shell 脚本中的多个条件

shell 脚本中的多个条件

我在脚本中给出两个条件时遇到困难。我能读出两件事 -

  1. 最近的服务器是哪个
  2. 如果是 MacBook 或其他产品

然后使用defaults write命令修改plist文件。

我如何添加一行来交叉检查模型和服务器,然后相应地写入文件?

#!/bin/sh
# Get the logfile for this machine
dslog="/tmp/DSNetworkRepository/Logs/$(ioreg -l | grep IOPlatformSerialNumber | awk '{print $4}' | cut -d \" -f 2).log"

NEARESTSERVER=$(awk 'gsub(/.*server=|port=.*/,"")' $dslog | tail -1)


# get machine model
MACHINE_MODEL=`/usr/sbin/ioreg -c IOPlatformExpertDevice | grep "model" | awk -F\" '{ print $4 }'`

MacBook=`/usr/sbin/ioreg -c IOPlatformExpertDevice | grep "model" | cut -c21-27`


# Check if the Model is MacBook or Desktop & connected to which Booster and write the plist file accordingly

if [[ "${MACHINE_MODEL}" == "MacBook" && $NEARESTSERVER == 'SRV-DELHI.xaas.com']]
then
  defaults write /Library/com.myorg.repo ConnectionNumber -string One

elif [[ "${MACHINE_MODEL}" != "MacBook" && $NEARESTSERVER == 'SRV-DELHI.xaas.com']]
then
  defaults write /Library/com.myorg.repo ConnectionNumber -string Two

fi

# Check if the Model is MacBook or Desktop & connected to which Booster and write the plist file accordingly
if [[ "${MACHINE_MODEL}" == "MacBook" && $NEARESTSERVER == 'SRV-MUMBAI.xaas.com']] 
then
  defaults write /Library/com.myorg.repo ConnectionNumber -string Three

elif [[ "${MACHINE_MODEL}" != "MacBook" && $NEARESTSERVER == 'SRV-MUMBAI.xaas.com']] 
then
  defaults write /Library/com.myorg.repo ConnectionNumber -string Four

fi

exit 0

答案1

如果我理解正确的话,您想了解如何使其在Shell语言上更简短、更有条理。

我会做这样的事情:

set -A strings \
    One \
    Two \
    Three \
    Four
# You should swap Three and Four so it's easy to fit the logic.
counter=0
for i in \
    "[ \"$NEARESTSERVER\" == 'SRV-MUMBAI.xaas.com' ]" \
    "[ \"$MACHINE_MODEL\" = 'MacBook' ]" ; do
    eval "$i && counter=\"$(($counter + (! $? + 1)))\""
done
defaults write /Library/com.myorg.repo ConnectionNumber -string ${strings[$counter]}

您应该对此进行测试和调整,因为我可能遗漏了一些东西。我不知道还有其他方法可以使其变得更好(除了使用命名空间而不是列表)。

相关内容