bash 脚本来检查当前的 git branch = "x"

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37890510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:47:35  来源:igfitidea点击:

bash script to check if the current git branch = "x"

gitbashshellsh

提问by Alexander Mills

I am very bad at shell scripting (with bash), I am looking for a way to check if the current git branch is "x", and abort the script if it is not "x".

我在 shell 脚本(使用 bash)方面非常糟糕,我正在寻找一种方法来检查当前的 git 分支是否为“x”,如果它不是“x”,则中止脚本。

    #!/usr/bin/env bash

    CURRENT_BRANCH="$(git branch)"
    if [[ "$CURRENT_BRANCH" -ne "master" ]]; then
          echo "Aborting script because you are not on the master branch."
          return;      # I need to abort here!
    fi

    echo "foo"

but this is not quite right

但这并不完全正确

回答by knittl

Use git rev-parse --abbrev-ref HEADto get the name of the current branch.

使用git rev-parse --abbrev-ref HEAD来获得当前分支的名字。

Then it's only a matter of simply comparing values in your script:

那么这只是简单地比较脚本中的值的问题:

BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [[ "$BRANCH" != "x" ]]; then
  echo 'Aborting script';
  exit 1;
fi

echo 'Do stuff';

回答by Pankrates

One option would be to parse the output of the git branchcommand:

一种选择是解析git branch命令的输出:

BRANCH=$(git branch | sed -nr 's/\*\s(.*)//p')

if [ -z $BRANCH ] || [ $BRANCH != "master" ]; then
    exit 1
fi

But a variant that uses git internal commands to get just the active branch name as suggested by @knittl is less error prone and preferable

但是使用 git 内部命令仅获取@knittl 建议的活动分支名称的变体更不容易出错且更可取

回答by jil

You want to use exitinstead of return.

您想使用exit而不是return.