To add multiple IPv4 routes using the ip route add command on Linux, you can specify each route individually or use a loop in a script if you have many routes to add. Here’s how you can do it:
You can manually add each route using the following syntax:
bashsudo ip route add <network>/<prefix> via <gateway> dev <interface>
Example:
bashsudo ip route add 192.168.1.0/24 via 192.168.0.1 dev eth0 sudo ip route add 10.0.0.0/8 via 10.0.0.1 dev eth1
If you have many routes, you can use a for loop in a shell script:
bash#!/bin/bash # Define an array of routes routes=( "192.168.1.0/24 via 192.168.0.1 dev eth0" "10.0.0.0/8 via 10.0.0.1 dev eth1" "172.16.0.0/16 via 172.16.0.1 dev eth2" ) # Add each route for route in "${routes[@]}"; do sudo ip route add $route done
Save the script (e.g., add_routes.sh), make it executable (chmod +x add_routes.sh), and run it.
The above commands only add routes temporarily. To make them persistent after a reboot, you need to add them to your network configuration. The method depends on your Linux distribution:
Edit /etc/network/interfaces or create a script in /etc/network/if-up.d/.
Edit /etc/sysconfig/network-scripts/route-<interface>.
Create a .network file in /etc/systemd/network/ or use netplan if applicable.
To check if the routes were added successfully, run:
baship route show