Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash substitution: log when variable is not set

Tags:

bash

I use bash substitutions to give neat one-line validation for input, e.g.:

#!/bin/bash
export PARAM1=${1?Error, please pass a value as the first argument"}
# do something...

In some cases though, I want to only log a message when something is unset and then continue as normal. Is this possible at all?

like image 938
Alex Avatar asked Dec 01 '25 16:12

Alex


2 Answers

Maybe something along the lines of

test -n "$1" && export PARAM1="$1" || log "\$1 is empty!"

should do; here the test clause returns true if and only if $1 is non-empty.

like image 103
Roberto Reale Avatar answered Dec 04 '25 08:12

Roberto Reale


For regular parameters (in bash 4 or later), you can use the -v operator to check if a parameter (or array element, as of version 4.3) is set:

[[ -v foo ]] || echo "foo not set"
bar=(1 2 3)
[[ -v bar[0] ]] || echo "bar[0] not set"
[[ -v bar[8] ]] || echo "bar[8] not set"

Unfortunately, -v does not work with the positional parameters, but you can use $# instead (since you can't set, say, $3 without setting $1).

(( $# >= 3 )) || echo "third argument not set"

Before -v became available, you would need to compare two default-value expansions to see if a parameter was unset.

[[ -z $foo && ${foo:-bar} == ${foo-bar} ]] && echo "foo is unset, not just empty"

There's nothing special about bar; it's just an arbitrary non-empty string.

like image 24
chepner Avatar answered Dec 04 '25 07:12

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!