Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

Passing a string containing the name of a variable to a script

 
Highlighted
SwissKnife
Frequent Advisor

Passing a string containing the name of a variable to a script

Hi there,

 After hours of attempts I think that there is no solution to this tricky problem ! really no ideas !

here is my script myscript.ksh
     #I need to redefine AA inside the script itself
     cmd=$1
     AA="Orange"
     echo $cmd

 


output of the command below
AA=""
./myscript.ksh "This is the new value ${AA}"
should be:
This is the new value: Orange

But because of the evalutation of the parameter result is:
This is the new value:

 

How to do the trick !??

 

kind regards,

Den.

2 REPLIES
Bill Hassell
Honored Contributor

Re: Passing a string containing the name of a variable to a script

Are you trying to set the command line parameter $1?
If so, look at the exec command that can restart your script with new values.
Or the eval command to take any string and process it as a shell command.



Bill Hassell, sysadmin
Steven Schweda
Honored Contributor

Re: Passing a string containing the name of a variable to a script

> How to do the trick !??

> ./myscript.ksh "This is the new value ${AA}"

   With quotation marks ("), the (interactive) shell evaluates "${AA}"
immediately, and the script never sees "AA".  Usig apostrophes (') would
help.  Consider:

pro3$ AA=fred

pro3$ cat script1.sh
#!/bin/sh
cmd=$1
AA='Orange'
echo "$cmd"
eval "echo \"$cmd\""


pro3$ ./script1.sh "New value:  ${AA}"
New value:  fred
New value:  fred

pro3$ ./script1.sh 'New value:  ${AA}'
New value:  ${AA}
New value:  Orange