user321627
user321627

Reputation: 2564

How to in-line modify a variable in a shell script?

I have a shell script that sets a variable RESULT= as empty to begin with. Then, the script makes a curl get request if RESULT is empty (if [ -z $RESULT ];then...), and then prints it out, telling the user to set the empty variable.

I am wondering if there is a way for me to in-line modify the RESULT variable only if it is empty, so that afterwards, the variable instead reads a string, such as

RESULT="SUCCESS"

Upvotes: 0

Views: 221

Answers (2)

chepner
chepner

Reputation: 531045

Simply use

: ${RESULT:=$(curl ...)

If RESULT is initially empty or unset, curl will run and its output assigned to RESULT. Otherwise, curl is not run, and RESULT retains whatever value it started with. (Note that RESULT may be an environment variable, with a value before the script actually starts.)

You can extend this to handle arguments as well.

# :-, not :=
RESULT=${1:-$(curl ...)}

curl only runs if the first argument is the empty string or not present:

yourScript
yourScript ""

Otherwise, it assigns whatever the first argument is to RESULT:

yourScript "$(curl ...)"

Upvotes: 1

Paul Hodges
Paul Hodges

Reputation: 15273

Supply an assigning default.

if [[ b0Gus == "${RESULT:=b0Gus}" ]]; then... # RESULT now b0Gus if it was empty

This returns the value of RESULT if it has one, else it sets it and returns that. Note that it is more like ((++x)) than ((x++)) in that it applies the change before returning the content to the test operator.

If you use a dash instead of equals, it returns the alternate value, but doesn't set the variable -

if [[ b0Gus == "${RESULT:-b0Gus}" ]]; then... # RESULT still empty after match

See https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html for more.

You can apply this by passing it as args to a no-op, too.

: ${RESULT:=b0Gus}

The : just returns true, but the parser still evaluates its arguments, which will set the var if empty - this is similar to a Perl ||= assignment, though that isn't inline.

Upvotes: 1

Related Questions