Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo multiline var to Grep

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.

like image 662
eduncan911 Avatar asked Oct 16 '25 04:10

eduncan911


1 Answers

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.

like image 63
PesaThe Avatar answered Oct 17 '25 19:10

PesaThe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!