old-monk
old-monk

Reputation: 931

When using git commands in batch script, how to fail on error?

Below is the batch script in which I am executing a set of git operations, how I can fail on a git error like on git checkout "Branch already exits"

```

REM arg 1 = branch to copy
REM arg 2 = branch in which copy will be merged
set arg1=%1%
set arg2=%2%
echo copying %arg1% to %arg2%
echo "check out as tmp "+%arg1%
set ret = git checkout -b tmp %arg1%
echo %ret%
set ret = git checkout -b tmp %arg1%
echo %ret%
exit 0
REM emitted code for brevity 

``` output :

c:\my-project>c:\bat\git-copy-branch.bat master my-git-branch

c:\my-project>git checkout -b tmp master
fatal: A branch named 'tmp' already exists.

c:\my-project>git checkout -b tmp master
fatal: A branch named 'tmp' already exists.

c:\my-project>git checkout -b tmp master
fatal: A branch named 'tmp' already exists.

Upvotes: 3

Views: 1992

Answers (1)

phd
phd

Reputation: 94511

REM arg 1 = branch to copy
REM arg 2 = branch in which copy will be merged
set arg1=%1%
set arg2=%2%
echo copying %arg1% to %arg2%
echo "check out as tmp "+%arg1%
git checkout -b tmp %arg1%
if errorlevel 1 goto Quit
echo Ok
git checkout -b tmp %arg1%
if errorlevel 1 goto Quit
echo Ok
:Quit

:Quit is a label. if errorlevel 1 checks if there was any error in previous command; it really checks if errorlevel >= 1.

Upvotes: 3

Related Questions