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

跟風遠走 提交于 2019-12-03 03:51:20

问题


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

I want this to return 1, and:

server@10.200.200.20:/some/directory/file

to return 0.


回答1:


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



回答2:


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

case "$STRING" in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac



回答3:


$ foo="/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
1
$ foo="server@10.200.200.20:/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
0



回答4:


cut -c1

This is POSIX, and unlike case actually extracts the first char if you need it for later:

myvar=abc
first_char="$(printf '%s' "$myvar" | cut -c1)"
if [ "$first_char" = a ]; then
  echo 'starts with a'
else
  echo 'does not start with a'
fi

awk substr is another POSIX but less efficient alternative:

printf '%s' "$myvar" | awk '{print substr ($0, 0, 1)}'

printf '%s' is to avoid problems with escape characters: https://stackoverflow.com/a/40423558/895245 e.g.:

myvar='\n'
printf '%s' "$myvar" | cut -c1

outputs \ as expected.

${::} does not seem to be POSIX.

See also: How to extract the first two characters of a string in shell scripting?



来源:https://stackoverflow.com/questions/18488270/how-to-check-the-first-character-in-a-string-in-bash-or-unix-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!