We have ip rules
# ip rule ls
0: from all lookup local
100: from 10.10.0.114 lookup RT0
100: from 10.8.0.118 lookup RT0
100: from 10.10.0.97 lookup RT1
220: from all lookup 220
32766: from all lookup main
32767: from all lookup default
and we want to execute the following command according to the ip rule ls
result:
ip rule del from 10.10.0.114 lookup RT0
ip rule del from 10.8.0.118 lookup RT0
ip rule del from 10.10.0.97 lookup RT1
I have tried following command but got no luck
for i in $(ip rule ls | grep lookup | grep -v all | awk '{print $2,$3,$4,$5}'); do ip rule del $i;done
But it seems that was wrong
How can we do that?
CodePudding user response:
Try:
ip rule ls | awk '/lookup/ && !/all/{print "ip rule del", $2, $3, $4, $5;}' | sh
CodePudding user response:
You could try
#!/bin/bash
IFS='
'
for i in $(ip rule ls | grep lookup | grep -v all | awk '{print $2,$3,$4,$5}')
do
echo $i | xargs ip rule del
done
CodePudding user response:
Try this Shellcheck-clean pure Bash (except for the ip
) solution:
#! /bin/bash -p
ip rule ls | while read -r -a f; do
(( ${#f[*]} == 5 )) || continue
[[ ${f[1]} == from ]] || continue
[[ ${f[2]} != all ]] || continue
[[ ${f[3]} == lookup ]] || continue
ip rule del from "${f[2]}" lookup "${f[4]}"
done
It's hyper-picky about checking that the output from ip rule ls
has exactly the expected format because I've found that it pays to be very careful when writing code that deletes things.