【问题标题】:xargs call fails when its shell command is specified with a variable当使用变量指定其 shell 命令时,xargs 调用失败
【发布时间】: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)

【问题讨论】:

    标签: shell variables xargs


    【解决方案1】:

    试试

    echo 'abcd1234' | xargs -I {} sh -c "$command"
    

    注意:我已经从命令中删除了-n 1,因为它与-I 相矛盾,这意味着逐行处理。

    您没有在命令替换 $(...) 周围使用双引号,这使得 shell 应用分词(通过空格拆分为标记),这意味着 多个 参数放在 @ 之后987654325@ 选项而不是单个命令字符串。

    除此之外,无需涉及命令替换:直接使用 - 双引号 - 变量 ("$command") 就足够了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      相关资源
      最近更新 更多