[英]How to verifiy if IP is used by particular server or not using Shell script?
I am trying to run a Shell script which fails at grep state, below is what I am running 我正在尝试运行在grep状态失败的Shell脚本,以下是我正在运行的脚本
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. 我将使用其他工具来解析文件,并且我也避免使用
eval
因为这样做很容易出错。 So using awk
, and assuming you're using bash
I'd do it like: 因此,使用
awk
,并假设您正在使用bash
我会这样做:
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 =
. 首先,我们使用
awk
与-F=
对分割字段=
。 Then if the first field is equal to active.server.ip
we'll print the second field. 然后,如果第一个字段等于
active.server.ip
我们将打印第二个字段。 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. 就像您尝试的那样,我们
activeIP
打印的值存储在activeIP
中。
Next, we check if the given IP shows up in our current IP list. 接下来,我们检查给定的IP是否显示在当前IP列表中。 The
ip
command is the newer version of ifconfig
, so I swapped for that. ip
命令是ifconfig
的较新版本,因此我换成了。 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. 无需构建字符串并进行
eval
,因为bash在执行命令时已经进行了变量替换。
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
). 我们将使用
grep
来检查ip addr show
命令的输出,并添加-w
以匹配单词,因此,如果我们的IP是另一个IP的子字符串,则它将不匹配(例如,字符串192.168.114.3
将与IP 192.168.114.37
不匹配)。 Also, since we don't actually care about the matching line, I added -q
to make it run quietly. 另外,由于我们实际上并不关心匹配的行,因此我添加了
-q
使其安静运行。
Finally, if
will look at the exit status already, so we don't have to do an explicit test for $?
最后,
if
已经查看退出状态,那么我们不必对$?
做显式测试$?
. 。
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: 作为另一个可能的减少步骤,我们实际上可以跳过将IP存储在变量中,然后让
bash
像这样为我们做进程替换:
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. 因此,它将按原样执行
awk
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.