Shell Script – How to Delete the Last Character of a String

shell-scriptstring

I would like to delete the last character of a string, I tried this little script :

#! /bin/sh 

t="lkj"
t=${t:-2}
echo $t

but it prints "lkj", what I am doing wrong?

Best Answer

In a POSIX shell, the syntax ${t:-2} means something different - it expands to the value of t if t is set and non null, and otherwise to the value 2. To trim a single character by parameter expansion, the syntax you probably want is ${t%?}

Note that in ksh93, bash or zsh, ${t:(-2)} or ${t: -2} (note the space) are legal as a substring expansion but are probably not what you want, since they return the substring starting at a position 2 characters in from the end (i.e. it removes the first character i of the string ijk).

See the Shell Parameter Expansion section of the Bash Reference Manual for more info:

Related Question