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

canecse picture canecse · Aug 28, 2013 · Viewed 117.8k times · Source

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:

[email protected]:/some/directory/file

to return 0.

Answer

user000001 picture user000001 · Aug 28, 2013

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