複数のif elseを含むif文

複数のif elseを含むif文

スクリプトを使用してコンピュータグループのコンピュータ名と固定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/ elsevs 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

おすすめ記事