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

cel*_*oad 6 macos bash shell applescript

我在macOS上.我有一个脚本,在使用read终端请求确认后,用于grep检查是否已挂载/ dev/disk1,然后格式化该磁盘.这是一个危险的脚本,因此,为什么先询问它是否合适是至关重要的.

最后,我想让这个脚本成为用户可以双击的可执行文件.但是,不是让用户键入"y"并返回到终端窗口,我宁愿显示"是"和"否"按钮的显示对话框,让他们选择,然后根据他们的答案运行脚本.在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
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助.

Jer*_*ton 10

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

#!/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
Run Code Online (Sandbox Code Playgroud)

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

它还显示了如何设置默认按钮,我假设示例为"否".

如果您有一个更复杂的对话框,您很可能会使用正则表达式来检测响应,就像您在自己的示例中一样; 虽然根据您的使用情况,您可能希望防止欺骗响应.