【发布时间】:2016-02-26 15:08:35
【问题描述】:
我需要在 xargs 调用中使用可变 shell 命令。
... xargs -I {} sh -c 命令 ...
我发现 xargs 在命令为“文字”时有效,但在我通过 shell 变量指定时失败。
有解决此问题的建议吗?
下面是示例代码。
## xargs call with literal shell command
# works; creates file abcd1234.txt containing string 'abcd1234'
echo 'abcd1234' | xargs -I {} -n 1 sh -c 'echo {} | grep "\d" > {}.txt'
## xargs call with variable as shell command
# create shell command to give to xargs
cmd1='echo'
cmd2='grep "\d"'
command=${cmd1}' {} | '${cmd2}' > {}.txt'
# returns the literal command that works: echo {} | grep "\d" > {}.txt
echo $command
# fails
echo 'abcd1234' | xargs -I {} -n 1 sh -c $(echo $command)
【问题讨论】: