简体   繁体   中英

Echo within bash subshell

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM