Shell Script to Get Last Character of a String

There are a couple of ways to extract the last character of a string within a shell script. The easiest way is if you are working on bash shell – as bash will get the job done without the help of any external utilities.

Let’s say that the string is “The quick brown fox jump over the lazy dog“.

If you are on a bash shell, Parameter Expansion can be used.

x="The quick brown fox jump over the lazy dog"
echo ${x: -1}

In the above example, we assign the string to the variable x. We then use Parameter Expansion to print the last character. Note that this trick does not work on shells like csh or tcsh.

Another way to extract the last character is to use the tail utility.

echo "The quick brown fox jump over the lazy dog" | tail -c 2

The echo command will pipe the string to tail and tail will output the last two bytes of the string. The reason for this is that the string has a newline character at the end of the string. This is why we need to tell tail to print two bytes instead of just printing the last byte.

If the string does not terminate with a newline character, tail can be ordered to print just the last character as in the following example.

echo -n "The quick brown fox jump over the lazy dog" | tail -c 1

The other method is to use sed, a stream editor.

echo "The quick brown fox jump over the lazy dog" | sed -e 's/.*\(.\)$/\1/'

The newline character is handled by sed and the above code will work whether or not the string is terminated with a newline character.

Special care has to taken to remove any trailing space characters (0x20) in the string if necessary.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }