* FIX: use 'tr' to replace repeated SPACE with a single SPACE before 'cut' lines
[lab.git] / iproute / setroute.sh
old mode 100644 (file)
new mode 100755 (executable)
index e88bdc6..59102fa
@@ -1,43 +1,58 @@
 #!/bin/sh
 
+# set individualized routing table and policy for each network device
+
+
 set -x
 
-IF="${1:?"usage: $0 <ether_device> [gateway] "}"
-GATEWAY=$2
+## INTERFACES(5)
+# IFACE  physical name of the interface being processed
+# METHOD method of the interface (e.g., static)\r
+# MODE   start if run from ifup, stop if run from ifdown\r
+# PHASE  as per MODE, but with finer granularity, distinguishing the pre-\r
+#        up, post-up, pre-down and post-down phases.\r
+
+# optional arugument to set default gateway manually
+GATEWAY=$1
 
-TID=`/sbin/ip addr show dev ${IF} | grep -w ${IF}: | cut -d : -f 1`
+TID=`/sbin/ip addr show dev ${IFACE} | grep -w ${IFACE}: | tr -s ' ' | cut -d : -f 1`
 
-if [ "${GATEWAY}" = "down" ]; then
+if [ "${PHASE}" = "post-down" ]; then
     # delete routing table and policy and exit
     ## routing table is automatically flushed, so 'route flush' can be removed
     /sbin/ip route flush table ${TID}
     ## device has no longer any IP addr, so do not use IPADDR
     /sbin/ip rule del table ${TID} priority ${TID}
     /sbin/ip route flush cache
-    echo "remove routing table and policy for ${IF}"
+    echo "remove routing table and policy for ${IFACE}"
     exit
 fi
 
 
 # get IP address, network mask, default gateway info
-IPADDR=`/sbin/ip addr show dev ${IF} | grep -w inet | cut -d t -f 2 | cut -d ' ' -f 2 | cut -d / -f 1`
-NETWORK=`/sbin/ip route show dev ${IF} | grep -w ${IPADDR} | cut -d ' ' -f 1`
+IPADDR=`/sbin/ip addr show dev ${IFACE} | grep -w inet | tr -s ' ' | cut -d ' ' -f 3 | cut -d / -f 1`
+if [ -z "${IPADDR}" ]; then
+    # fail to bind IP address to device
+    echo "${IFACE} has no IP address."
+    exit
+fi
+NETWORK=`/sbin/ip route show dev ${IFACE} | grep -w ${IPADDR} | tr -s ' ' | cut -d ' ' -f 1`
 
 if [ -z "${GATEWAY}" ]; then
-    GATEWAY=`/sbin/ip route show dev ${IF} | grep -w default | cut -d ' ' -f 3`
+    GATEWAY=`/sbin/ip route show dev ${IFACE} | grep -w default | tr -s ' ' | cut -d ' ' -f 3`
 fi
 if [ -z "${GATEWAY}" ]; then
-    GATEWAY=`/sbin/ip route | grep -w default | cut -d ' ' -f 3`
+    GATEWAY=`/sbin/ip route | grep -w default | tr -s ' ' | cut -d ' ' -f 3`
     # this may add wrong default route especially on RHEL
 fi
 
 
 # set routing table
-/sbin/ip route add ${NETWORK} dev ${IF} table ${TID}
-/sbin/ip route add default via ${GATEWAY} dev ${IF} table ${TID}
+/sbin/ip route add ${NETWORK} dev ${IFACE} table ${TID}
+/sbin/ip route add default via ${GATEWAY} dev ${IFACE} table ${TID}
 
 # set routing policy
 /sbin/ip rule add from ${IPADDR} table ${TID} priority ${TID}
 
 /sbin/ip route flush cache
-echo "add routing table and policy for ${IF} on table ${TID}"
+echo "add routing table and policy for ${IFACE} on table ${TID}"