【问题标题】:Bash command fails with bash -c but works in an interactive shellbash 命令因 bash -c 失败,但在交互式 shell 中工作
【发布时间】:2019-03-19 01:44:06
【问题描述】:

我有这个相当简单的命令,当在 bash 中运行时,将剩余的磁盘空间输出到stdout

echo -n "External1TB: $(grep -Poi '(\/mnt\/External1TB\s+)\K(.*)' <(df -H --output=target,avail))B"

我使用进程重定向&lt;()df 的输出通过管道传输到grep,然后处理输出并过滤掉剩余的空间。所有这些都包裹在一个子shell $() 中并馈送到echo,因此我可以在输出前加上磁盘名称。

示例输出:External1TB: 882GB

在交互式 bash shell 中运行时效果相当好,但是如果我尝试使用 bash -c 运行它,如下所示:

bash -c "echo -n "External1TB: $(grep -Poi '(\/mnt\/External1TB\s+)\K(.*)' <(df -H --output=target,avail))B"",

输出始终为:External1TB:。似乎grepdf 由于某种原因失败了。

我做错了什么?

【问题讨论】:

    标签: bash io-redirection quoting subshell


    【解决方案1】:

    您对内部部分的引用需要转义:

    bash -c "echo -n \"External1TB: $(grep -Poi '(\/mnt\/External1TB\s+)\K(.*)' <(df -H --output=target,avail))B\"",
    

    或者,考虑将其中的至少一部分放入函数或脚本中,这样您就不需要在字符串转义时堆叠字符串转义。

    【讨论】:

      猜你喜欢
      • 2015-02-19
      • 2016-02-18
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 2013-04-16
      • 1970-01-01
      相关资源
      最近更新 更多