Checking the 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 wrappers?
If you really should only be doing this POSIX:
my_string="Here is a string"
last_character=${my_string#"${my_string%?}"}
What it does is essentially remove $my_string
without the last character from the beginning $my_string
, leaving you with only the last character.
num=`echo $my_string | wc -c `
let num-=1
last=`echo $my_string | cut -c$num`
echo $last
Assumption: (its last char here) is the string for which u needs the last character. Hope this is helpful.
If you just need to check what is the last character and then act on its value, then a constructor case ... esac
is a portable way of expressing it.