我在 bash 上写过脚本。它获取了所有接口列表。并在循环中与变量进行了比较。但效果不佳。我的脚本:
#!/bin/bash
search=`ls -1 /sys/class/net | grep -v lo`
echo $search
eth=eno1
echo $eth
for i in $search; do
if [ $i == $eth ]; then
echo "You choose is: $i"
else
echo "not found"
fi
done
结果我得到了:
dummy0 eno1 enp4s0 virbr0 virbr0-nic
eno1
not found
You choose is: eno1
not found
not found
not found
没问题。我想得到一条消息“您选择的是:eno1”。如果 $eth 不包含在“/sys/class/net”中,我想得到消息“未找到”。我哪里错了?请帮忙。谢谢。
答案1
用一个 if 语句替换整个循环,如下所示:
if [[ "$eth" =~ "$search" ]];then
echo "You choose is: $eth"
else
echo "not found"
fi
整个脚本非常紧凑:
#!/bin/bash
eth=eno1
if [ -d /sys/class/net/$eth ];then
echo "You choose is: $eth"
else
echo "not found"
fi