Bash Shell: Trim Leading White Space From Input Variables

My script depends upon $1 to take certain actions:

echo “|${file}|”

However, sometime there will leading while space which will result into:

|     output.txt|

How do I trim leading white space from one of my input variables?

There are many ways to remove leading white space from input variables. The simplest one use the read command as follows:

var="    output.txt"
echo "|$var|"

Sample outputs:

|    output.txt|

Use the read command to get rid of white space:

read  -rd '' var <<< "$var"
echo "|$var|"

Sample outputs:



You can also use extglob shell option (Bash v2.2+) to turn on or off the extended pattern matching features.

var="         output.txt"
shopt -q -s extglob
echo "|${var##+([[:space:]])}|"
shopt -q -u extglob

You can store result to var itself:

echo "|${var}|"

The above syntax also works with ksh shell.

sed command

You can also use sed (see Here strings):

var="      output.txt"
var=$(sed -e 's/^[[:space:]]*//' <<<"$var")
echo "|${var}|"

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.