Skip to content

Instantly share code, notes, and snippets.

@wookietreiber
Last active April 27, 2021 05:15
Show Gist options
  • Save wookietreiber/3bf8621274caafed543fca6a3feab284 to your computer and use it in GitHub Desktop.
Save wookietreiber/3bf8621274caafed543fca6a3feab284 to your computer and use it in GitHub Desktop.
git pre-commit hook to check shell scripts with shellcheck
#!/usr/bin/env bash
set -efu -o pipefail
# returns staged files
function staged.files {
if git rev-parse --verify HEAD &> /dev/null
then
against=HEAD
else
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
git diff-index --cached --name-only $against |
grep \
-e '\.bashrc' \
-e '\.zshrc' \
-e '\.bash_profile' \
-e '\.sh$' || true
}
declare -a paths=()
while read -r file
do
paths[${#paths[@]}+1]=$file
done < <(staged.files)
if [[ ${#paths[@]} -eq 0 ]]
then
echo -e '\e[1m\e[32m[info]\e[0m \e[1mshellcheck\e[0m no files in stage'
else
if ! command -v shellcheck &> /dev/null
then
echo -e '\e[1m\e[33m[warn]\e[0m \e[1mshellcheck\e[0m is not installed' >&2
exit 0
fi
stage=$(mktemp -d)
trap 'rm -r $stage' EXIT INT TERM
for path in "${paths[@]}"
do
file="$stage/$path"
mkdir -p "$(dirname "$file")"
git show ":$path" > "$file"
done
pushd "$stage" &> /dev/null
shellcheck "${paths[@]}"
popd &> /dev/null
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment