I have a command that I need to use repeatedly within a shell script. This is command contains a pipe and the output of the whole command will be piped to other commands.
e.g. Let’s say for simplicity sake the command is ls | tee. Then I might pipe it to other commands, says ls | tee | someprogram or ls | tee | anotherprogram.
So naturally I’ll want to keep ls | tee is a variable. The problem is that I can’t seem to execute a variable with a pipe in it.
#!/bin/sh
TEST="ls | tee"
$TEST
Gives the following output
ls: cannot access |: No such file or directory
ls: cannot access tee: No such file or directory
How do I execute a variable like $TEST above, whist being able to pipe the output to other commands?
The short answer is
eval.However, you need to be aware that
evalmeans problems with quoting special characters and blanks and the like. If everything is simple (TEST="ls -l | tee"), then it is easy. If you have spaces in arguments or shell metacharacters, then it is hard — very hard — to do it right. At that point, you’d be better off creating a function or separate shell script.You might well be better off with a function or shell script even so.
If the string you
evalcomes from a user, you have to worry even more!