问题描述
上下文:我正在制作一个 shell 函数,以更人性化的方式输出 git rev-list
信息(灵感来自 this answer)。
但我因无法解释的意外行为而受阻。这是一个插图:
REVLIST="$(git rev-list --left-right --count main...fix/preview-data)"
# just to check what the variable contains
$echo \"$REVLIST\" # outputs "57 0"
# This is the unexpected behavior: cut didn't work
echo $(echo "$REVLIST" | cut -d " " -f 6) commits ahead.
# This prints: 57 0 commits ahead. It should print 0 commits ahead.
# note also the single space between 57 and 0. In the echo above there are 5 spaces.
我尝试在子shell中没有git的情况下复制它,然后它按预期工作:
REVLIST="$(echo "57 0")"
echo $(echo "$REVLIST" | cut -d " " -f 6) commits ahead.
# this prints as expected: 0 commits ahead.
我尝试添加/删除引号以回显命令和变量赋值。我还尝试使用 <<<
运算符而不是管道,例如cut -d " " -f 6 <<< "$REVLIST"
。那些尝试没有奏效。
我不确定这是哪里出了问题或如何使它按预期运行。是子壳吗?是 git 输出吗?我是否错误地使用了回声/管道?
我使用的是 5.7.1 版的 ZSH。
更新:附加上下文
要回答 KamilCuk 关于这个问题:
REVLIST="$(git rev-list --left-right --count main...fix/preview-data)"
echo "$REVLIST" | hexdump -C
this prints:
00000000 35 37 09 30 0a |57.0.|
00000005
REVLIST="$(echo "57 0")"
echo "$REVLIST" | hexdump -C
this prints:
00000000 35 37 20 20 20 20 20 30 0a |57 0.|
00000009
解决方法
输出有一个制表符,而不是 6 个空格。
就
cut -f2 <<<"$REVLIST"
cut
的默认分隔符是制表符。