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

前端 未结 10 2099
温柔的废话
温柔的废话 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 19:22

    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
    

提交回复
热议问题