bash variables magic


I often find myself searching for a, say, left() or mid() function when coding bash. Somehow my subconscious mind seems to know I’m doing too much in bash and therefore tends to forget things like a simple left() in bash. So I note them here. Lets hope I don’t forget where I wrote that down…

len() in bash

$ var='Hello, World!'
$ echo "${#var}"

left() in bash

$ var='Hello, World!'
$ echo "${var:0:5}"

right() in bash

$ var='Hello, World!'
$ echo "${var:7:${#var}}"
#or a litte more dynamic.. (the 6 most right chars)
echo "${var:$((${#var}-6)):${#var}}"

mid() in bash

$ var='Hello, World!'
$ echo "${var:4:4}"
o, W

string replace first in bash (substitute)

$ var='Hello, World!'
$ echo "${var/o/a}"
Hella, World!

string replace all in bash (substitute)

$ var='Hello, World!'
$ echo "${var//o/a}"
Hella, Warld!

Did I miss one?


  1. Love this, bookmarked.

    The last one will really cut down my use of sed and pipes in the middle of my scripts. :)

  2. Please make sure you double-quote your expansions in your examples; otherwise, terrible things can happen!

    See also:

  3. admin

    19.11.2013 at 08:49

    You are completely right! I updated the post accordingly!


  4. There’s also the remove matching prefix and suffix pattern operations:

    shortest prefix:
    echo ${var#*l} –> “lo, world!”
    longest prefix:
    echo ${var##*l} –> “ld!”

    shortest suffix:
    echo ${var%l*} –> “Hello, wor”
    longest suffix:
    echo ${var%%l*} –> “He”

    hope this won’t completely break due to comment restrictions ;)

    tl;dr: there’s prefix and suffix matching for removing parts of strings, my use case is stripping file name extensions mostly

  5. mr51m0n

    19.11.2013 at 12:35

    Uhhhh, I’ll do a followup post including them! Thanks!

Leave a Reply

Your email address will not be published.


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2014 netmess

Theme by Anders NorenUp ↑