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

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


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


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

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


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