Bash – Get last character in string

To get last character in a string in Bash scripting, you can use parameter expansion and substring expansion as shown in the following expression.

${string: -1}

Please note the spacing between : and -1.

Example

In the following script, we take a string in str. We get the last character in this string and echo it to output.

example.sh

#!/bin/bash
 
str="apple"
ch=${str: -1}
echo $ch

Output

sh-3.2# ./example.sh 
e

References

Bash Substring

ADVERTISEMENT

Conclusion

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