Shell script to open files related to a git commit

11 Oct 2020

This is a small shell script that I use to open all files related to a commit in git; I find it quite useful when I want to resume working on a local branch.

This is useful if you're not using an IDE or you are working on multiple changes and switch between them.

Anyway, let's get to the script.

#!/bin/bash
gitPrefix=$(git rev-parse --show-toplevel)

__num=$(git diff --name-only | wc -l)

filter_open() {
$1 | perl -p -e 's!.+!'$gitPrefix'/$&!; s!.+(png|jpeg)$!!' | xargs kate -n > /dev/null 2>&1 &
}

if [ -z "$1" -a "$__num" -ge 1 ]; then
filter_open "git diff --name-only"
else
filter_open "git diff HEAD^1 --name-only"
fi

git rev-parse --show-toplevel: returns the absolute path to the top-level git repo directory

git diff --name-only: returns the list of the files that are changed but not committed yet

git diff HEAD^1 --name-only: returns the list of files that were changed (committed or not) since the commit before last in the repo

perl -p -e 's!.+!'$gitPrefix'/$&!; s!.+(png|jpeg)$!!': since the git diff commands above return relative paths, I need to prepend $gitPrefix (the output of the git rev-parse --show-toplevel command) to all those relative paths, that's what this perl command does; also it filters out all png/jpeg files (I don't want to edit images with a text editor... it doesn't work)

As you can see, I write hacky bash scripts, I am sure there are ways to make it more elegant, but it works, so.

I have two use cases here: