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:
1. Adding Routes Individually
You can manually add each route using the following syntax:
sudo ip route add <network>/<prefix> via <gateway> dev <interface>
Example:
sudo 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
2. Adding Multiple Routes Using a Script
If you have many routes, you can use a for loop in a shell script:
#!/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.
3. Persisting Routes After Reboot
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:
Debian/Ubuntu:
Edit /etc/network/interfaces or create a script in /etc/network/if-up.d/.
RHEL/CentOS:
Edit /etc/sysconfig/network-scripts/route-<interface>.
Systemd-based systems:
Create a .network file in /etc/systemd/network/ or use netplan if applicable.
4. Verifying Added Routes
To check if the routes were added successfully, run: