0

I would like to print git log in bash script line by line, current script output in one line, I guess need to split it by some way but not work!

#!/bin/bash

x=$(git log --oneline --no-merges -n 5)
echo $x

IFS=$'\n' lines=( $(echo $x) )
for line in lines; do
    echo $line
done
lucky1928
  • 8,708
  • 10
  • 43
  • 92
  • Why not just use `git log --oneline --no-merges -n 5` to get line by line print – anubhava Oct 21 '22 at 17:05
  • 1
    `echo "$x"` -- the quotes matter. Similarly, `echo "$line"` or else a line with a `*` in it will have a list of files from the current directory added. – Charles Duffy Oct 21 '22 at 17:12
  • Also, for `lines=( $(echo $x) )`, it would be more efficient as `lines=( $x )`, but even that is buggy. See [BashPitfalls #50](https://mywiki.wooledge.org/BashPitfalls#hosts.3D.28_.24.28aws_.2BICY.29_.29). – Charles Duffy Oct 21 '22 at 17:13

1 Answers1

1
git log --oneline --no-merges -n 5 | while IFS= read -r line
do
    echo "$line"
done

Assuming that, in reality, you plan to replace that echo with something else (otherwise, anubhava's comment applies: my code is the equivalent of git log | cat, in which | cat is a useless convolution.

Or, alternative method,

exec < <(git log --oneline --no-merges -n 5)

while IFS= read -r l
do
    echo "$l"
done
chrslg
  • 9,023
  • 5
  • 17
  • 31
  • 1
    `while IFS= read -r line` to avoid trimming of leading/trailing whitespace and removal of backslashes. And `echo "$line"` to make the line actually be represented as-given. – Charles Duffy Oct 21 '22 at 17:13
  • Beyond that, the usual grumbling about answering duplicative questions -- and associated link to the _Answer Well-Asked Questions_ section of [How to Answer](https://stackoverflow.com/help/how-to-answer) -- applies. – Charles Duffy Oct 21 '22 at 17:14
  • For that grumbling, well, I'd answered before. And I don't think the problem was about quoting variables. I mean, it would have been a problem certainly, at one point. But the immediate problem, the one the question was about, was "how to I get result of a command line by line". Answer being "not with command expansion, aka ``$(...)``". So maybe it is a duplicate, but I do believe it is not a duplicate of the linked question. – chrslg Oct 21 '22 at 17:22