Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GIT, check return code of commands (bash script)

Tags:

git

bash

I am working on a large project where it is split in many repositories.

I am thinking of making a small bash script that iterates and checkouts a specific remote or local branch or tag in each repository, BUT if this fails because the branch doesnt exist, to have a second option of a tag/repository to checkout.

i.e.

#!/bin/bash
printf "\n ### Checkout Tag ### \n \n"

for repo in rep1 rep2 ...
do

checkout $1 
(check if that fails somehow, and if it fails, checkout $2)

done

printf "\n ### DONE ### \n \n"

exit 0

Or, do you have an alternative idea?

Thank you

like image 616
thahgr Avatar asked Dec 24 '22 17:12

thahgr


2 Answers

You do not need to check the return codes manually. Just concat the commands with || and you will be fine

#!/bin/bash
printf "\n ### Checkout Tag ### \n \n"

for repo in rep1 rep2 ...
do
    checkout $1 || checkout $2 || echo "Error"
done

printf "\n ### DONE ### \n \n"

exit 0

|| will execute the following command only if the previous failed. Think of it as "One of the commands has to succeed". If the first succeeded, you are fine and do not have to check the following.

&& will execute the following command only if the previous succeeded. Think of it as "All commands have to succeed". If the first one failed, you are already lost and do not have to check the following.

In my opinion, this solution is cleaner and easier than the accepted answer.

like image 78
Rambo Ramon Avatar answered Jan 02 '23 16:01

Rambo Ramon


#!/bin/bash
printf "\n ### Checkout Tag ### \n \n"

for repo in rep1 rep2 ... ; do
    checkout $1
    if [[ $? != 0 ]]; then
        checkout $2
        if [[ $? != 0 ]]; then
            echo "Failed to checkout $1 and $2"
        fi
    fi
done

printf "\n ### DONE ### \n \n"
exit 0
like image 25
Eugeniu Rosca Avatar answered Jan 02 '23 16:01

Eugeniu Rosca