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

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

    For portability you can say "${s#"${s%?}"}":

    #!/bin/sh
    m=bzzzM n=bzzzN
    for s in \
        'vv'  'w'   ''    'uu  ' ' uu ' '  uu' / \
        'ab?' 'a?b' '?ab' 'ab??' 'a??b' '??ab' / \
        'cd#' 'c#d' '#cd' 'cd##' 'c##d' '##cd' / \
        'ef%' 'e%f' '%ef' 'ef%%' 'e%%f' '%%ef' / \
        'gh*' 'g*h' '*gh' 'gh**' 'g**h' '**gh' / \
        'ij"' 'i"j' '"ij' "ij'"  "i'j"  "'ij"  / \
        'kl{' 'k{l' '{kl' 'kl{}' 'k{}l' '{}kl' / \
        'mn$' 'm$n' '$mn' 'mn$$' 'm$$n' '$$mn' /
    do  case $s in
        (/) printf '\n' ;;
        (*) printf '.%s. ' "${s#"${s%?}"}" ;;
        esac
    done
    

    Output:

    .v. .w. .. . . . . .u. 
    .?. .b. .b. .?. .b. .b. 
    .#. .d. .d. .#. .d. .d. 
    .%. .f. .f. .%. .f. .f. 
    .*. .h. .h. .*. .h. .h. 
    .". .j. .j. .'. .j. .j. 
    .{. .l. .l. .}. .l. .l. 
    .$. .n. .n. .$. .n. .n. 
    

提交回复
热议问题