0

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
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116

1 Answers1

5

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.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • I was searching for the link on wooledge.org until I realized that you all ready posted it :-) – Andreas Louv Mar 21 '16 at 17:28
  • Ok, thanks for the feedback. Incidentally, it appears that this works: `echo $cmd | bash` – Samir Nagheenanajar Mar 22 '16 at 13:22
  • @SamirNagheenanajar No that doesn't work. It "works". Sometimes. For some inputs. In some cases. And is *still* a dangerous and bad idea. Seriously, don't do this sort of thing if you can **possibly** avoid it. – Etan Reisner Mar 22 '16 at 13:33