1

I am getting dhcp server status using service dhcpd status. Result is

Redirecting to /bin/systemctl status dhcpd.service ● dhcpd.service - DHCPv4 Server Daemon Loaded: loaded (/usr/lib/systemd/system/dhcpd.service; enabled; vendor preset: disabled)

Active: active (running) since......

I just want to extract active and send to php (Zend) server. To do it, I used

service dhcpd status | awk '{for (I=1;I<=NF;I++) if ($I == "Active:") {print $(I+1)};}'

Result is

Redirecting to /bin/systemctl status dhcpd.service

active

I just don't understand how to remove Redirecting to /bin/systemctl status dhcpd.service part from the result.

I have tried these answers, but they were not addressing my issue.

Am I missing something? or is there a better way to do it? I am not familiar with shell scripts.

Thanks in advance.

Sachith Muhandiram
  • 2,819
  • 10
  • 45
  • 94

1 Answers1

3

Just use Awk looking for the Active: string and print the status

service dhcpd status 2>&1 | awk '$1=="Active:"{print $2}'

The part $1="Active:" looks up the line whose first column value is Active: and print the next column value which is the status you are looking for.

As suggested above, redirect the stderr, the standard error stream to stdout and apply Awk on it to filter the error message.


As suggested by anubhava in comments you could use |& in recent versions of bash to redirect stderr to stdout as

service dhcpd status |& awk '$1=="Active:"{print $2}'
Inian
  • 80,270
  • 14
  • 142
  • 161