简体   繁体   中英

echo command behaviour issue in bash

command="echo 'hello world' > file.txt";
$command;

And I'm expecting that it will write the "hello world" text to file.txt, But it prints the whole string as,

'hello world' > file.txt

What wrongs with my code?

After a variable is replaced, the result is only scanned for word splitting and wildcard expansion. Other special shell characters, such as quotes and redirection, are not processed. You need to use eval to reprocess it completely:

eval "$command"

You cannot store full command line in variables and execute like this.

Using this will work but is dangerous if command line is coming from users or from an external source:

bash -c "$command"

Safe approach is to store command in BASH array:

command=(echo 'hello world')

And execute it like this:

"${command[@]}" > file.txt

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