03. Substitution Operators :-, :=, :?, :+

It's extremely important that the variables in your shell scripts are set - otherwise the results can be disastrous!

Take, for example:

$ rm -r /Users/johnPC/$UNSET_VARIABLE
# Same as rm -r /Users/JohnPC/ if variable unset!

We wouldn't want to destroy our entire home folder, would we?

Luckily there are several ways around this, with the use of substitution operators.

The following four operators are used to substitute for a variable if its value is null. Assume we have an unset variable named $TEST.

1) Simply return -

With the dash (-), we can simply return the value if our variable is not set.

#!/bin/bash
echo "${TEST:-hello world}"
echo "$TEST"
$ ./test
hello world
 

2) Set and return =

With the =, we may set the value, and also return it.

#!/bin/bash
echo "${TEST:=hello world}"
echo "$TEST"
$ ./test
hello world
hello world

3) Abort if unset ?

To abort the entire program if the variable is unset, use the question mark (?).

#!/bin/bash
echo "${TEST:?hello world}"
echo "$TEST"
$ ./test
./test: line 2: TEST: hello world

4) Inverse +

We may also return a different value if the variable is set with the plus symbol (+).

#!/bin/bash
echo "${TEST:+hello world}"
echo "$TEST"
$ ./test
 
 

Since our $TEST variable is unset, we return nothing.

Take your Linux skills to the next level!

How Linux Works

Take your Linux skills to the next level! Try Linux & UNIX

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Ad