Bash – Remove last character in string

To remove last character in a string in Bash scripting, you can use string slicing. Get the substring from starting character till the last but one character in the string, as shown in the following expression.

${string::-1}

Example

In the following script, we take a string in str. We remove the last character in the string, and print the resulting string using echo.

example.sh

#!/bin/bash
 
string="helloworld"
index=5
output=${string::-1}
echo $output

Bash Version: GNU bash, version 5.2.15(1)-release (aarch64-apple-darwin22.1.0)

Output

sh-3.2# bash example.sh 
helloworl

References

Bash Substring

ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to remove the last character in given string using string slicing.