Save command output on variable and check exit status
<p>The following command will resolve google ip</p>
<pre><code>&gt; ip=`dig +short google.com`
&gt; echo $ip
&gt; 216.58.210.238
</code></pre>
<p>Sometimes (especially when internet connection is lost) this command fail with this error</p>
<pre><code>&gt; ;; connection timed out; no servers could be reached
</code></pre>
<p>When the command fail and I use <code>$#</code> the output is 0 for the assigment</p>
<pre><code>&gt; ip=`dig +short google.com`
&gt; echo $#
&gt; 0
&gt; echo $ip     # Command failed
&gt; ;; connection timed out; no servers could be reached
</code></pre>
<p>How can I save the output of command in variable, and also check if the command succeeded?</p>