Bash grep file for string and use each as a variable in another commands -


in ha configuration checking periodically vip address on eth0, (lets call 2.2.2.2). if up, need bring group of ip address defined eth0 in /etc/network/interfaces configuration file:

up ip addr add **1.2.3.34** dev $iface ip addr add **1.2.3.40** dev $iface ip addr add **1.2.3.48** dev $iface 

and pass each ip group of commands:

ip a **1.2.3.34/32** dev eth0 ip a **1.2.3.40/32** dev eth0 ip a **1.2.3.48/32** dev eth0 

what i've done far is:

#!/bin/bash status=$(ip s eth0 | grep inet | awk '{print $2}' | sed 's/addr://') if ip s eth0 | grep inet | awk '{print $2}' | sed 's/addr://' | grep 2.2.2.2/27 ; cat /etc/network/interfaces | grep -o "up ip addr add [0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" |  grep -o "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" > /tmp/ext_ip.txt 

now need how pass each line command mentioned above (ip a 1.2.3...), have no idea how properly.

optionally i'd revert operation if vip not present in system - in case if primary ha host go offline.

one way achieve parse ip addresses array , use for loop assign them interface:

#!/bin/bash  iface='eth0' vip='192.168.0.1' ifaces_file='/etc/network/interfaces'  status=$( ip address show "$iface" | grep -o "$vip" )  if [ ! -z "$status" ];     ip_addresses=( $( grep -o '[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*' "$ifaces_file" ) )      ip in "${ip_addresses[@]}";         ip address add "$ip" dev "$iface"     done fi 

this simplified example. may want add more checks, add logging messages provide output useful debugging. also, depending on server configuration commands may not work without sudo.


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -