上下文:我正在制作一个shell函数,以一种更人性化的方式输出git rev-list
信息(受到这个答案的启发)。
但是我被我无法解释的意外行为所阻止。下面是一个例子:
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的输出吗?我是否错误地使用了回声/管道?
我使用的ZSH版本是5.7.1。
更新:额外的上下文
回答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
的默认分隔符是tab。