1753725 Members
4398 Online
108799 Solutions
New Discussion юеВ

Re: scripting question

 
SOLVED
Go to solution
yap
Regular Advisor

scripting question

Hi,
How can I put argument as variable in script? Such as:

If first argument to a script is "Arg1". If I do

x=1
echo $($x)

Can I get "Arg1" to print out? I know this is not the correct way to do. Anyone can point out the right way? Thanks.

regards,
tenghin
19 REPLIES 19
Bernhard Mueller
Honored Contributor

Re: scripting question

Hi,

x=$1
echo $($x)

Regards,
Bernhard
Umapathy S
Honored Contributor

Re: scripting question

The arguments are passed as $n where n is 1, 2, 3...

You can capture them as $1, $2 etc. You can use them as any other variable.

echo $1

HTH,
Umapathy
Arise Awake and Stop NOT till the goal is Reached!
yap
Regular Advisor

Re: scripting question

Hi Bernhard,
Thanks for the reply. The reason I want to make the argument as variable is because sometime the position of argument can change, may be first argument, may be second. So I don't think your suggestion can work. Do you have other suggestion ?

regards,
tenghin
marc seguin
Regular Advisor
Solution

Re: scripting question

If your command is as "./myscript arg1", then you can get the value arg1 inside your script using $1 ($2, $3, ... for 2nd, 3rd,... parameters).

echo $1
=> arg1

If $arg1 is a parameter ($arg1=value1), then you can do :
eval echo \${$1}
=> value1

marc.
Umapathy S
Honored Contributor

Re: scripting question

Tenghin,
At some point you have to identify what that incoming argument means. At that same point you can assign them to your variable of choice.

I dont find any problem here.

HTH,
Umapathy
Arise Awake and Stop NOT till the goal is Reached!
yap
Regular Advisor

Re: scripting question

Hi Marc,
Thanks a lot. That is just what I want.

Umapathy,
Thanks for you reply also.


Thanks guys!!

regards,
tenghin
Bernhard Mueller
Honored Contributor

Re: scripting question

Hi Thenghin,

so I guess you want something like

./script -1 arg1 -2 arg2
would work exactly like
./script -2 arg2 -1 arg1

???

then you would use a case statement and use shift for each $1 to read each script argument sequentially and set variables according to whether -1 -2 etc have been found until you have gone through the whole command line.

Regards,
Bernhard

yap
Regular Advisor

Re: scripting question

Hi Bernhard,
Actually what I want is assign the second last argument to a variable, such as :

x=$#
y=`expr $x - 1`
h=`eval echo \${$y}`
echo $h


I can do "eval echo \${$y}" alone but cannot assign to variable h as above.Any idea anyone ?

regards,
tenghin
Umapathy S
Honored Contributor

Re: scripting question

Tenghin,
One way to do is to use the shift. Go on shifting till last but one.

HTH,
Umapathy
Arise Awake and Stop NOT till the goal is Reached!