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:

LOGTIME=`date "+%Y-%m-%d %H:%M:%S"`
route -n | grep -v grep | grep > /dev/null
if grep -q >/dev/null
     echo "$LOGTIME : Does not exist - OK.." >> $LOGFILE 2>&1
    echo "$LOGTIME : : Exist - Updating routing table." >> $LOGFILE 2>&1 | echo "$LOGTIME : : Exist - Updating routing table."
    ip route delete via
    ip route add via dev tun0
  • 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 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

There are several issues with your script.

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

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

Then test the result of your command like so:

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

This idiom could be simplified, to something like:

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


route -n | grep -q ''
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.