Bash 分配给变量的命令保持为空

Bash command assigned to variable stays empty

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; "







$~

我已经尝试了它的多种变体,但无法弄清楚我错在哪里。有人可以发现问题吗?

谢谢!

您需要为 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; '

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

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

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

_ 是一个伪参数,用于在 shell.

中设置 [=17=]