20

How can I tell if a git clone had an error in a bash script?

git clone git@github.com:my-username/my-repo.git

If there was an error, I want to simply exit 1;

4

3 回答 3

30

Here are some common forms. Which is the best to choose depends on what you do. You can use any subset or combination of them in a single script without it being bad style.


if ! failingcommand
then
    echo >&2 message
    exit 1
fi

failingcommand
ret=$?
if ! test "$ret" -eq 0
then
    echo >&2 "command failed with exit status $ret"
    exit 1
fi

failingcommand || exit "$?"

failingcommand || { echo >&2 "failed with $?"; exit 1; }
于 2012-12-10T02:47:21.797 回答
12

You could do something like:

git clone git@github.com:my-username/my-repo.git || exit 1

Or exec it:

exec git clone git@github.com:my-username/my-repo.git

The latter will allow the shell process to be taken over by the clone operation, and if it fails, return an error. You can find out more about exec here.

于 2012-12-10T01:42:01.333 回答
3

Method 1:

git clone git@github.com:my-username/my-repo.git || exit 1

Method 2:

if ! (git clone git@github.com:my-username/my-repo.git) then
    exit 1
    # Put Failure actions here...
else
    echo "Success"
    # Put Success actions here...
fi
于 2016-11-11T21:01:09.940 回答