Bash: How to Trim Leading Whitespace from a Variable


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

There are two common ways to do so:

Method 1: Trim Leading Whitespace Using Wildcards

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

Method 2: Trim Leading 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 Leading 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 with built-in Bash wildcards to remove the leading whitespace from the variable:

my_var="      Hey there"

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

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

Bash remove leading whitespace from variable

Notice that when we use the echo statement to view the updated my_var variable we can see that all of the leading whitespace has been removed.

Example 2: Trim Leading 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 with sed to remove the leading whitespace from the variable:

my_var=" Hey there"

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

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

Bash remove leading whitespace from variable using sed

When we use the echo statement to view the updated my_var variable we can see that all of the leading whitespace has been removed.

Feel free to use whichever method you prefer to remove the leading 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