printf '%c
"$s"
This was mentioned by brunoais in a comment, and it might be the best option since:
it is likely POSIX. TODO confirm. The following quote from https://pubs.opengroup.org/onlinepubs/9699919799/utilities/printf.html suggests this:
It shall not be considered an error if an argument operand is not completely used for a b, c, or s conversion.
it can extract the character to a variable unlike using case
directly
unlike cut -c1
printf
is a Bash built-in so it could be a little bit faster
myvar=abc
first_char="$(printf '%c' "$myvar")"
if [ "$first_char" = a ]; then
echo 'starts with a'
else
echo 'does not start with a'
fi
cut -c1
This is POSIX, and unlike case
:
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?