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

前端 未结 10 2107
温柔的废话
温柔的废话 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:18

    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.

提交回复
热议问题