Unix shell: executable files and command line parameters
Example1: putting commands in a file and making it executable
$date Fri Oct 20 09:17:37 EDT 2017 $d=`date` $echo $d Fri Oct 20 09:17:48 EDT 2017 $date Fri Oct 20 09:21:45 EDT 2017 ~$echo $d Fri Oct 20 09:17:48 EDT 2017Notice how the value of $d doesn't change as time passes. $cat dprog d=`date` echo $dNow let's put those two commands in a file called dprog $ls -l dprog -rw-r--r--. 1 SRUNET\david.dailey SRUNET\faculty 17 Oct 20 09:24 dprog ~$chmod +x dprog ~$ls -l dprog -rwxr-xr-x. 1 SRUNET\david.dailey SRUNET\faculty 17 Oct 20 09:24 dprogAnd let us change the permissions on the file dprog so that it is executable. ~$./dprog Fri Oct 20 09:27:34 EDT 2017 ~$./dprog Fri Oct 20 09:27:41 EDT 2017Now I may run the program dprog again and again with different values of $d being assigned (internally) each time. $echo $d Fri Oct 20 09:17:48 EDT 2017Note, however, that the value of the variable $d, outside the program (in the shell, itself) remains unchanged.
For a given executable command file, named, for example, "thiscommand"
running the command as follows:
./thiscommand string1 string2 string3
(in which string1, string2, etc. are separated by spaces) results in the strings being passed into the command file as input parameters, usable by the program by the variable names: $1, $2, $3, etc.
Example2:
$cat params echo $1 echo and now the second parameter: $2 echo the total number of parameters is $# echo some others are $3,$4,$5,and $6 $./params here are some various parameters 6 7 8 9 10 11 12 here and now the second parameter: are the total number of parameters is 12 the others are some,various,parameters,and 6
Example3:
$cat params echo $1 echo and now the second parameter: $2 echo the total number of parameters is $# echo some others are $3,$4,$5,and $6 $./params here are some various parameters 6 7 8 9 10 11 12 here and now the second parameter: are the total number of parameters is 12 the others are some,various,parameters,and 6
Example4:
$cat params echo $1 echo and now the second parameter: $2 echo the total number of parameters is $# echo the others are $3,$4,$5,$6,$7,$8,$9,$10,$11 for i in $@ do echo $i done $./params here are some various parameters 6 7 8 9 10 here and now the second parameter: are the total number of parameters is 10 the others are some,various,parameters,6,7,8,9,here0,here1 here are some various parameters 6 7 8 9 10
Special parameters:
$# is the shell variable referring to the number of such parameters.
$0 is the name of the command itself.
$@ is the list of all parameters.
$? is the status of the last shell command -- it returns a value of 0 if the command terminates properly.