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
bash script to check if the current git branch = "x"
提问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 HEAD
to 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 branch
command:
一种选择是解析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 exit
instead of return
.
您想使用exit
而不是return
.