0

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
Thor Galle
  • 68
  • 7
  • 1
    I guess this could be explained if the string would be along `" 0\r57"` (or something more complicated). Please post the output of `echo "$REVLIST" | hexdump -C`. – KamilCuk Feb 16 '21 at 09:36
  • Hey @KamilCuk, thanks for your reply. I added the output of the command that you requested in both cases. I see there are indeed differences, but I'm not yet familiar enough with internal string representations & hexes to interpret the output. – Thor Galle Feb 16 '21 at 09:45
  • 1
    `09` is a tab, not a space – KamilCuk Feb 16 '21 at 09:46
  • Ah.. that probably explains things. I'll try to cut on a tab delimiter instead. Strange that it manifests in the terminal as spaces when I copy-paste it. – Thor Galle Feb 16 '21 at 09:48

1 Answers1

2

The output has a tab, not 6 spaces.

Just

cut -f2 <<<"$REVLIST"

The default separator for cut is tab.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 1
    Thanks for the quick answer! I just verified that it is a tab, and cutting on a tab fixes the problem. My confusion came from the tab being displayed as multiple spaces in my VSCode terminal, at least when I copy-pasted the output to use as a variable assignment. I'll remember `hexdump` for the future! – Thor Galle Feb 16 '21 at 09:53