I am trying to run a Shell script which fails at grep state, below is what I am running
activeIP=`grep -Po '(?<=active.server.ip=).*' /etc/active.properties`
command="ifconfig | grep "$activeIP
eval "$command"
if [ $? == 0 ]; then
echo"You are on Active"
else
echo"You are not on Active"
fi
active.server.ip=10.25.15.1
standby.server.ip=10.25.15.2
Please help......
I would use a different tool for parsing the file, and also I'd avoid the eval
since it's so easy to go wrong with that. So using awk
, and assuming you're using bash
I'd do it like:
activeIP=$(awk -F= '$1 == "active.server.ip" {print $2}' /etc/active.properties)
if ip addr show | grep -qw "$activeIP"; then
echo "You are on Active"
else
echo "You are not on Active"
fi
First we use awk
with -F=
to split fields on =
. Then if the first field is equal to active.server.ip
we'll print the second field. Note, if you have/allow whitespace around the =
this will need to be changed a bit. We store that printed value in activeIP
just as you did in your attempt.
Next, we check if the given IP shows up in our current IP list. The ip
command is the newer version of ifconfig
, so I swapped for that. There's no need to build a string and eval
it because bash will already do variable substitution as when it's executing the command.
We'll use grep
to check the output of the ip addr show
command, and we add the -w
to match words, so if our IP is a substring of another IP it won't match (eg, the string 192.168.114.3
will not match the IP 192.168.114.37
). Also, since we don't actually care about the matching line, I added -q
to make it run quietly.
Finally, if
will look at the exit status already, so we don't have to do an explicit test for $?
.
As another possible step reduction, we could actually skip storing the IP in a variable and let bash
do process substitution for us like so:
if ip addr show | grep -qw $(awk -F= '$1 == "active.server.ip" {print $2}' /etc/active.properties); then
echo "You are on Active"
else
echo "You are not on Active"
fi
So it will do the awk
"in line" as it were.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.