Friday, June 8, 2007

Accessing the 10th and beyond command line parameter.

Yes, we all know about command line parameters in Shell scripting. These are accessed using $1, $2 and so on.

but what happnes after $9 ?? , see the below example.

Below is simple Shell script code, lets name it as "test.sh", this is supposed to give me value of 10th command line parameter.

#!/bin/bash
echo $9
echo $10

Now, lets execute it as show:
$ ./test.sh A B C D E F G H I J K L M N O ---- Am sending 15 command line parameters.

Output :
I ---- as expected
A0 ---- expected "J"

well, one way is surely using shift(refer any UNIX book, to know how this works) command in shell script code. But imagine trying to access the 20th or 25th command line parameter. How, many shift command would give in your Shell script code ?

Solution : Damn simple, below is how we can write our code.

#!/bin/bash
echo ${10} # So, anything above 9th parameter, use the "{}".

Reason : The shell understands the "$10" as "$1" and "0" and hence enclosing it in curly braces would solve the problem.

No comments: