akhil.cs
akhil.cs

Reputation: 691

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?

Upvotes: 0

Views: 49

Answers (2)

anubhava
anubhava

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

Barmar
Barmar

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

Related Questions