string 如何在 Bash 或 UNIX shell 中检查字符串中的第一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18488270/
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-09 02:04:12  来源:igfitidea点击:

How to check the first character in a string in Bash or UNIX shell?

stringbashunixcharacterexitstatus

提问by canecse

I'm writing a script in UNIX where I have to check whether the first character in a string is "/" and if it is, branch.

我正在 UNIX 中编写一个脚本,我必须检查字符串中的第一个字符是否为“/”,如果是,则进行分支。

For example I have a string:

例如我有一个字符串:

/some/directory/file

I want this to return 1, and:

我希望它返回 1,并且:

[email protected]:/some/directory/file

to return 0.

返回 0。

回答by user000001

Many ways to do this. You could use wildcards in double brackets:

有很多方法可以做到这一点。您可以在双括号中使用通配符:

str="/some/directory/file"
if [[ $str == /* ]]; then echo 1; else echo 0; fi

You can use substring expansion:

您可以使用子字符串扩展:

if [[ ${str:0:1} == "/" ]] ; then echo 1; else echo 0; fi

Or a regex:

或正则表达式:

if [[ $str =~ ^/ ]]; then echo 1; else echo 0; fi

回答by konsolebox

Consider the case statement as well which is compatible with most sh-based shells:

还要考虑与大多数基于 sh 的 shell 兼容的 case 语句:

case $str in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac

回答by devnull

$ foo="/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
1
$ foo="[email protected]:/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
0