Bash script to check if route exists with netstat and grep

Recently while crafting a Vagrantfile I came across the need of checking if I had already added a route to my host when reload the vagrant box.

Listing routes

netstat -nr
  • -r shows the routing table
  • -n shows the network addresses as number

Matching the pattern

grep -co '172.17 *'
  • -c writes the number of matches to stdout
  • -o prints only the matching part of the line

Putting both commands together

if [ $(netstat -nr | grep -co '172.17 *') = 0 ]; then
        echo 'Adding gateway route for docker0 network'
        sudo route -n add " + $vb_ip_address + "