Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a bash string of command with redirect and pipe?

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?

like image 591
Sangcheol Choi Avatar asked Mar 22 '23 00:03

Sangcheol Choi


1 Answers

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

eval "$command"
like image 124
William Pursell Avatar answered Apr 10 '23 09:04

William Pursell