Reputation: 6405
In bash, why do I have to eval
a variable whose value is a redirection:
bash> foo=echo
bash> $foo true
true
bash> foo='>/dev/null'
bash> $foo true
bash: >/dev/null: No such file or directory
bash> eval $foo true
bash>
How to do this without eval
?
Upvotes: 0
Views: 180
Reputation: 75618
Redirections are simply not parsed after word splitting with a variable. Only pathname expansion and similar stuffs are recognized.
With your example, >/dev/null
is treated literally there as if you ran:
">/dev/null" "false"
In which case, >
doesn't have a special meaning.
That is the reason why eval
is needed to re-evaluate the resulting arguments as a new command. Whatever you see with echo
is what you get with eval
.
# foo='>/dev/null'
# echo $foo true
>/dev/null true
So sometimes you also need to quote to prevent word splitting and other expansions before evaulation:
echo "$foo true"
Upvotes: 3
Reputation: 2170
eval
means evaluate, telling the shell to evaluate (or perform) the expression inside the quotes. Otherwise it's regarded as just a literal string, likely only having meaning to the user.
If you provide more detail in your question, I might be able to help with alternative approaches.
Upvotes: 0