Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save command output on variable and check exit status

Tags:

bash

The following command will resolve google ip

> ip=`dig +short google.com`
> echo $ip
> 216.58.210.238

Sometimes (especially when internet connection is lost) this command fail with this error

> ;; connection timed out; no servers could be reached

When the command fail and I use $# the output is 0 for the assigment

> ip=`dig +short google.com`
> echo $#
> 0
> echo $ip     # Command failed
> ;; connection timed out; no servers could be reached

How can I save the output of command in variable, and also check if the command succeeded?

like image 526
Nasr Avatar asked Apr 28 '16 17:04

Nasr


People also ask

How do you save output of command in a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

What is the command to check exit status?

Checking Exit Status of Command command to get the status of executed command. for exmaple, if you have executed one command called “ df -h “, then you want to get the exit status of this command, just type the following command: $ echo $? From the above outputs, you can see that a number 0 is returned.

Which variable gives the exit status of last executed command?

variable in Linux. “$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred.


1 Answers

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
like image 118
Rany Albeg Wein Avatar answered Sep 23 '22 09:09

Rany Albeg Wein