在Bash脚本中将带有空格的outputstring赋值给变量

时间:2016-03-18 15:41:58

标签: bash

我想输入一个带有几个管道到var的命令输出。我写的代码看起来像这样:

curl https://www.gentoo.org/downloads/signatures/ | grep 0x | cut -d '>' -f3 | cut -d '<' -f1  |  while read line; do
gpg --recv-keys $line
tempfingerprint= `gpg --fingerprint $line | head -2 | tail -1 | cut -d'=' -f2 | cut -d ' ' -f2-12`
echo $tempfingerprint

当我尝试回显结果(最后一行代码行)时,我收到错误消息。我调试了它,这是调试日志:

336 + head -2
336 + tail -1
336 + cut -d= -f2 
336 + cut -d ' ' -f2-12 
336 + gpg --fingerprint 0xBB572E0E2D182910
36 + tempFingerPrint= 36 + 13EB BDBE DE7A 1277 5DFD B1BA BB57 2E0E 2D18 2910 
./gentoo-stage.sh: line 36: 13EB: command not found

如何将所有指纹分配给变量?

1 个答案:

答案 0 :(得分:2)

=之后还有一个空格:

tempfingerprint= `gpg --fingerprint $line | head -2 | tail -1 | cut -d'=' -f2 | cut -d ' ' -f2-12`
#               ^

导致错误的原因是将其删除。

此外,它不是必需的,但您应该更喜欢"$(...)"而不是`...`,因为它更安全,更容易阅读:

tempfingerprint="$(gpg --fingerprint $line | head -2 | tail -1 | cut -d'=' -f2 | cut -d ' ' -f2-12)"

而且,一般来说,总是引用你的变量扩展。

相关问题