Git Hooks with stderr

For example, it’s tricky to validate a commit with pre-commit hook if an app does not return a proper exit code. Here’s a way to validate with the stderr.

  1. Make a temporary file
  2. Redirect stderr to the temp file
  3. Count the length of its content

You can understand it with code snippets below:

PowerShell

1
2
3
4
5
6
7
$errFile = New-TemporaryFile
command > /dev/null 2>$errFile
$err = Get-Content $errFile
If ($err.Length -ne 0) {
Exit 1
}
Exit 0

Unix/Linux shell

1
2
3
4
5
6
7
errFile = $(mktemp)
command > /dev/null 2>$errFile
$l = wc -l $errFile
if [$l -ne 0]; then
exit 1
fi
exit 0