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

前端 未结 4 422
无人共我
无人共我 2021-01-30 06:07

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:

/         


        
4条回答
  •  感情败类
    2021-01-30 07:02

    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
    

提交回复
热议问题