Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the first character in a string in Bash or Unix shell?

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.

like image 692
canecse Avatar asked Aug 28 '13 12:08

canecse


People also ask

How do I get the first character of a string in bash?

Show activity on this post. To short, use: ${str::1} .

How do you get the first character of a string in Unix?

To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction.

How do I find a character in a string in bash?

Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ . When this operator is used, the right string is considered as a regular expression. The period followed by an asterisk . * matches zero or more occurrences any character except a newline character.

How do you check if a character is a letter in bash?

If you wish to test for a single letter, you can use the POSIX character class [[:alpha:]] or equivalently [a-zA-Z] . No need to check the length or use wildcards as a single bash pattern will only test multiple occurrences of a match when using extglob optional patterns. Save this answer.


1 Answers

There are 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 
like image 123
user000001 Avatar answered Oct 04 '22 12:10

user000001