Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check last character of a string

Is there a built-in POSIX equivalent for this bashism?

my_string="Here is a string"
last_character=${my_string: -1}

I keep seeing things like this recommended, but they seem like hacks.

last_character=$(echo -n "$my_string" | tail -c 1)
last_character=$(echo -n "$my_string" | grep -o ".$")

But, maybe a hack is all we have with POSIX shells?

like image 566
miken32 Avatar asked Mar 09 '23 23:03

miken32


2 Answers

If you really have to do it POSIX only:

my_string="Here is a string"
last_character=${my_string#"${my_string%?}"}

What it does is essentially removing $my_string sans its last character from the beginning of the $my_string, leaving you with only the last character.

like image 174
zwer Avatar answered Mar 19 '23 03:03

zwer


If you just need to check what is the last character and then act on its value, then the case ... esac construct is a portable way to express it.

like image 37
JooMing Avatar answered Mar 19 '23 03:03

JooMing