2

If I add a route with

ip route add 172.10.1.0/24 via 10.0.0.100 dev eth0

and then execute the same command a second time, it fails because the route is already present.

I don't see that behavior documented anywhere. Is it safe to depend on this behavior, or might different / future versions of Linux allow duplicate routes?

use-case

I'm writing a bash script that configures the routing table. I want to make it safe to run the script multiple times.

I see two options:

  • Put the ip route add command within an if statement that runs ip route list and uses regex to check if the route is already in place.

  • Just run ip route add and ignore if it fails because the route already exists.

The first doesn't seem very robust, as I have to depend on the output format of ip route list. The second seems to depend on undocumented behavior.

1
  • 1
    No. You can add multiple routes just now if they have different metrics: for m in 1 2 3; do ip route add 172.10.1.0/24 via 10.0.0.100 dev eth0 metric $m; done. A route with a metric != 0 is still a route. You don't have to use ip list | grep regex (yuck), you can check for the existence of a route explicitly: just replace the add with list in your command.
    – mosvy
    Dec 4, 2019 at 21:50

1 Answer 1

4

You can use ip route replace instead of add.

This takes the same parameters as add but does not fail, when the route currently exists.

As man ip-route tells us

ip route replace
change or add new one

it will silently add the route when it is not already set and "change"(replace) it with whatever you specify.

1
  • This is very nice! Thanks a lot. Too bad the same does not exist ip rule.
    – Stefan
    Dec 4, 2019 at 22:59

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.