'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.
Solution 1:[1]
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
Solution 2:[2]
Consider the case statement as well which is compatible with most sh-based shells:
case $str in
/*)
echo 1
;;
*)
echo 0
;;
esac
Solution 3:[3]
$ foo="/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
1
$ foo="[email protected]:/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
0
Solution 4:[4]
cut -c1
This is POSIX, and unlike case, it actually extracts the first character if you need it for later:
myvar=abc
first_char="$(printf '%s' "$myvar" | cut -c1)"
if [ "$first_char" = a ]; then
echo 'starts with a'
else
echo 'does not start with a'
fi
awk substr is another POSIX command, but less efficient alternative:
printf '%s' "$myvar" | awk '{print substr ($0, 0, 1)}'
printf '%s' is to avoid problems with escape characters: Bash printf literal verbatim string, e.g.,
myvar='\n'
printf '%s' "$myvar" | cut -c1
outputs \ as expected.
${::} does not seem to be POSIX.
See also: How can I extract the first two characters of a string in shell scripting?
Solution 5:[5]
Code:
place="Place"
fchar=${place:0:1}
echo $fchar
Output:
P
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
| Solution 2 | |
| Solution 3 | devnull |
| Solution 4 | Peter Mortensen |
| Solution 5 | naqviO7 |
