How to get the last character of a string in a shell? How to get the last character of a string in a shell? shell shell

How to get the last character of a string in a shell?


Per @perreal, quoting variables is important, but because I read this post like 5 times before finding a simpler approach to the question at hand in the comments...

str='abcd/'echo "${str: -1}"

Output: /

str='abcd*'echo "${str: -1}"

Output: *

Thanks to everyone who participated in this above; I've appropriately added +1's throughout the thread!


That's one of the reasons why you need to quote your variables:

echo "${str:$i:1}"

Otherwise, bash expands the variable and in this case does globbing before printing out. It is also better to quote the parameter to the script (in case you have a matching filename):

sh lash_ch.sh 'abcde*'

Also see the order of expansions in the bash reference manual. Variables are expanded before the filename expansion.

To get the last character you should just use -1 as the index since the negative indices count from the end of the string:

echo "${str: -1}"

The space after the colon (:) is REQUIRED.

This approach will not work without the space.


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.