当用变量指定其 shell 命令时,xargs 调用失败
xargs call fails when its shell command is specified with a variable
我需要一个变量 shell 命令用于 xargs 调用。
... xargs -I {} sh -c 命令 ...
我发现 xargs 在命令为 'literal' 时有效,但在我通过 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)
尝试
echo 'abcd1234' | xargs -I {} sh -c "$command"
注意:我已经从命令中删除了 -n 1
,因为它与 -I
相矛盾,这意味着 逐行 处理.
您没有在命令替换 $(...)
周围使用双引号,这使得 shell 应用分词(按空格分成标记),这意味着 多个 参数放在 -c
选项之后,而不是 单个 命令字符串。
除此之外,无需涉及命令替换:直接使用 - 双引号 - 变量 ("$command"
) 就足够了。
我需要一个变量 shell 命令用于 xargs 调用。
... xargs -I {} sh -c 命令 ...
我发现 xargs 在命令为 'literal' 时有效,但在我通过 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)
尝试
echo 'abcd1234' | xargs -I {} sh -c "$command"
注意:我已经从命令中删除了 -n 1
,因为它与 -I
相矛盾,这意味着 逐行 处理.
您没有在命令替换 $(...)
周围使用双引号,这使得 shell 应用分词(按空格分成标记),这意味着 多个 参数放在 -c
选项之后,而不是 单个 命令字符串。
除此之外,无需涉及命令替换:直接使用 - 双引号 - 变量 ("$command"
) 就足够了。