4

How do you pipe a multiline variable to grep and retain the newlines?

Expected results:

$ git status --porcelain --branch
## test-branch
M  image.go
 M item.go
?? addme.go
?? testdata/
$ git status --porcelain --branch | grep -c '^??'
2

"2" is the answer.

But in a script (or just entering the commands), I am not able to parse this $x from below.

$ x="$(git status --porcelain --branch)"
$ y="$(echo $x | grep -c '^??')"
$ echo "$y"
0

I suspect it is with how I am echoing $(echo $x ... within the y variable assignment.

EDIT: I am only executing x="$(git status --porcelain --branch)" one time, and parsing it a few dozen times with multiple grep commands for various outputs, values, counts, status, branches, behinds, aheads and other values. Therefore I need to assign the output of git status ... to a variable, and parse it multiple times.

eduncan911
  • 17,165
  • 13
  • 68
  • 104

1 Answers1

13

If you don't quote $x, it will undergo word-splitting and echo will print one long line. You just need to use "$x":

x=$(git status --porcelain --branch)
y=$(echo "$x" | grep -c '^??')
echo "$y"

Also, you don't have to use extra echo:

y=$(grep -c '^??' <<< "$x")

I recommend using shellcheck. It is really helpful in such cases.

PesaThe
  • 7,259
  • 1
  • 19
  • 43