4

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

1
  • Check value of $?. If it's 0 (zero) that means that command succeeded, otherwise it failed. Commented Jun 25, 2015 at 11:17

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

6
#!/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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.