0

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"
3
  • 2
    Could you elaborate a bit more? what do you mean afterwards, the variable instead reads a string, such as . Unless you set the variable it will be always be empty Commented Sep 9, 2020 at 11:14
  • Sorry, I mean changing the actual text of the file itself to be from RESULT= to RESULT="SUCCESS" Commented Sep 9, 2020 at 11:16
  • You don't have to explicitly set it to the empty string. if [ -z "$RESULT" ] (the quotes are important) has the same result whether RESULT is unset or is set but null. Commented Sep 9, 2020 at 13:51

2 Answers 2

1

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 ...)"
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

Also note, you can replace b0Gus with a command substitution like $(curl ...), and curl will only be executed if the default value is needed.
And/or you can use another variable as the new value.
The OP specifically mentioned running curl if the value is empty, so I though it worth emphasizing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.