Saturday, April 11, 2009

Command writing, command line arguments in shell script

Command writing inside shell script
Unlike any other scripting language or programming language a statement inside shell script need not to be ended with semicolon (;).
If you press newline(i.e enter button from your keyboard) after a statement then shell script automatically determines another statement.
However, if you want to include two statements in one line then you have to separate by them by comma(;).

# vi t_sep.sh
ls -l;pwd

# chmod +x t_sep.sh

# ./t_sep.sh

total 36
-rwxr-xr-x 1 root root 67 Apr 10 03:00 echo.sh
drwxr-xr-x 2 root root 4096 Apr 11 09:08 practice
-rwxr-xr-x 1 root root 106 Apr 10 11:06 quote.sh
-rwxr-xr-x 1 root root 104 Apr 11 04:30 read.sh
-rwxr-xr-x 1 root root 177 Apr 10 03:33 test_echo.bash
-rwxr-xr-x 1 root root 325 Apr 6 10:45 test_echo.sh
-rwxrwxrwx 1 root root 569 Apr 6 12:23 test_user.txt
-rwxr-xr-x 1 root root 41 Apr 9 07:48 test_v.sh
-rwxr-xr-x 1 root root 10 Apr 11 11:37 t_sep.sh
/home/arju/test
See after ls -l command, pwd command is executed.

Command line Arguments and $#,$@,$*,$0
Whenever you run script you can pass arguments to the script from command line. Those command line arguments can tracked.

With $# you can count the number of arguments specified on command line. Number count (starts from 1) is the total number of arguments except shell script name.

With $@ or $* you can refer to the argument of the command line.

With $0, $1 , $2 etc. you can access the first argument, second argument, third argument corresponds on the command line. Note that, $0 indicates the shell script name that is specified first while tunning shell script.

# cat command.sh
echo -n 'The list of arguments $*:'
echo $*
echo -n 'The number of arguments $#:'
echo $#
echo -n 'The list of arguments $@:'
echo $@
echo -n 'First Argument $0:'
echo $0
echo -n 'Second Argument $1:'
echo $1
echo -n 'Third Argument $2:'
echo $2

# chmod +x command.sh

# ./command.sh first second 100

The list of arguments $*:first second 100
The number of arguments $#:3
The list of arguments $@:first second 100
First Argument $0:./command.sh
Second Argument $1:first
Third Argument $2:second
Related Documents

No comments:

Post a Comment