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}|"

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 9 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
9 comments… add one
  • Philippe Petrinko Mar 26, 2010 @ 11:02

    Yeah right.
    (and may be credits for this topic goes to Bash hackers page and could be referenced?)

    Furthermore, if you want to get rid of all spaces,
    you can use another bash function: search and replace brace expansion
    that is :

    ${var// /}

    or using as you suggest the “Space” class [[:space:]] to grab all kind of spaces.
    (may be you should introduice a little character classes ?)


    As for instance:

    v=" some thing here ";echo ":$v:";echo ":${v//[[:space:]]/}:"

  • Zdenek Styblik Mar 26, 2010 @ 11:16

    ead -rd '' var <<< "$var"
    should be read

  • 🐧 nixCraft Mar 26, 2010 @ 12:05

    @ Zdenek:

    Thanks for the heads up.

    @Philippe: thanks for mentioning ${var// /} syntax.

  • Eric Shubert Mar 26, 2010 @ 15:36

    How about
    var=${var#*( )}
    or, if you prefer the space class,

    I believe the search and replace syntax is more appropriately ${var//^ /} in order to replace only leading spaces, as the problem specified.

  • bashme Mar 28, 2010 @ 2:32

    Yall have forgotten the easiest by far …
    t=" abc"; echo "|$t|" => | abc|
    t=$(echo $t); echo "|$t|" => |abc|

  • Philippe Petrinko Mar 28, 2010 @ 10:36

    @Vivek – Fine then, if you appreciate ${var// /} syntax, would you add it to your article,
    even if it is to get rid of all spaces, not just the leading ones.
    This way, readers would come naturally to it, instead of having to browse all comments.

    @Eric: I am afraid that neither of your proposal works.
    Did you first test them?
    If not, you should test before posting advice.
    And if you did, you should post an entire self-explanatory example.

    @bashme: No, because your proposal will trim leading _and_ trailing spaces, not just the leading ones. Check this:

    v=" abc def ghi ";echo ":$v:";v=$(echo $v);echo ":${v}:"

  • Eric Shubert Mar 28, 2010 @ 15:33

    @Philippe: – I did test both methods. Apparently not very effectively though. I can only guess that I dropped the leading | in my test echo at some point. Please accept my apology.

    I was attempting to utilize a feature of the extglob shell option. This was probably a bad idea from the beginning because the option is usually off by default, and this is a feature of Pathname Expansion, which is not really related to the problem at hand.

  • Jalal Hajigholamali Mar 31, 2010 @ 3:55

    Very useful topic

  • James Z Apr 2, 2010 @ 9:46

    Hi, the easist way is :)
    v=`echo $v`

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum