How to get the last character of a string in a shell?
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.
Per @perreal, quoting variables is important, but because I read this post like five times before finding a simpler approach to the question at hand in the comments...
str='abcd/'
echo "${str: -1}"
=> /
Alternatively use ${str:0-1}
as pointed out in the comments.
str='abcd*'
echo "${str:0-1}"
=> *
Note: The extra space in ${str: -1}
is necessary, otherwise ${str:-1}
would result in 1
being taken as the default value if str
is null or empty.
${parameter:-word}
Use Default Values. If parameter is unset or null, the
expansion of word is substituted. Otherwise, the value of
parameter is substituted.
Thanks to everyone who participated in the 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.