David Stegmüller
David Stegmüller

Reputation: 11

Linux Command Results in a bash Variable

I am trying to write a Ping result bash code.

this way it work, but i'm not a fan of using the last ouput function:

#!/bin/bash

ping -q -c2 10.10.50.120 > /dev/null
resp=$?
echo "$resp"
if [ "$resp" == 0 ]
then
    echo "ok"
else
  echo "not ok"
fi

Ouput:

0
ok

but this way it doesn't work:

#!/bin/bash

resp=$(ping -q -c2 10.10.50.120 > /dev/null)
echo "$resp"
if [ "$resp" == 0 ]
then
    echo "ok"
else
  echo "not ok"
fi

Ouput:

not ok

Can anyone help me to find out how to write it correctly?

Upvotes: 0

Views: 1212

Answers (1)

KamilCuk
KamilCuk

Reputation: 141493

I wanted to avoid the "$?" function.

That's great. So just use if.

if output=$(ping -q -c2 10.10.50.120); then
# or like: if ping -q -c2 10.10.50.120 >/dev/null; then
    echo "ok"
else
    echo "not ok"
fi
echo "Anyway, ping command ouptutted: $output"

It is possible to save the exit status to a variable without the "$?" function?

No.

Upvotes: 3

Related Questions