This might be a question of eval command, but anyway, I'm having a hard time to understand the syntax of /bin/sh indirect reference. I usually write bash scripts, ${!val} way, so I wasn't thinking much about it, but I'm writing /bin/sh specific code now and I wonder.

I understand we can write indirect reference something like this. (The sample code works like a flipflop)

interface=wlan1 #this value would be fed by an external env value
eval gateway=\$$interface
echo $(eval "echo \$$interface")
g=$(eval "echo \$$interface")
echo $gateway $g

My question is, why can't we simply write like

gateway=$(eval \$$interface)
echo $(eval \$$interface)

But, it has to be assigned to a variable or echo'd, then entier line must be eval'd, like my sample

eval gateway=\$$interface
echo $(eval "echo \$$interface")
g=$(eval "echo \$$interface")

My guess is, it doesn't work like a pointer as I expected, but eval might need an actual variable space to construct the value, but then I wonder what's "echo ..." is actually doing.

Could someone give me an insight for better understanding?

  • 3
    Those command substitutions $(...) are absolutely useless and slower, as they have to fork an extra process; instead of echo $(eval "echo \$$interface"), write it "simply" as eval echo \$$interface, And unless you can control the content of $interface, you should take care with the whole IFS split + glob + "special characters interpreted by echo" mess. – mosvy Jan 3 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.