0

Hi guys im wondering how does || work when declaring variables? You can see this in the 3rd line in the code below. $output is set to a function and then the $error variable is set to the exit code of the previous command after the ||. What does || do in this situation/how is it handled?

 if [ "$ENABLED" = "yes" ] || [ "$ENABLED" = "YES" ]; then
    log_action_begin_msg "Starting firewall:" "ufw"
    output=`ufw_start` || error="$?"  <-- HERE
    if [ "$error" = "0" ]; then
        log_action_cont_msg "Setting kernel variables ($IPT_SYSCTL)"
    fi
    if [ ! -z "$output" ]; then
        echo "$output" | while read line ; do
            log_action_cont_msg "$line"
        done
    fi
else
    log_action_begin_msg "Skip starting firewall:" "ufw (not enabled)"
fi
rgo1991
  • 73
  • 5

2 Answers2

0

Just like && , || is a bash control operator: && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero). || means execute the statement which follows only if the preceding statement failed (returned a non-zero exit code).

0

In general, the exit status of an assignment is 0. But when a command substitution is present, the exit status is the exit status of the command substitution, in this case of ufw_start.

So if ufw_start fails, its non-zero exit status is stored in the variable error.

Also, since error is only used to see if its value is 0 or not, it could be eliminated altogether.

if output=$(ufw_start); then
    log_action_cont_msg "..."
fi
chepner
  • 497,756
  • 71
  • 530
  • 681
  • ah ok got it. so what happens during command substitution? does the command get executed internally somehow to get the exit status or is it just checked that the syntax has no errors/function exists? – rgo1991 Sep 16 '21 at 14:01
  • It gets executed: its output is what gets assigned to `output`. – chepner Sep 16 '21 at 14:03