How do I call echo from within a bash subshell? This is behavior I want:
# w=5
# echo $w > /tmp/x
# cat /tmp/x
5
But:
# cmd="echo $w > /tmp/x"
# $cmd
5 > /tmp/x
And:
# $( $cmd )
bash: 5: command not found
How do I call echo from within a bash subshell? This is behavior I want:
# w=5
# echo $w > /tmp/x
# cat /tmp/x
5
But:
# cmd="echo $w > /tmp/x"
# $cmd
5 > /tmp/x
And:
# $( $cmd )
bash: 5: command not found
Your problem is not echo
.
Your problem is the redirection. You can't put redirection inside a string.
That's why you get echo
outputting 5 > /tmp/x
in your first attempt.
The problem with your second attempt is that you "lose" the echo
by the time the $()
tries to run the output (because as your first attempt shows your output from $cmd
is 5 > /tmp/x
which isn't a valid command.
That said this is Bash FAQ 050 so stop trying to put commands in variables. It doesn't work.