user53029
user53029

Reputation: 695

need help modifying a script to check service status

I have a script that gets called up remotely that will check the status of a service and echo whatever I tell it to. The external process that calls the script up determines the service that gets checked. Instead of echoing a custom message I need it to echo back out the actual output of the command. Here is my script as it is now:

#!/bin/bash
S1="active"
Info=$(systemctl status $1 | awk 'NR==3' | awk '{print $2}')
if [ $Info == $S1 ]
then
    echo  $1 "is running!"
    exit 0
else
    echo  $1 "is not running!"
    exit 2
fi

As you can see, its pretty basic and scripting is not my cup of tea but this works. However I need make it more complex. In the script instead of echoing back out "$1 is running" or "$1 is not running" I need to change those 2 to actually echo the result from the command giving me the 3rd line only. So I need the echo to be like this:

Active: active (running) since Fri 2015-10-30 14:58:47 CDT; 1h 7min   ago

Which is the actual result of the command in the script now excluding awk '{print $2}'

And if the result comes back "active running" or "active exited", etc.. it needs to exit with 0. If the result comes back with anything other than that, exit with 2. This seems fairly simple but I am having a hard time wrapping my head around what changes I need to make. Thanks in advance for the help and please be detailed.

Upvotes: 0

Views: 1842

Answers (1)

Barmar
Barmar

Reputation: 780818

Put the entire line in Info, not just the second field. Then extract the second field from that to check it.

info=$(systemctl status $1 | awk 'NR == 3')
read prefix status rest <<<"$info"
echo "$info"
if [ $status = $S1 ]
then
    exit 0
else
    exit 2
fi

Upvotes: 2

Related Questions