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…
#!/bin/bash [ ! -z "$1" ] && name="$1" || name=default echo $name
#!/bin/bash name=$([ ! -z "$1" ] && echo "$1" || echo default) echo $name
Save one of the variations into a bash script file, say
Give it executable permissions:
$ chmod +x script.sh
Run with or without an argument:
$ ./script.sh Dave Dave $ ./script.sh default
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!