Tuesday, December 14, 2010

How can I check the number of command line arguments passed to my bash script?

I've written a bash script auto.shI want this script to accept few command line parameters like some file names or values etc and then use them in my script somewhere. 

Sol: So here is what I found to be useful:

if test $# -lt 2 ; then
  echo "Need 2 Arguments"
  exit 0

The above basically tests how many command line arguments have been passed. You can see that here it compares it with 2. So basically there are 2 arguments that are required.

$# -> Tells Number of arguments passed

To use the arguments:

$1                                         --> First argument 
$2 and so on.....                     --> Second argument

If you simply do an echo $1 and echo $2 it will print the command line arguments that you have passed to ./auto.sh.

No comments:

Post a Comment