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.
Show activity on this post. To short, use: ${str::1} .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With