macOS 循环的 Bash 脚本 if then else

问题描述

尝试使用下面的脚本进行循环。如果我通过从应用程序中删除 Google Chrome 来破坏它,它会起作用。如果我将 Chrome 放回原位,它会不断杀死 Dock 并说没有找到属于您的匹配进程。我是否必须向 killall Dock 添加一些内容才能退出脚本,还是在错误的位置完成?尝试了很多事情没有任何运气。最终希望它每 15 分钟尝试一次,直到所有应用程序都在应用程序中并杀死停靠栏,以便显示快捷方式而不是问号。一旦安装了所有应用程序并重新启动 Dock,就会发生这种情况。

i=0
while [ $i -lt 4 ]
do
if [[ -d "/Applications/Company Portal.app" && -d "/Applications/Google Chrome.app" ]];
        then
                killall Dock         
        else
i=$((i + 1)) | echo "Will tray again...."
sleep 10
fi
done

更新 这是我最终想到的,是的,很乱!但是有效!不过,看到这里的回复后,还得再多看看。

echo $(date)

# Check to see if script has already run on computer before,if so,then exit.
file=/Users/Shared/.If_Installed_Restart_Dock_Has_Run.txt
if [ -e "$file" ]; then
    echo "The If_Installed_Restart_Dock.sh script has run before and exiting..." && exit 0
else
touch /Users/Shared/.If_Installed_Restart_Dock_Has_Run.txt
fi

i=0
while [ $i -lt 6 ]
do

if [[ -d "/Applications/Google Chrome.app" && -d "/Applications/Microsoft Edge.app" ]];
        then
                killall Dock && exit 0
        else
                echo "Applications still need installed in order to restart Dock,will check again in 10 minutes for up to an hour,intune will try again in 8hrs..."
fi

i=$((i + 1))
sleep 600
done

解决方法

Chrome 无关紧要。你正在成为经典错误的受害者。考虑:

#!/bin/bash

i=0
while [ $i -lt 4 ]; do
        if echo "in first if,i = $i"; false ; then
                echo bar
        else
                echo "in else,i = $i"
                i=$((i + 1)) | echo "Will tray again...."  # (1)
                echo "after echo i = $i"
                i=$((i + 1))
                echo "after 2nd echo i = $i"
        fi
done

在上面的代码中,i=$((i + 1)) 行中的 (1) 不会增加控制循环中使用的变量。由于该命令在管道中,因此它在子 shell 中执行,并且主 shell 中的变量 i 不会递增。将代码结构化可能会更好:

#!/bin/sh

i=0
while [ $((i++)) -lt 4 ]; do
        if [ -d "/Applications/Company Portal.app" ] && [ -d "/Applications/Google Chrome.app" ]; then
                killall Dock
        else
                echo "Will tray again...."
                sleep 10
        fi
done

#!/bin/bash

for (( i = 0; i < 4; i++ )); do
        if [ -d "/Applications/Company Portal.app" ] && [ -d "/Applications/Google Chrome.app" ]; then
                killall Dock
        else
                echo "Will tray again...."
                sleep 10
        fi
done