unexpected operator [: git: in bourne shell script 'if' conditional statement
bash, debugging, sh, shell, unix
Solution
In this statement:
if [ git diff-index --quiet HEAD ]
The `[` is an alias for the `test` command, so what you're actually running is...
if test git diff-index --quiet HEAD ]
...which isn't what you mean. You don't need to use the `test` command in order to evaluate the result of a command; you should just do this:
if git diff-index --quiet HEAD
Take a look at the documentation for the `if` command:
$ help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
The conditional argument to the `if` statement is command. Normally, the `test` command is used to make it look like other languages, but you can put any command there. Things that exit with a return code of 0 evaluate to true and anything else evaluates to false.
Problem
I've watched an excellent shell scripting course through a multitude of videos. Now that I think I am fairly familiar with the Bourne shell, I decided to write my first shell script. Script goal: check if git working directory is clean. If so, overwrite working directory to a branch named `deployment`. Finally, push the deployment branch to origin. I ended up with this code: ``` #!/bin/sh ###################################################### # Deploys working directory to git deployment branch. # Requires that the working directory is clean. ###################################################### #check if the working directory is clean if [ git diff-index --quiet HEAD ] then if [ git branch -f deployment ] then if [ git push origin deployment ] then echo echo "OK. Successfully deployed to git deployment branch." echo exit 0 #success else echo echo "Error: failed to push deployment branch to origin." echo exit 1 #failure fi else echo echo "Error: failed to create or overwrite deployment branch." echo exit 1 #failure fi else echo git status #show the status of the working directory echo echo "Error: working directory is not clean. Commit your changes first..." echo exit 1 #failure fi ``` Unfortunately, this seems to give me an error: `./tools/deploygit: 9: [: git: unexpected operator` Why is this so? What operator am I using in `if [ git diff-index --quiet HEAD ]` that is unexpected? As a bonus, do you have any suggestions or tips on how to improve the efficiency, logic or readability of this script?