Shell Scripting - part 2

Command Line Arguments
-------------------------------
Here we will discuss some more about command line arguments( values passed along with script like flags in commands)
and how they can be accessed in script

1)Name of the program
The name of the program is stored in variable '0'
So the value can be accessed as ${0}
e.g:- vi file1.sh
---------------------------------------------------------------------
#!/bin/bash
echo ${0}
---------------------------------------------------------------------
The output of the program will be like
./file.sh
2)All arguments passed along with script
All values passed to the script(command line arguments) will be stored in variable '@'
So the value can be accessed as ${@}
e.g:- vi file2.sh
---------------------------------------------------------------------
#!/bin/bash
echo ${0}
---------------------------------------------------------------------
If you execute the script with out any arguments,there will be no output
So to verify the script ,execute with some arguments like

root@localhost]#./file2.sh a b c

The output of the program will be like
a b c
3) Number of command line arguments
Number of arguments passed to the program will be stored in variable '#'
So the value can be accessed as ${#}
e.g:- vi file3.sh
---------------------------------------------------------------------
#!/bin/bash
echo ${#}
---------------------------------------------------------------------
If you execute the script with out any arguments,there will be no output
So to verify the script ,execute with some arguments like

root@localhost]#./file2.sh a b c

The output of the program will be like
3
4) PID of shell executing the script
variable that will store PID of shell executing will be on $ or _
So the value can be accessed as ${$} or ${_}
The PID of shell executing will depend on how you execute the program

The script can be executed in two way
a) on current shell
e.g:-
root@localhost]#. file3.sh
5388
b) on a separate shell
root@localhost]#./file3.sh
5344

On e.g (a) the PID displayed will be the PID of current shell
You can verify it using 'ps' command
root@localhost]#ps
PID TTY TIME CMD
5388 pts/0 00:00:00 bash
5464 pts/0 00:00:00 ps
5) Command line arguments
So finally we are on the actual arguments
The values that are passed to the script for processing

The values start with 1

e.g:- vi file4.sh
---------------------------------------------------------------------
#!/bin/bash
echo ${1}
echo ${2}
echo ${3}
---------------------------------------------------------------------
Execute the program with some arguments

root@localhost]#./file4.sh a b c
a b c

Thats for Now we will continue with more on coming posts

Comments

Popular posts from this blog

How to Configure YUM in RHEL6

How to Configure Squid with Mysql DB authentication

HMC vtmenu exit