使 bash 脚本显示系统事件对话框,然后获取其结果并在 if 语句中使用它

make bash script display system event dialog, then take its result and use it in an if statement

我在 macOS。我有一个脚本,在终端中使用 read 请求确认后,使用 grep 检查是否安装了 /dev/disk1,然后格式化该磁盘。这是一个危险的脚本,因此为什么首先询问它是否可以是至关重要的。

最后,我想让这个脚本成为用户可以双击的可执行文件。但是,与其让用户在终端 window 中键入 "y" 和 Return,我宁愿出现一个带有 "yes" 和 "no" 按钮的显示对话框,让它们选择,然后根据他们的答案编写脚本 运行。这在 bash 中可行吗?

我在一个没有管理权限的环境中工作,所以虽然我可以编写一个 AppleScript 服务来完成我想做的事情并将其优雅地集成到用户界面中,但我可以'不要将该服务集成到没有管理员密码的环境中(因为没有它我无法为用户编辑 ~/Library/Services )。此外,我无法在环境中下载或安装任何新的库、应用程序——实际上是任何东西;我只能在 Mac OS X.

中使用原生 bash

这是我的资料:

read -p "Are you sure you want to partition this disk? " -n 1 -r # Can I make this be a dialog box instead?
echo 

if [[ $REPLY =~ ^[Yy]$ ]] # Can this accept the result as a condition?
then
    if grep -q 'disk1' /dev/ && grep -q 'file.bin' ~/Downloads; then
        echo # redacted actual code
    else
        osascript -e 'tell app "System Events" to display dialog "The disk is not mounted."'
        exit 1
    fi
else
    exit 1
fi

非常感谢您的帮助。

如果您对文本模式(但跨平台且经过验证)解决方案感到满意,请尝试使用 ncurses,尤其是名为 dialog.

的实用程序
dialog --yesno "Are you sure you want to partition this disk?" 5 50
answer=$?       # Returns: 0 == yes, 1 == no

this tutorial 中有更多详细信息。

是的,在 bash 中可以获取 osascript 对话框的输出。这是一个带有 Yes/No 对话框的示例:

#!/bin/bash

SURETY="$(osascript -e 'display dialog "Are you sure you want to partition this disk?" buttons {"Yes", "No"} default button "No"')"

if [ "$SURETY" = "button returned:Yes" ]; then
    echo "Yes, continue with partition."
else
    echo "No, cancel partition."
fi

如果您 运行 此脚本,脚本应根据按下的按钮回显相应的行。

它还展示了如何设置默认按钮,我假设该示例为“否”。

如果您有一个更复杂的对话,您很可能会使用正则表达式来检测响应,就像您在自己的示例中所做的那样;尽管根据您的用例,您可能希望防止欺骗响应。