简体   繁体   中英

Why does git commands work differently in script then in terminal?

I'm trying to make a bash script that goes in the.gitmodules file, gets the path and branch of each submodule then goes where the submodule is located and git checkout to the right branch. BUT the git commands doesn't work well when I run the script but work well when I enter them manully in the terminal.

Keep getting stuff like:

-> fatal not a git repository (or any of the parent directories): .git

(I then added git init in the while loop)

-> fatal: you are on a branch yet to be born

Can you tell me what i'm missing here plz?

#!/bin/bash


sed -n '/path/p' .gitmodules > tampon01.txt  #selectionne uniquement les ligne contenant path 
sed -n '/branch/p' .gitmodules > tampon02.txt  #selectionne uniquement les ligne contenant path 
cut -d = -f 2- tampon01.txt > pathlist.txt #selectionne uniquement les champs de caractères après le "=") pour les path
cut -d = -f 2- tampon02.txt > branchlist.txt #selectionne uniquement les champs de caractères après le "=") pour les branch

let "i=1"
Pnb_lignes=$(sed -n '$=' pathlist.txt)
Bnb_lignes=$(sed -n '$=' branchlist.txt)
echo $Pnb_lignes "path trouvées"
echo $Bnb_lignes "branch trouvées"
#while [ $i < $nb_lignes ]


#if [$Pnb_lignes -le $Bnb_lignes] #test pour trouver le minimum entre le nb de lignes trouvée dans chaque fichier
if [ 5 -le 2 ] #test pour trouver le minimum entre le nb de lignes trouvée dans chaque fichier
then
    let "nb_lignes = Pnb_lignes"
    
else
    let "nb_lignes = Bnb_lignes"
    
fi 


echo $nb_lignes "actions a realiser"

while (($i < $nb_lignes))
do 
    #pa= $(sed -n "$i"p tampon02.txt) #retourne la ligne i
    pa= sed -n "$i"p pathlist.txt
    br= sed -n "$i"p branchlist.txt
    #echo $pa "xxxx"
    cd $pa
    git init
    git checkout $br
    cd /mnt/c/_D/Devel/taoSet
    echo ".............................."
    let "i = $i +2"
done
echo $i "actions realisees"

#rm -v tampon01.txt tampon02.txt branchlist.txt pathlist.txt

In bash, there cannot be any spaces around the = sign in an assignment statement.

In a terminal, it may be re-using the values from previously assigned variables.
While in a bash script, since old / global variables are not accessible by default, it may assign null values or fail for incorrectly written commands and proceed ahead.

This is a plausible reason that you get different behaviours in both approaches.

The command substitution seems to be missing, leading to the $pa and $br variables to be undefined in these lines:

pa= sed -n "$i"p pathlist.txt
br= sed -n "$i"p branchlist.txt

It should be

pa=$(sed -n "$i"p pathlist.txt)
br=$(sed -n "$i"p branchlist.txt)

Other things could be broken as well, haven't checked thoroughly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM