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:

#!/bin/bash

name=default
if [ ! -z "$1" ]; then
  name="$1"
fi

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

#!/bin/bash

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

echo $name

Variation #2

#!/bin/bash

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 script.sh.

Give it executable permissions:

$ chmod +x script.sh

Run with or without an argument:

$ ./script.sh Dave
Dave
$ ./script.sh
default

Farewell

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

0 Comments
Code Chewing Twitter