bashpositional-parameter

Bash - how to get a last character of a positional Parameter?


I am trying to read a last character of a string saved in a positional parameter $1. So far, I know how to do this only for the named variable, such as

echo "${str: -1}"

Could someone advise me how to do it for $1. Thought this could work, but it didnt. Thank you.

echo "${\$1: -1}"

Solution

  • Trivially

    echo "${1: -1}"
    

    The numbered arguments use exactly the same syntax as any other variables.

    The parameter expansion ${str: -1} is a Bash extension; if you need POSIX sh compatibility, you need two steps.

    _=${1%?}
    echo "${1#"$_"}"
    

    The first expansion returns the string with its last character removed; then, we remove this string from the prefix, yielding just the character we chopped off before.