Search code examples
bashwatcharchlinuxi3

script not executing all the way through


I wanted to replace ifplugd with a script, a deamon-like script that will be launched at startup by i3. Everything works fine when launching it from terminal, but whenever i try to auto launch it at startup, it gets killed instantly.

The command i use to launch it as i3 starts up:

exec ./.scripts/ifwatch enp0s25>ifwatch.log

The log file content:

[17:00:54]:Setting enp0s25 up
[17:00:55]:Listening on enp0s25

The script it self:

#!/bin/sh
dev=$1
echo [$(date +'%H:%M:%S')]:Setting $dev up
sudo ip link set $dev up
echo [$(date +'%H:%M:%S')]:Listening on $dev
while watch -n 5 -g ip link show dev $dev;
do
    if [[ -n $(ip link show dev $dev |tr '\n' ' ' | grep -v 'NO-CARRIER') ]];
    then
        echo [$(date +'%H:%M:%S')]:$dev "connected! running dhcpcd"
        echo $(sudo dhcpcd $dev)
    else
        echo [$(date +'%H:%M:%S')]:$dev "disconnected! killing dhcpcd"
        echo $(sudo dhcpcd -k $dev)
    fi

done

I tried to launch it in a screen instance (from the i3config file) but it didn't even created the socket, I also tried not sending the watch output buffer to /dev/null but it didn't help. I'm assuming the process get's instantly killed because at every startup the timestamp of the log file changes.


Solution

  • As Charles Duffy suggested i wrote a function to do the job of watch -g and now it works perfectly. As he said probably watch does not work outside of a TTY.

    Here's the code if anyone's intrested:

    #!/bin/sh
    dev=$1
    sleeptime=5
    
    function watcher {
        state1=$(ip link show dev $dev) 
        state2=$state1
        while [ "$state1" == "$state2" ];
        do
            sleep $sleeptime
            state2=$(ip link show dev $dev)
        done
        return 0
    }
    
    
    echo [$(date +'%H:%M:%S')]:Setting $dev up
    sudo ip link set $dev up
    echo [$(date +'%H:%M:%S')]:Listening on $dev
    while watcher;
    do
        if [[ -n $(ip link show dev $dev |tr '\n' ' ' | grep -v 'NO-CARRIER') ]];
        then
            echo [$(date +'%H:%M:%S')]:$dev "connected! running dhcpcd"
            sudo dhcpcd $dev
        else
            echo [$(date +'%H:%M:%S')]:$dev "disconnected! killing dhcpcd"
            sudo dhcpcd -k $dev
        fi
    
    done