DATE1=`perl -e 'use POSIX qw(strftime); print strftime "%Y-%m-%d",localtime(time()- 3600*72);'`
DATE2=`perl -e 'use POSIX qw(strftime); print strftime "%Y%m%d",localtime(time()- 3600*72);'`
DATE3=`perl -e 'use POSIX qw(strftime); print strftime "%Y%m%d",localtime(time()- 3600*48);'`
DATE4=`perl -e 'use POSIX qw(strftime); print strftime "%Y/%m/%d",localtime(time()- 3600*48);'`
Below is my shell script(test1.sh), in which I need to print four dates and all those four dates should come from above. Meaning I need to pass above those four dates from the command prompt only to the below shell script.
#!/bin/bash
echo Date1
echo Date2
echo Date3
echo Date4
So when I am running the shell script like this- it should get Date1, Date2, Date3, Date4 from the above four dates?
sh -x test1.sh Date1 Date2 Date3 Date4
Is it possible to do in shell script?
If you execute your first code-block in a shell, then you'll have defined 4 variables with the output of those commands. To access any of those variables, you have to prepend a $
to the variable name - say, $DATE1
.
So, for running your script with those parameters, you should run:
bash -x test1.sh $DATE1 $DATE2 $DATE3 $DATE4
Pay attention to the $
and the case-sensitiveness.
Finally, in your script, arguments are received in a family of variables that are called with the number of order of the parameter. So, your first parameter is retrieved by $1
, the second by $2
, and so on.
So, your script ends up being:
#!/bin/bash
echo $1
echo $2
echo $3
echo $4
Watch also that you are defining a she-bang that tells the script to be interpreted by bash
, but your previous invocation was using sh
. They have lots of compatibilities, but they are not the same.
You only need to reference the global argument variables if passing via perl.
#!/bin/bash
echo "$1" # Date1
echo "$2" # Date2
echo "$3" # Date3
echo "$4" # Date4
else you can open a sub-shell using $()
to return the result
> echo $(date "+%Y-%m-%d")
2012-11-20