0

I read a similar example from bash programming book:

$ cat indirection 
#!/usr/bin/env bash

set -x
num=1
eval "${!num#*:}"
$ 

When I execute the script with bash indirection "test:echo blah", then how is the last line of the script processed? I guess first the indirection happens so that eval "${!num#*:}" becomes eval "${1#*:}"? Then substring removal takes place and eval "${1#*:}" becomes eval echo blah? If yes, then why is eval needed, i.e ${!num#*:} instead of eval "${!num#*:}" would provide the same results?

3

The output of the parameter expansion is:

$ echo "${1#*:}"
echo blah

Well, yes, in this specific case:

$ set -- "test:echo blah"
$ eval "${1#*:}"
blah

$ ${1#*:}
blah

Execute the same command. But that is not always true:

$ "${1#*:}"
bash: echo blah: command not found

In fact, an string that contains shell meta characters will not work correctly even if unquoted.

$ set -- "test:echo blah > file"
${1#*:}
blah > file

The redirection did not happen, but (beware that a file will be created):

$ eval "${1#*:}"

Will create a file called file in the PWD.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.