- Telling the command/utility which option to use.
- Informing the utility/command which file or group of files to process (reading/writing of files).
$ rm {file-name}
Here rm is command and filename is file which you would like to remove. This way you tail rm command which file you would like to remove. So we are doing one way communication with our command by specifying filename Also you can pass command line arguments to your script to make it more users friendly. But how we access command line argument in our script.
Lets take ls command
$ Ls -a /*
This command has 2 command line argument -a and /* is another. For shell script,
$ myshell foo bar
Shell Script name i.e. myshell
First command line argument passed to myshell i.e. foo
Second command line argument passed to myshell i.e. bar
In shell if we wish to refer this command line argument we refer above as follows
myshell it is $0
foo it is $1
bar it is $2
Here $# (built in shell variable ) will be 2 (Since foo and bar only two Arguments), Please note at a time such 9 arguments can be used from $1..$9, You can also refer all of them by using $* (which expand to `$1,$2...$9`). Note that $1..$9 i.e command line arguments to shell script is know as "positional parameters".
Exercise
Try to write following for commands
Shell Script Name ($0),
No. of Arguments (i.e. $#),
And actual argument (i.e. $1,$2 etc)
$ sum 11 20
$ math 4 - 7
$ d
$ bp -5 myf +20
$ Ls *
$ cal
$ findBS 4 8 24 BIG
Answer
Shell Script Name | No. Of Arguments to script | Actual Argument ($1,..$9) | ||||
$0 | $# | $1 | $2 | $3 | $4 | $5 |
sum | 2 | 11 | 20 | |||
math | 3 | 4 | - | 7 | ||
d | 0 | |||||
bp | 3 | -5 | myf | +20 | ||
Ls | 1 | * | ||||
cal | 0 | |||||
findBS | 4 | 4 | 8 | 24 | BIG |
Set execute permission as follows:
$ chmod 755 demo
Run it & test it as follows:
$ ./demo Hello World
If test successful, copy script to your own bin directory (Install script for private use)
$ cp demo ~/bin
Check whether it is working or not (?)
$ demo
$ demo Hello World
NOTE: After this, for any script you have to used above command, in sequence, I am not going to show you all of the above command(s) for rest of Tutorial.
Also note that you can't assigne the new value to command line arguments i.e positional parameters. So following all statements in shell script are invalid:
$1 = 5
$2 = "My Name"
Example for Summation program
# # summation # echo "sum of $1,$2 = `expr $1 + $2` $chmod 755 sum $./sum 5 6 sum of 5,6 = 11 |
No comments:
Post a Comment