【问题标题】:Bash command assigned to variable stays empty分配给变量的 Bash 命令保持为空
【发布时间】:2016-11-10 20:47:19
【问题描述】:

xargs 之后,我很少有命令相互跟随。有趣的是,如果只是将其回显到stdout,该命令就可以正常工作。当我尝试将其分配给变量时,该变量保持为空。见下文:

$~ ./somescript | grep -f fc.samples  | xargs -I {} sh -c "echo {} | tr '/' '\t' | cut -f9;"
sample1
sample2
sample3
sample4
sample5
sample6
sample7
sample8
$~

尝试将其分配给一个变量,然后回显它会导致空行:

$~ ./somescript | grep -f fc.samples  | xargs -I {} sh -c "sample=$(echo {} | tr '/' '\t' | cut -f9); echo $sample; "







$~

我已经尝试了它的多种变体,但无法弄清楚我做错了什么。有人能发现问题吗?

谢谢!

【问题讨论】:

  • 你试过这个吗? sample=$(./somescript | grep -f fc.samples | xargs -I {} sh -c "echo {} | tr '/' '\t' | cut -f9;")
  • 不,我没有 - 分配给 sample 的想法是供以后在 xargs 命令中使用 - 我认为这对我来说行不通;)

标签: linux bash shell variables xargs


【解决方案1】:

您需要为sh -c 命令转义$ 字符,否则$( )$sample 部分将由当前shell 而非sh -c 处理。

... | xargs -I {} sh -c "sample=\$(echo {} | tr '/' '\t' | cut -f9); echo \$sample; "

或者您可以考虑使用单引号作为外部引用。

... | xargs -I {} sh -c 'sample=$(echo {} | tr "/" "\t" | cut -f9); echo $sample; '

【讨论】:

  • 太棒了!引用切换...感谢您的帮助 - 正确!
【解决方案2】:

最好将参数传递给 sh,而不是尝试通过嵌入结果来动态创建shell命令。 (此外,除非tr 的目的是在像foo/bar\tbaz 这样的字符串中创建附加 字段,否则您可以告诉cut 使用/ 作为字段分隔符,而不是使用选项卡的默认值。)

# script='sample=$(echo "$1" | cut -d / -f9); echo "$sample"'

script='sample=$(echo "$1" | tr '/' '\t' | cut -f9); echo "$sample"'
./somescript | grep -f fc.samples  | 
  xargs -I {} sh -c "$script" _ {}

_ 是一个虚拟参数,用于在 shell 中设置 $0

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 2012-07-16
    • 2014-02-26
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    相关资源
    最近更新 更多