How to delete a branch without error message if the branch does not exist?

I would like to include a command to delete the local Git branch in the script, and I don't want any error message to be displayed if the branch does not exist. At the same time, I also don’t want a status code indicating that the Git command has failed.

In the following example:

git branch -D foo

If a branch exists, it is deleted, and the return status of the command is 0, which indicates success. If I run the same script again, the branch no longer exists, so the command does not work, prints

error: branch 'foo' not found.

and the return status of the Git command is> 0, which indicates an error.

Is there a way to silence a team, so anyway, was there a branch in the first place? Ideally, it will not display an error message, nor does it indicate a failure through a non-zero return status.

, , , Windows (.bat) Unix/Linux/Mac (.sh).

, ?

+4
2

:

branch="${1:?foo}"  

if git show-ref --verify --quiet "refs/heads/$branch"; then
echo "Branch exists."
.......
+3

, , .. 0,... , , ... , .

:

Linux   $ git branch -D <branch> &>/dev/null    
Windows $ git branch -D <branch> 1>nul 2>nul

, .

+2

Source: https://habr.com/ru/post/1531538/


All Articles