Context: I'm making a shell function to output git rev-list
information in a more human-friendly way (inspired by this answer).
But I'm blocked on unexpected behavior that I can't explain. Here's an illustration:
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.
I tried replicating this without git in the subshell, then it works as expected:
REVLIST="$(echo "57 0")"
echo $(echo "$REVLIST" | cut -d " " -f 6) commits ahead.
# this prints as expected: 0 commits ahead.
I tried adding/removing quotes to echo commands and variable assignments. I also tried using the <<<
operator instead of piping, e.g. cut -d " " -f 6 <<< "$REVLIST"
. Those attempts didn't work.
I'm not sure where this goes wrong or how to make it run as expected. Is it the subshell? Is it the git output? Am I using echo/piping incorrectly?
I'm using ZSH with version 5.7.1.
Update: additional context
To answer KamilCuk's on this question:
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
The output has a tab, not 6 spaces.
Just
cut -f2 <<<"$REVLIST"
The default separator for cut
is tab.