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

前端 未结 10 2089
温柔的废话
温柔的废话 2020-12-22 18:54

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/

10条回答
  •  不思量自难忘°
    2020-12-22 19:08

    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!

提交回复
热议问题