views:

69

answers:

5

i have unix shell script which is need to be run like below

test_sh XYZ=KLMN

the content of the script is

#!/bin/ksh

echo $XYZ

for using the value of XYZ i have do set -k before i run the script.

is there a way where i can do this without doint set -k before running the script. or is there something that i can do in the script where i can use value of the parameter given while running the script in the below way

test_sh XYZ=KLMN

i am using ksh. Any help is appreciated.

A: 

It looks like you are trying to use the environment variable "INSTANCE" in your script.

For that, the environment variable must be set in advance of executing your script. Using the "set" command sets exportable environment variables. Incidentally, my version of ksh dates from 1993 and the "-k" option was obsolete back then.

To set an environment variable so that it is exported into spawned shells, simply use the "export" command like so:

export INSTANCE='whatever you want to put here'

If you want to use a positional parameter for your script -- that is have the "KLMN" value accessed within your script, and assuming it is the first parameter, then you do the following in your script:

#!/bin/ksh

echo $1

You can also assign the positional parameter to a local variable for later use in your script like so:

#!/bin/ksh

param_one=$1
echo $param_one

You can call this with:

test_sh KLMN

Note that the spacing in the assignment is important -- do not use spaces.

Peter Degen-Portnoy
+3  A: 

How about running this?

XYZ=KLMN ./test_sh //running from directory where test_sh is
Aviator
synonym for using the external /usr/bin/env, which is shell neutral: env XYZ=KLMN ./test.sh
dz
contraint is i have to run the script in this way only test_sh XYZ=KLMN
Vijay Sarathi
+3  A: 

If your script needs no other arguments, a quick and dirty way do to it is to put

eval "$@"

at the start of your script. This will evaluate the command line arguments as shell commands. If those commands are to assign a shell/environment variable, then that's what it will do.

It's quick-and-dirty since anything could be put on the command line, causing problems from a syntax error to a bad security hole (if the script is trusted).

I'm not sure if "$@" means the same in ksh as it does in bash - using just $* (without quotes) would work too, but is even dirtier.

camh
+1 I think in this case a simple eval $1 will do
Alexander Pogrebnyak
A: 

I am tring this option

#!/bin/ksh

echo $1
awk '{FS="=";print $2}' $1

and on the command line

test_sh INSTANCE=LSN_MUM

but awk is failing.is there any problem over here?

Vijay Sarathi
That's treating `$1` as a file name. You should echo it through a pipe to awk instead.
Dennis Williamson
A: 

Probably #!/bin/ksh -k will work (untested).

glenn jackman