10

I tried to clone the git repository by passing the username, password. That was successful.

But what my intention is that I want to know whether the git clone command executed or not. If not, I would like to handle such kind of errors in shell script itself.

My working shell script:

cd ..
git clone https://username:[email protected]/username/repositoryname.git
cd repositoryname
git checkout branchname1
cd ..
mv repositoryname newfoldername
git clone https://username:[email protected]/username/respositoryname.git
cd repositoryname
git checkout branchname2
cd ..
mv repositoryname newfoldername

How do I test, in the script, whether these steps were successful?

0

3 Answers 3

20

The return value is stored in $?. 0 indicates success, others indicates error.

some_command
if [ $? -eq 0 ]; then
    echo OK
else
    echo FAIL
fi

I haven't tried it with git, but I hope this works.

0
2
if some_command
then
  echo "Successful"
fi

Example

if ! git clone http://example.com/repo.git
then
  echo "Failed"
else
  echo "Successful"
fi

See How to detect if a git clone failed in a bash script.

0

This one should work (Just put your script at the place marked "--- your script here ---" below):

#!/bin/bash

# call your script with set -e to stop on the first error
bash <<EOF
set -e
--- your script here ---
EOF

# test status: I don't want this part to stop on the first error,
# and that's why use the HERE document above to wrap a sub-shell for "set -e"
if [ $? -eq 0 ]; then
  echo success
else
  echo fail
fi

Alternatively, HERE document can be replaced by:

(
  set -e
  --- your script here ---
)
1
  • Thanks Robin for giving such a good solution for my problem.It's working fine for my script now.
    – bhadram
    Commented Nov 7, 2014 at 6:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.