Figure out changed lines in a commit in a git repo
git show
can be used to figure out the changed lines in a commit. I recently worked on a task at work to remove all unused texts. I used a script and it was not feasible for QA to test and make sure that I had not removed some text that is in use by going through the entire product.
QA reached out to me asking the list of strings removed, and I used git show
to get them.
The command was:
git show <commit-hash> --unified=0 -- <file-path>
Lets break it down.
git show
-> Is used to get the changes in the commit with the--unified=0
-> Is only gives the list of changed lines without any surrounding context lines.--
-> Tells that the next values are not a git option.-> Is the absolute or relative path of the file in git repo.
I was only interested in getting the removed lines so the output of this command was filtered through grep to only get removed lines(-
)
So now the command was:
git show --unified=0 <commit-hash> -- <file-path> | grep '^-'
grep '^-'
-> Matches all lines starting(^
) with a -
To make the output cleaner, I further filtered it with cut -c2-
(remove leading -). I also removed empty lines with grep -v '^[[:space:]]*$'
. I then redirected the output to file, so it can be shared with QA.
So the final command is:
git show --unified=0 <commit-hash> -- <file-path> | grep '^-' | cut -c2- | grep -v '^[[:space:]]*$' > <output-file-name>
cut -c2-
-> Extract characters starting from 2nd position(- is in 1st position, it is 1 based indexing)grep -v '^[[:space:]]*$'
-> Remove all lines with only whitespaces,-v
does inverted matching.^[[:space:]]*$
matches lines with 0 or more whitespaces.
References: man git-show
, man grep
, man cut