Remove the last character from a bash variable


The following method, removes the last character from a bash variable by using a regular expression that matches any character.


VAR=${VAR%?};

The functionality ${string%substring} deletes shortest match of $substring from the back of $string.
The question mark ? matches zero or one of the previous regular expression. It is generally used for matching single characters.
So by using ? as our $substring we instruct bash to match any character at the end of the variable and remove it.

Example


$ VAR="Banana";
$ VAR=${VAR%?};
$ echo $VAR;
Banan

This post is also available in: Αγγλικα

Απάντηση

Αυτός ο ιστότοπος χρησιμοποιεί το Akismet για να μειώσει τα ανεπιθύμητα σχόλια. Μάθετε πώς υφίστανται επεξεργασία τα δεδομένα των σχολίων σας.