0

I wrote a commit-msg hook to prevent commits with empty messages by checking to see if COMMIT_EDITMSG is empty, and if so, then to exit process :

#!/bin/sh
# .git/hooks/commit-msg

# Read COMMIT_EDITMSG file
COMMIT_MSG_FILE=$(cat $1)

# No empty commit message rule
if [$COMMIT_MSG_FILE == '']
then
  echo "Must have a commit message"
  exit 1
fi

It is working as expected except when I make a commit with text in it terminal interprets the first string in the commit message as a command. Say for example if i do git commit -m "commit 1", shell interprets "commit" as a command. The commit still goes through but does anyone know why this is happening and how I can prevent this?

  • Do you think the shell is interpreting "commit" as a command because you are seeing a message like: `[commit: command not found`? If so, your interpretation is incorrect. – William Pursell Aug 26 '22 at 20:57
  • Try adding a space after `[`. – William Pursell Aug 26 '22 at 20:58
  • Consider making a habit of running your code through http://shellcheck.net/ before asking questions here. – Charles Duffy Aug 26 '22 at 20:58
  • To explain the error message concretely: The command you _want_ to run is named `[` (or, alternately, `test`; when called under the `[` name it expects a final argument of `]`, but that's the only difference). Commands are separated from their arguments by spaces. When you expand `[$something` and `something='hello world'`, that means you're trying to run a command named `[hello`, which -- unlike the command `[` -- typically doesn't exist. – Charles Duffy Aug 26 '22 at 20:59
  • Another potential bug in your code: `==` is not guaranteed to work in `[`; the only [standard-defined](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html) string comparison operator is `=`. With `==`, it will work on some Linux distros but not others, depending on which version of `/bin/sh` they use (`/bin/[` typically exists as an external command, but shells also generally provide a built-in version for speed, even though it's parsed the same way as any other command; to get special handling by the parser you need `[[` not `[` in extended shells that provide it). – Charles Duffy Aug 26 '22 at 21:02

0 Answers0