How can I make a bash string of command with redir

2020-04-11 06:33发布

I want to make a bash string of commands with redirect and/or pipe, and use it to either display the string of commands or execute the string of commands. A simple command without redirect or pipe works, but a string of commands with redirect or pipe does not. For example,

command="echo 1"
$command
echo "$command"

would display

1
echo 1

However,

command="echo 1 | cat"
$command
echo "$command"

would display

1 | cat
echo 1 | cat

but, I want

1
echo 1 | cat

Similarly for redirect,

command="echo 1 | cat > 1.out"
$command
echo "$command"

would display

1 | cat > 1.out
echo 1 | cat > 1.out

but I want

echo 1 | cat > 1.out

with a new file named "1.out" with content 1 in it.

Is there a way to achieve what I want?

1条回答
Juvenile、少年°
2楼-- · 2020-04-11 07:11

If you want the shell to evaluate the string as a command, tell it to do so:

eval "$command"
echo "$command"
查看更多
登录 后发表回答