我想验证用户是否在鞭子尾对话框中输入正确的设备或用户输入错误的东西。
我在谷歌上搜索了2天,找不到任何类似的问题。
这是我的代码:
ALL_DEVICES=$(ifconfig -a | grep Ethernet | awk '{print $1}' | tr 'n' ' ' | sed -e 's/[[:space:]]*$//')
U_INPUT=$(whiptail --title "[choose]" --inputbox "Please input your device" 0 0 all 3>&1 1>&2 2>&3)
如果我回显"$ALL_DEVICES",我将得到:eth0 wlan0
假设用户输入:eth wlan0 wlan1
我怎样才能告诉用户他输入正确:wlan0,但是eth和wlan1是错误的输入,因为那个设备不存在。
我试过这个代码:
ALL_DEVICES=$(ifconfig -a | grep Ethernet | awk '{print $1}' | tr 'n' ' ' | sed -e 's/[[:space:]]*$//')
U_INPUT=$(whiptail --title "[choose]" --inputbox "Please input your device" 0 0 3>&1 1>&2 2>&3)
arr1=("$ALL_DEVICES")
arr2=("$U_INPUT")
echo "arr1 ${arr1[@]}"
echo "arr2 ${arr2[@]}"
FOUND="echo ${arr1[*]} | grep ${arr2[*]}"
if [ "${FOUND}" != "" ]; then
echo "Valid interfaces: ${arr2[*]}"
else
echo "Invalid interfaces: ${arr2[*]}"
fi
非常感谢
我会这样写:
devices="eth0 wlan0"
input="eth0 whlan0 wlan0"
#translate output strings to array based on space
IFS=' ' read -r -a devicesa <<< "$devices"
IFS=' ' read -r -a inputa <<< "$input"
for i in "${inputa[@]}"
do
for j in "${devicesa[@]}"; do
if [ ${i} == ${j} ]; then
correct=1
break
else
correct=0
fi
done
if [ $correct = 1 ]; then
echo "device $i is correct"
else
echo "device $i isnt correct"
fi
done
也许它可以更简化,但您可以阅读要做的步骤。首先遍历字符串数组,查找设备,然后将它们与用户输入进行比较,并写入查找值。最后一步是澄清是否找到了该值。