Question

I have that bash script that shall read the output of git show into an array.

First, I create a string with the following statement:

git show --quiet --date=rfc --pretty=format:"%s|%b|%an, %ae|%H|%cd" HEAD

Which gives me the pattern that I want:

SUBJECT|BODY|AUTHOR_NAME, AUTHOR_EMAIL|COMMIT_HASH|COMMIT_DATE

I can confirm that the resulting string does not contain a | character on an unexpected place.

Next, I want to split up the string into it's fields as supposed in Split string into an array in Bash:

  IFS='|' read -ra FIELDS <<< "$(git show --quiet --date=rfc --pretty=format:"%s|%b|%an, %ae|%H|%cd" $i)"

When I now look at FIELDS, only the first two elements are filled, but the others are empty:

echo ${FIELDS[0]} # prints SUBJECT
echo ${FIELDS[1]} # prints BODY
echo ${FIELDS[2]} # prints nothing
echo ${FIELDS[3]} # prints nothing
echo ${FIELDS[4]} # prints nothing

What am I doing wrong? Why are the last three array elements empty?

Was it helpful?

Solution

As @l0b0 pointed out, the problem is caused by a newline in git show's output, right after "BODY" -- the read command reads a single line, so it stops there. You can make it read the whole thing by changing its line delimiter character from newline to... nothing, with read -d '':

IFS='|' read -d '' -ra FIELDS <<< "$(git show --quiet --date=rfc --pretty=format:"%s|%b|%an, %ae|%H|%cd" $i)"

This sets ${FIELDS[0]} to "SUBJECT", ${FIELDS[1]} to "BODY\n", ${FIELDS[2]} to "AUTHOR_NAME, AUTHOR_EMAIL", etc. One complication, however, is that it'll also treat the syntactic newline at the end of the output as part of the last field, i.e. ${FIELDS[4]} will be set to "COMMIT_DATE\n".

OTHER TIPS

The git show command you've given splits the output into multiple lines (at least in version 1.8.3.1), even when passed to another command:

$ git show --quiet --date=rfc --pretty=format:"%s|%b|%an, %ae|%H|%cd" HEAD
SUBJECT|BODY
|AUTHOR_NAME, AUTHOR_EMAIL|COMMIT_HASH|COMMIT_DATE

To work around this you can pipe the output to tr -d '\n' before reading it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top