如何在Bash或UNIX Shell中检查字符串中的第一个字符? [英] How to check the first character in a string in Bash or UNIX shell?

查看:729
本文介绍了如何在Bash或UNIX Shell中检查字符串中的第一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在UNIX中编写脚本,在该脚本中,我必须检查字符串中的第一个字符是否为"/",如果是,则为分支.

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.

例如,我有一个字符串:

For example I have a string:

/some/directory/file

我希望它返回1,并且:

I want this to return 1, and:

server@10.200.200.20:/some/directory/file

返回0.

推荐答案

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

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

或正则表达式:

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

这篇关于如何在Bash或UNIX Shell中检查字符串中的第一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆