Search code examples
unixshdash-shell

variable variables in sh or dash


The following code executes fine on bash.

sms="SMSFile"
email="EmailSubj"
for x in sms email; do echo variable \$$x=${!x}; done;

Output is

variable $sms=SMSFile
variable $email=EmailSubj

But I need to write it in sh NOT bash. if I execute same command in sh it gives me error

sh: 3: Bad substitution

This is due to ${!x}. I looked up the manual of sh which does not state anything about such parameter expansion. So sh does not support it I believe. If not how can use variable variables in sh


Solution

  • I don't think that you have any option but to use eval.

    The following:

    sms="SMSFile"
    email="EmailSubj"
    for x in sms email; do eval val=\$$x; echo variable \$$x=$val; done;
    

    should result in:

    variable $sms=SMSFile
    variable $email=EmailSubj
    

    in both sh and dash.