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?