我试图创建一个脚本来设置计算机名和使用脚本的一组计算机的静态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发布于 2020-07-06 22:45:38
您的脚本,正如所写的,有大量的代码重复,这将使它难以工作时,事情发生了变化。除了if/else和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发布于 2020-07-07 01:35:28
如果.那么.部分,也许你可以用凯斯代替
它也适用于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;;
esachttps://unix.stackexchange.com/questions/597073
复制相似问题