I have written the following lines to get the last character of a string:
str=$1
i=$((${#str}-1))
echo ${str:$i:1}
It works for abcd/
I know this is a very old thread, but no one mentioned which to me is the cleanest answer:
echo -n $str | tail -c 1
Note the -n
is just so the echo doesn't include a newline at the end.
Every answer so far implies the word "shell" in the question equates to Bash.
This is how one could do that in a standard Bourne shell:
printf $str | tail -c 1
expr $str : '.*\(.\)'
Or
echo ${str: -1}
Try:
"${str:$((${#str}-1)):1}"
For e.g.:
someone@mypc:~$ str="A random string*"; echo "$str"
A random string*
someone@mypc:~$ echo "${str:$((${#str}-1)):1}"
*
someone@mypc:~$ echo "${str:$((${#str}-2)):1}"
g