Linux Shell Scripting Tutorial (LSST) v1.05r3 | ||
Chapter 2: Getting started with Shell Programming | ||
|
Let's take rm command, which is used to remove file, but which file you want to remove and how you will tail this to rm command (even rm command don't ask you name of file that you would like to remove). So what we do is we write command as follows:
$ 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 |
Following script is used to print command ling argument and will show you how to access them:
Run it as follows
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"
| ||
Command Line Processing | Redirection of Standard output/input i.e.Input - Output redirection |