Trimming the Last Character from a String in Bash


Trimming the Last Character from a String in Bash.

In the world of shell scripting, manipulating string variables is a common task. One interesting challenge you might encounter is removing the last character from a string. This task might seem simple at first glance, but it showcases the flexibility and power of Bash scripting.

Let’s dive into a practical example to illustrate how this can be achieved efficiently.


Imagine you have a string stored in a variable, and you need to remove the last character of this string for your script’s logic to work correctly. For instance, you might be processing a list of filenames, paths, or user inputs where the trailing character needs to be omitted.


Bash provides several ways to manipulate strings. One of the simplest and most elegant methods to remove the last character from a string is using parameter expansion. Here’s a quick script to demonstrate this approach:


# Original string
str1="foo bar"
echo "String1: ${str1}"

# Removing the last character
echo "String2: ${str2}"

In this script:

  • We define a string variable `str1` with the value “foo bar”.
  • We then use `${str1%?}` to create a new variable `str2` that contains all characters of `str1` except for the last one. The `%?` syntax is a form of parameter expansion that removes a matching suffix pattern. In this case, `?` matches a single character at the end of the string.

How It Works

The `${variable%pattern}` syntax in Bash is a form of parameter expansion that removes the shortest match of `pattern` from the end of `variable`. The `?` in our pattern is a wildcard that matches any single character. Thus, `${str1%?}` effectively removes the last character from `str1`.

Alternative Approaches

Although the method shown above is succinct and effective for our purpose, Bash offers other string manipulation capabilities that could be used for similar tasks. For example:

  • Substring Extraction: `echo “${str1:0:${#str1}-1}”`
  • sed: If you prefer using external tools, `sed` can also achieve this: `echo “$str1” | sed ‘s/.$//’`

Each method has its use cases, depending on the complexity of the operation you’re performing and your personal preference.


Removing the last character from a string in Bash is straightforward with parameter expansion. This technique is just one example of the powerful string manipulation capabilities available in Bash. Experimenting with these features can help you write more efficient and effective scripts.

Leave a Reply

Your email address will not be published. Required fields are marked *