-2

I'm trying to make a script on my Linux machine that will grep for a specific routing in my routing table and execute command depends on the find. This is what I have so far and it's not working:

#!/bin/bash
LOGFILE=/root/check/logfile.log
LOGTIME=`date "+%Y-%m-%d %H:%M:%S"`
route -n | grep -v grep | grep 192.168.38.2 > /dev/null
if grep -q 192.168.38.2 >/dev/null
then
     echo "$LOGTIME : 192.168.38.2: Does not exist - OK.." >> $LOGFILE 2>&1
else
    echo "$LOGTIME : 192.168.38.2 : Exist - Updating routing table." >> $LOGFILE 2>&1 | echo "$LOGTIME : 192.168.38.2 : Exist - Updating routing table."
    ip route delete 192.168.34.0/24 via 192.168.38.2
    ip route add 192.168.34.0/24 via 192.168.38.5 dev tun0
fi
  • 3
    Please don't just tell us "it's not working". We need to know how it is failing. Does it not run? Does it run but not do what you want? Does it make your computer explode? That sort of thing. What is the if grep -q 192.168.38.2 line doing? You haven't given grep any input, what are you expecting it to do? What should it be grepping? Also, what's the point of the grep -v grep there? Why would you have the string grep in your route -n output? – terdon Mar 11 at 12:46
2

There are several issues with your script.

To perform simple pass / fail checks with grep consider the following idiom:

fail=$(route -n | grep -q '192.168.38.2'; echo $?)

Then test the result of your command like so:

if [ "$fail" -ne 0 ]; then
    # Handle failure
else
    # Handle success
fi

This idiom could be simplified, to something like:

if [ $(route -n | grep -q '192.168.38.2'; echo $?) ] then
    ...

or

route -n | grep -q '192.168.38.2'
if [ "$?" ]; then
    ...

However, I would recommend taking the time to understand the commands your are running rather than just copying something that you do not understand (like grep -v grep).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.