I have this script to check git status for all of my repositories:
find / -type d -name .git 2>&- |
while read gitFolder; do if [[ $gitFolder == *"/Temp/"* ]]; then continue; fi if [[ $gitFolder == *"/Trash/"* ]]; then continue; fi if [[ $gitFolder == *"/opt/"* ]]; then continue; fi parent=$(dirname $gitFolder); if [[ `git -C $parent status --porcelain` ]]; then echo ""; echo $parent; git -C $parent status --porcelain else if [[ $(git -C $parent status | grep ahead) ]]; then echo ""; echo "$parent is not pushed yet"; fi
done But it's not working.
If I remove the second else-block then it works.
Basically I want to know if a git repository has any changes (first if) or if it's ahead of master (second if).
How should I change that second if condition?
22 Answers
The Bash if...else if...else statement takes the following form:
if CONDITION1; then STATEMENTS1
elif CONDITION1; then STATEMENTS2
else STATEMENTS3
fiThe specific error in your script is the usage of the incorrect keyword else if instead of the correct one elif.
If the CONDITION1 evaluates to True, the STATEMENTS1 will be executed. If the CONDITION2 evaluates to True, the STATEMENTS2 will be executed. If none of the test commands evaluate to True, the CONDITION3 is executed.
The conditions are evaluated sequentially. Once a condition returns True, the remaining conditions are not performed, and program control moves to the end of the if statements.
You can have one or more elif clauses in the statement.
Suggestion: you can install shellcheck package to check your bash code. See for reference.
Try replacing
else if [[ $(git -C $parent status | grep ahead) ]]; thenwith
else if git -C $parent status | grep ahead; thenYou might also want to add -q to grep.
This works by replacing the [[ test with a naked command. The last command in the pipeline (grep) exits with a true or false value, depending if it found anything or not. The -q option tells it to only return with that value and not actually print what it found.
Note: there are other errors in your script that also need fixing.
7