0

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
repos[0]="./sandbox"
repos[1]="./playground"

# branch or tag to checkout in all repos (TODO: change this to a list user selects from)
ref="tags/v1"

# checkout reference in all repos
for i in "${repos[@]}"
do
    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
done
    
# 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. enter image description here

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

knot22
  • 2,648
  • 5
  • 31
  • 51
  • Move that up before checkout – Daniel A. White Jun 11 '22 at 21:32
  • 1
    `git -C "$i" -c advice.detachedhead=false checkout $ref`, or save yourself the repetition and `git config --global advice.detachedhead false` once and never be bothered again. `git`'s `-c` option is a one-time override. – jthill Jun 11 '22 at 21:35

1 Answers1

2

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!)

torek
  • 448,244
  • 59
  • 642
  • 775