如何在 bash 中测试一个字符串是否以另一个字符串开头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15418149/
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
How do I test if a string starts with another in bash?
提问by Maslow
Very similar but not duplicate : https://stackoverflow.com/a/2172367/57883
非常相似但不重复:https: //stackoverflow.com/a/2172367/57883
I'm in Git Bash 3.1 (at least that's what comes up in the prompt when I type bash inside git bash.
我在 Git Bash 3.1 中(至少当我在 git bash 中输入 bash 时出现在提示中。
and $ test [["DEV-0" == D*]] || echo 'fail'prints fail.
和$ test [["DEV-0" == D*]] || echo 'fail'打印失败。
if [['DEV-0-1' == DEV* ]]; then echo "yes";says [[DEV-0-1: command not foundI'm trying to test if git branchreturns something that starts with DEV. but I can't seem to apply the answer. is it because all my attempts are using a string literal on the left instead of a variable value?
if [['DEV-0-1' == DEV* ]]; then echo "yes";说[[DEV-0-1: command not found我正在尝试测试是否git branch返回以 DEV 开头的内容。但我似乎无法应用答案。是不是因为我所有的尝试都使用左侧的字符串文字而不是变量值?
I've also tried it on ideone http://ideone.com/3IyEND
我也在 ideone http://ideone.com/3IyEND上试过
and no luck. It's been ~14 years since I was good with a linux prompt.
没有运气。自从我擅长 linux 提示符以来,已经有大约 14 年了。
What am I missing for a string starts with test in bash?
我在 bash 中以 test 开头的字符串缺少什么?
回答by P.P
You missed a space there:
你错过了一个空间:
if [[ 'DEV-0-1' == DEV* ]]; then echo "yes"; fi
^^
回答by Ansgar Wiechers
I'd probably rather do the check like this:
我可能宁愿做这样的检查:
s1=DEV-0-1
s2=DEV
if [ "${s1:0:${#s2}}" == "$s2" ]; then
echo "yes"
fi

