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.

Executing a Shell script

Its very useful and handy thing to know different ways to execute shell script. Find out how by the below

Description : Lets have a shell script "test.sh" with code as shown below:

#!/bin/bash

export STRING="Hello Mate" # Intialization of a string variable.

Now, consider the below scenario

Scenario 1) :
--> Excute the below steps on your command line:
$ ./test.sh
$ echo $STRING

--> Output: The command "echo $STRING" would give you empty string.

Scenario 2) :
--> Excute the below steps on your command line:
$ . ./test.sh <<< See the difference in executing w.r.t scenario 1
$ echo $STRING

--> Output: The command "echo $STRING" would give you "Hello Mate".

Reason: The fact is in first scenario, the shell script gets executed in its child shell, due to which the variables set by the script is lost in the parent shell once the shell script is executed in child shell and returns to the parent shell.
This is overcome in second scenario, in this scenario the shell script is executed in the parent shell itself, due to which all the variables set are not lost.

All this happened because the way of executing Shell script differed in the Scenario 1 and Scenario 2.





Getting Started.............:)

Well, i surely wont be starting off this blog giving out Unix commands and gyans(lectures), i am sure there are hell lot of books and websites which would help you to get started.



And one such book i would personally suggest is "UNIX by Sumithaba Das". Its really good for starters who take there first step towards UNIX.