Skip to end of metadata
Go to start of metadata

Default values

Most people know a variable can be referenced as ${FOO}, but you can put extra syntax inside the { } that can save you some if/else blocks.

If null, use default value

mingus:~ 07:47:10 
$ export FOO=first

mingus:~ 07:48:58 
$ echo "The ${FOO-second} choice"
The first choice

mingus:~ 07:51:49 
$ unset FOO

mingus:~ 07:51:56 
$ echo "The ${FOO-second} choice"
The second choice

mingus:~ 07:51:59 
$ export FOO=

mingus:~ 07:52:03 
$ echo "The ${FOO-second} choice"
The  choice

If null or empty, use default value

mingus:~ 07:52:06 
$ export FOO=first

mingus:~ 07:53:39 
$ echo "The ${FOO:-second} choice"
The first choice

mingus:~ 07:53:44 
$ unset FOO

mingus:~ 07:53:52 
$ echo "The ${FOO:-second} choice"
The second choice

mingus:~ 07:53:56 
$ export FOO=

mingus:~ 07:54:04 
$ echo "The ${FOO:-second} choice"
The second choice

Default value can be a variable

mingus:~ 07:55:06 
$ export FOO=first

mingus:~ 07:55:47 
$ export BAR=second

mingus:~ 07:56:01 
$ echo "The ${FOO:-$BAR} choice"
The first choice

mingus:~ 07:56:15 
$ unset FOO

mingus:~ 07:56:51 
$ echo "The ${FOO:-$BAR} choice"
The second choice

Default value can be a command

mingus:~ 08:08:02 
$ export FOO="Friday"

mingus:~ 08:08:10 
$ date +%A
Wednesday

mingus:~ 08:08:15 
$ echo "Today is ${FOO:-$(date +%A)}"
Today is Friday

mingus:~ 08:08:19 
$ unset FOO

mingus:~ 08:08:26 
$ echo "Today is ${FOO:-$(date +%A)}"
Today is Wednesday
Labels
  • None