Bash: How to Trim Trailing Whitespace from a Variable


Often you may want to use Bash to trim trailing whitespace from a variable.

There are two common ways to do so:

Method 1: Trim Trailing Whitespace Using Wildcards

my_var="${my_var%"${my_var##*[![:space:]]}"}"

Method 2: Trim Trailing Whitespace Using sed

my_var="$(echo -e "${my_var}" | sed -e 's/[[:space:]]*$//')"

Both of these methods will remove the leading whitespace in the variable named my_var.

The following examples show how to use each method in practice.

Example 1: Trim Trailing Whitespace Using Wildcards

Suppose that we have a variable named my_var that contains the following text:

  • “Hey there      “

We can use the following syntax to define this variable and display its length in Bash:

my_var="Hey there      "

echo "${#my_var}"

We can then use the following syntax to remove all trailing whitespace from the variable and view its length again:

my_var="${my_var%"${my_var##*[![:space:]]}"}"

echo "${#my_var}"

The following screenshot shows how to use this syntax in practice:

Bash remove trailing whitespace from variable

Notice that when we use the echo statement to view the length of the my_var variable we can see that it originally had  a length of 15 and once we removed the trailing whitespace it had a new length of 9.

Example 2: Trim Trailing Whitespace Using sed

Once again, suppose that we have a variable named my_var that contains the following text:

  • “Hey there      “

We can use the following syntax to define this variable and display its length in Bash:

my_var="Hey there      "

echo "${#my_var}"

We can then use the following syntax with sed to remove all trailing whitespace from the variable and view its length again:

my_var="$(echo -e "${my_var}" | sed -e 's/[[:space:]]*$//')"

echo "${#my_var}"

The following screenshot shows how to use this syntax in practice:

Bash remove trailing whitespace from variable using sed

Notice that when we use the echo statement to view the length of the my_var variable we can see that it originally had  a length of 15 and once we removed the trailing whitespace it had a new length of 9.

Feel free to use whichever method you prefer to remove the trailing whitespace from your own variable.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Remove All Whitespaces from File
Bash: How to Remove Leading Zeros from a Variable
Bash: How to Remove First and Last Characters from String

Leave a Reply