Command Line Arguments
|
NOTE: Variable $# holds number of arguments specified on command line and $* or $@ refer to all arguments passed to script.
Exercise:Try to determine command and arguments from following commands
|
| Command | No. of argument to this command (i.e $#) | Actual Argument |
| cd | 1 | .. |
| Ls | 4 | foo& -l, -a ,-r |
| Cp | 2 | y and y.bak |
| mv | 3 | -v , & bot1.txt bot2.txt |
| date | 0 | |
| clear | 0 |
Command Line arguments in Scripting
| #!/bin/bash
#arguments.sh #Script illustrating use of positional parameters echo “The name of the program is $0” echo “The first argument is $1” echo ”The second argument is $2” echo “The number of arguments are $#” echo “They are $*” exit 0 |
| TERMINAL àEXECUTION OF SCRIPT
$ bash arguments.sh test1 test2 The name of the program is arguments.sh The first argument is test1 The second argument is test2 The number of arguments are 2 They are test1 test2 |
Example:
| #!/bin/bash
#arguments1.sh #Practical example # Read a file but give the name of file externally using parameter #The file should be in the directory of shellscript arguments1.sh #Script illustrating use of positional parameters echo “The name of the program is $0” echo “The first argument is $1” cat $1 exit 0 |
| TERMINAL àEXECUTION OF SCRIPT
$ bash arguments1.sh [file_name] The name of the program is arguments1.sh The first argument is [file_name] |
