bash script to trigger on and off events from journalctl

Viewed 20

I am trying to write a bash script to set a variable "status" to either online or offline. I use logger "trigger offline" and logger "trigger online" for simplicity.

The offline event triggers ok, and I can see the output correct in journalctl, but when the online event is sent by logger, the variable £status is still offline. If its offine, I want it to restart the NetworkManger until the event online is triggered. thanks

!/bin/bash
journalctl -fqn0 | \
while read line
        do

        #trigger if offline
        echo "$line" | grep "trigger offline"
        if [ $? = 0 ]
        then
                status="offline"
        fi

        #trigger if online
        echo "$line" | grep "trigger online"
        if [ $? = 0 ]
        then
               status="online"
        fi

        sleep 3
        logger "Status is $status"

        if [[ $status="offline" ]]
        then
                #restart the network here
                logger "do some stuff"
        fi

        done
1 Answers
if [[ $status="offline" ]]

when $status is online means

if [[ online=offline ]]

online=offline is a single string. [[ string ]] is true if string is non zero. Which is the case.

You wanted to use the string comparison, to call [[ with 3 arguments (not counting the closing ]]), a string, a = and another string, not just one.

In other words

if [[ $status = "offline" ]]

with the correct spaces.

Another thing unrelated to your error, but related to the next one: I surmise that all line won't contain either 'online' or 'offline'. So, $status maybe empty (at least at the beginning. Then, it will be whatever it already was for all lines not related to your status. Which may be a 3rd error, but that an applicative problem I can not judge whether this is a problem or not. I do have the feeling that you don't want to log a status line each time a totally unrelated event is shown by journalctl tho. So you may want to reset status to "" at each loop. Not sure. Your call).

But the important point is, whatever you choose, $status maybe the empty string. In which case, your if will become if [[ =offline ]] which is true, and mine if [[ = offline ]] which is a syntax error. To avoid that, you want to enclose $status in double quotes

So :

if [[ "$status" = "offline ]]
Related