Save command output on variable and check exit status

You should use $? instead of $#.

  • $? contains the return value from the last script.
  • $# contains the total number of arguments passed to a script or function.

Do something like below :

ip=$(dig +short google.com)
if [ $? -eq 0 ]; then
  echo "Success" # Do something here
else
  echo "Fail" # Fallback mode
fi

You can check the return or use command-substitution and check the resulting variable. e.g.

$ ip=$(dig +short google.com)
$ [ -n "$ip" ] && echo "all good, ip = $ip"

(you can do the reverse check for failure with -z


You can avoid accessing $?, and simply:

if ip=$(dig +short google.com); then
    # Success.
else
    # Failure.
fi

Example:

The following function will print "fail" and return 1.

print_and_fail() { printf '%s' fail; return 1; }

Thus, if we do the following:

if foo=$(print_and_fail); then printf '%s\n' "$foo";fi

We'll get no output, yet store print_and_fail output to $foo - in this case, "fail".

But, take a look at the following function, which will print "success" and return 0.

print_and_succeed() { printf '%s' success; return 0; }

Let's see what happens now:

$ if foo=$(print_and_succeed); then printf '%s\n' "$foo";fi
$ success

Tags:

Bash