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 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!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)