numbers='901.32.02'
firstdigit="${numbers:0:1}"
printf 'The first digit is "%s"\n' "$firstdigit"
The result of the above is
The first digit is "9"
The ${numbers:0:1}
parameter expansion in bash
give you the substring of length 1 from the start of the string (offset zero). This is a bash
-specific parameter substitution (also in some other shells, but not in the POSIX standard).
In a POSIX shell, you may also do
firstdigit=$( printf "%s\n" "$numbers" | cut -c 1 )
This will use cut
to only return the first character.
Or, using standard parameter expansions,
firstdigit="${numbers%${numbers#?}}"
This first uses ${numbers#?}
to create a string with the first digit removed, then it removes that string from the end of $numbers
using ${numbers%suffix}
(where suffix
is the result of the first expansion).
The above assumes that the first character of $numbers
is actually a digit. If it is not, then you would have to first remove non-digits from the start of the value:
numbers=$( printf '%s\n' "$numbers" | sed 's/^[^0-9]*//' )
or,
numbers="${numbers#${numbers%%[0-9]*}}"
${numbers[0]}
would have worked if each character was a separate element in the array numbers
(and if the first character was a digit). Since numbers
is not an array, it's equivalent to just $numbers
.