Reputation: 691
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?
Upvotes: 0
Views: 49
Reputation: 786289
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
Upvotes: 0
Reputation: 782693
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"
Upvotes: 2