我可以使用一些帮助来弄清楚以下脚本中的省略号为什么不起作用。 if的第一部分有效,而语句的else部分有效,而elif无效。换句话说,当我以“ root”身份登录时,会得到我期望的DNS地址。如果我以Guest身份登录,则可以获得我期望的DNS地址,但如果我以elif中列出的任何学生身份登录,则不会。
#!/bin/bash
\# Setting DNS by User
\# Get variables. $3 is logging in user.
user=$3
\# Root and Admin should be wide open
if [ $user = "root" ] || [ $user = "admin" ]; then
networksetup -setdnsservers Wi-Fi 8.8.8.8
networksetup -setdnsservers Ethernet 8.8.8.8
\# Older students get an open, but filtered experience:
elif
\# Adams class
[ $user = "Student01" ] ||
[ $user = "Student02" ] ||
[ $user = "Student03" ] ||
[ $user = "Student04" ] ||
\# Mariannes class:
[ $user = "Student05" ] ||
[ $user = "Student06" ] ||
[ $user = "Student07" ] ||
[ $user = "Student08" ]
then
networksetup -setdnsservers Wi-Fi 8.8.4.4
networksetup -setdnsservers Ethernet 8.8.4.4
\# Everyone else gets whitelisted DNS
else
networksetup -setdnsservers Wi-Fi 208.67.222.222
networksetup -setdnsservers Ethernet 208.67.222.222
fi
exit 0
答案 0 :(得分:1)
我的第一个想法是,这实际上不是一种可维护的方法。这是 我认为)不是使用if / elif / if / fi结构的方式。
也就是说,我将向您抛出一些高级脚本,该脚本将执行以下操作 您想要的并且更受支持。
首先,我建议在bash数组中保留管理员和学生的姓名。最终, 您可以从其他来源(例如文件: 注释)。如图所示,这将使if / elif测试更加简单。
#! /usr/bin/env bash
# Setting DNS by User
# Get variables. $3 is logging in user.
user=$3
# admin_list=$HOME/admin.list
# declare -a admins
# if [[ -f "$admin_list" ]] ; then
# IFS=$'\n' read -d '' -r -a admins < <(sed -e 's/#.*$//' "$admin_list")
#
# wait $! || return $?
# else
# echo "$admin_list not found: skipping"
# fi
declare -a admins=( root admin )
# special_list=$HOME/special.list
# declare -a special
# if [[ -f "$special_list" ]] ; then
# IFS=$'\n' read -d '' -r -a special < <(sed -e 's/#.*$//' "$special_list")
#
# wait $! || return $?
# else
# echo "$special_list not found: skipping"
# fi
declare -a special=(
# Adams class
"Student01"
"Student02"
"Student03"
"Student04"
# Mariannes class:
"Student05"
"Student06"
"Student07"
"Student08"
)
# Root and Admin should be wide open
if [[ " ${admins[@]} " =~ " $user " ]] ; then
echo Admin
# networksetup -setdnsservers Wi-Fi 8.8.8.8
# networksetup -setdnsservers Ethernet 8.8.8.8
elif [[ " ${special[@]} " =~ " $user " ]] ; then
# Older students get an open, but filtered experience:
# Adams class
echo Special
# networksetup -setdnsservers Wi-Fi 8.8.4.4
# networksetup -setdnsservers Ethernet 8.8.4.4
else
echo "Everyone else"
# Everyone else gets whitelisted DNS
# networksetup -setdnsservers Wi-Fi 208.67.222.222
# networksetup -setdnsservers Ethernet 208.67.222.222
fi
exit 0
注意:我从您的脚本中注释了nerworksetup并添加了回显 对于每种测试条件。您可以删除回声线并取消注释 网络设置行。
我将其测试为:
$ script a1 a2 root
Admin
$ script a1 a2 Student02
Special
$ script a1 a2 Student1000
Everyone else
我希望这会有所帮助。