Conditionally assign value to a variable in bash

Goal: A bash script that accepts one argument. If the argument isn't provided, then set a default value.

This is the kind of conditional assignment I wanted to avoid:


if [ ! -z "$1" ]; then

echo $name

There's nothing bad with this, I just felt it was a more verbose outcome than what I had in mind. I wanted something that more closely resembled a ternary operator, which leads us nicely onto the following variations…

Variation #1


[ ! -z "$1" ] && name="$1" || name=default

echo $name

Variation #2


name=$([ ! -z "$1" ] && echo "$1" || echo default)

echo $name

Using the conditional assignment script

Save one of the variations into a bash script file, say

Give it executable permissions:

$ chmod +x

Run with or without an argument:

$ ./ Dave
$ ./


I'm sure there are other variations I've missed, and I don't know which one in particular I prefer, but it's good to know of a few different options!

Stay up-to-date...

@codechewing is where we always announce the release of any new guide - follow us to keep updated.

Join in

Code Chewing Twitter