Friday 4 October 2013

Navigating through the arguments of a shell script while executing

 How to get access to the arguments we pass while executing a shell script  
   In the shell script myscript.sh we write
  
   #!bin/bash
  
   while [ -n "$1" ]
   do
     echo "$1"
     shift
   done
  
   output of the shell script when its argument are like this
  
   myscript.sh first comes nation then family
  
   first
   comes
   nation
   then
   family
  
   shift actually takes the next argument from $1 to $2 then to $3 and so on.
   -n "$1" checks whether the value is non zero. When there is no more argument
   -n "$1" return false and the loop end.
  
   You can also write the condition like this.
  
   while [ ! -z "$1" ]
  
   -z check whether the value of "$1" is zero so when there is argument -z "$1" returns false
   so when it is prefixed by ! its return true.
  
   Using for loop instead of while loop
  
   As $1, $2, $3 returns consecutive arguments, $@ return all the arguments in a sentence separated
   by space so if write a for loop like this
  
   for arg in "$@" - here arg takes one word from the sentence $@ for each iteration
   The full script is like this
  
   for arg in "$@"
   do
   echo "$@"
   done

No comments: