0 bash
我正在尝试创建一个脚本来使用脚本设置一堆计算机的计算机名称和静态 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
Run Code Online (Sandbox Code Playgroud)
您编写的脚本有大量代码重复,当事情发生变化时,这将使其难以使用。除了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
Run Code Online (Sandbox Code Playgroud)