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?
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 ...]
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.
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.
You can avoid accessing $?
, and simply:
if ip=$(dig +short google.com); then
# Success.
else
# Failure.
fi
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With