suppress detached head warning in Bash script


I’m writing a shell script to checkout branches or tags in multiple Git repositories. Sometimes, the checkout is to move HEAD to a tagged commit which does not have a branch associated with it. That is intentional, and it causes a detached HEAD state. While looking for a way to suppress the lengthy detached HEAD warning just for the current script (not in the config), I found this thread.

Here is the attempt I made to incorporate the answer from that thread into my code:

# repositories against which to run commands in this script

# branch or tag to checkout in all repos (TODO: change this to a list user selects from)

# checkout reference in all repos
for i in "${repos[@]}"
    echo "$i"
    # git -C "$i" checkout "$ref" # <--- this worked to repoint HEAD but got detatched HEAD error
    git -C "$i" checkout "$ref" -c advice.detachedHead=false
# wait to close terminal until user is ready
read -p "Press Enter to exit terminal"

However, this results in the following –

error: unknown switch ‘c’

When the lines in the loop are changed to this:

echo "$i"
git -C "$i" -c advice.detachedHead=false
git -C "$i" checkout "$ref"

a message appears about the usage of Git (see partial screenshot below) and the detached HEAD message is still present.

How can this code be modified to suppress the detached HEAD message just for the script?

>Solution :

The order of flags to git matters:

git <flag-set-1> <command> <flag-set-2> <arguments>

runs git with flag-set-1 so that git runs command with flag-set-2 arguments while obeying flag-set-1. The -c advice.detachedHead=false argument is an argument to git, not to any of the command commands. That is, you want:

git -C "$path" -c advice.detachedHead=false checkout ...

rather than:

git -C "$path" checkout -c advice.detachedHead=false ...

(The git clone command accepts very similar -c arguments in its flag-set-2, but don’t let that mislead you!)

Leave a Reply Cancel reply