我正在尝试创建一个脚本来使用脚本设置一组计算机的计算机名称和静态 IP 地址,但在运行时出现文件结束错误。这是脚本的一个小示例:
#!/bin/sh
serial=`/usr/sbin/system_profiler SPHardwareDataType | /usr/bin/awk '/Serial\ Number\ \(system\)/ {print $NF}'`
if test "$serial" == "C07M802Z4E825DY3J"
then
scutil --set ComputerName "qa-mac-1"
scutil --set LocalHostName "qa-mac-1"
networksetup -setproxyautodiscovery "Ethernet" on
networksetup -setmanual Ethernet 10.1.1.1 255.255.255.128 10.1.1.129
networksetup -setdnsservers Ethernet 10.2.76.98 10.2.76.97
networksetup -setsearchdomains Ethernet mycompany.com mycompanycorp.com us.mycompany.com
else
if test "$serial" == "C07M803JDLSY3J"
then
scutil --set ComputerName "qa-mac-2"
scutil --set LocalHostName "qa-mac-2"
networksetup -setproxyautodiscovery "Ethernet" on
networksetup -setmanual Ethernet 10.1.1.2 255.255.255.128 10.1.1.129
networksetup -setdnsservers Ethernet 10.2.76.98 10.2.76.97
networksetup -setsearchdomains Ethernet mycompany.com mycompanycorp.com us.mycompany.com
if test "$serial" == "C0737951JDLSY3J"
then
scutil --set ComputerName "qa-mac-3"
scutil --set LocalHostName "qa-mac-3"
networksetup -setproxyautodiscovery "Ethernet" on
networksetup -setmanual Ethernet 10.1.1.2 255.255.255.128 10.1.1.129
networksetup -setdnsservers Ethernet 10.2.76.98 10.2.76.97
networksetup -setsearchdomains Ethernet mycompany.com mycompanycorp.com us.mycompany.com
fi
exit 0
答案1
正如所写的那样,您的脚本有大量的代码重复,当情况发生变化时,这将使其难以使用。除了if
/ else
vs if
/之外elif
,我建议您有条件地编写代码来处理以下部分:各不相同并一次完成其他所有事情。
根据我对脚本的快速扫描,不同序列号之间唯一不同的是主机名和 IP 地址。鉴于此,您的脚本可以是:
#!/bin/sh
# I tried to minimize the changes to your original to avoid distracting from the
# point I was trying to make, but alas...
# This is functionally equivalent to what you had originally.
serial="$(/usr/sbin/system_profiler SPHardwareDataType | /usr/bin/awk '/Serial Number \(system\)/ {print $NF}')"
name=""
address=""
if [ "${serial}" = "C07M802Z4E825DY3J" ]; then
name="qa-mac-1"
address="10.1.1.1"
elif [ "${serial}" = "C07M803JDLSY3J" ]; then
name="qa-mac-2"
address="10.1.1.2"
elif [ "${serial}" = "C0737951JDLSY3J" ]; then
name="qa-mac-3"
address="10.1.1.3" # You had 10.1.1.2 here, I'm guessing it should have been .3
else
echo "Serial ${serial} is unsupported"
exit 1
fi
scutil --set ComputerName "${name}"
scutil --set LocalHostName "${name}"
networksetup -setproxyautodiscovery "Ethernet" on
networksetup -setmanual Ethernet "${address}" 255.255.255.128 10.1.1.129
networksetup -setdnsservers Ethernet 10.2.76.98 10.2.76.97
networksetup -setsearchdomains Ethernet mycompany.com mycompanycorp.com us.mycompany.com
答案2
对于 if/then/elif... 部分,也许您可以尝试使用 CASE 代替
它也适用于 bash。
#!/bin/sh
...
case $serial in
"C07M802Z4E825DY3J")
name="qa-mac-1"
address="10.1.1.1"
;;
"C07M803JDLSY3J")
name="qa-mac-2"
address="10.1.1.2"
;;
"C0737951JDLSY3J")
name="qa-mac-3"
address="10.1.1.3"
;;
\?) # incorrect option
echo "Error: Invalid option"
exit;;
esac