我有一个命令需要在shell脚本中重复使用。这个命令包含一个管道,整个命令的输出将通过管道输出到其他命令。
e.g。让我们说,为简单起见,命令是ls | tee
。然后我可以将它传递给其他命令,ls | tee | someprogram
或ls | tee | anotherprogram
。
所以很自然地我想保持ls | tee
是一个变量。问题是我似乎无法使用管道执行变量。
#!/bin/sh
TEST="ls | tee"
$TEST
提供以下输出
ls: cannot access |: No such file or directory
ls: cannot access tee: No such file or directory
如何执行上面的$TEST
变量,whist能否将输出传递给其他命令?
答案 0 :(得分:4)
简短回答是eval
。
eval $TEST somefile
eval $TEST otherfile | more
但是,您需要注意eval
表示引用特殊字符和空格等问题。如果一切都很简单(TEST="ls -l | tee"
),那么很容易。如果你在参数或shell元字符中有空格,那么很难 - 很难 - 做得对。那时,您最好创建一个函数或单独的shell脚本。
即使如此,使用函数或shell脚本也可能会更好。
如果您eval
的字符串来自用户,则必须更加担心!