简体   繁体   English

如何在调用 shell 中检测 osascript 报告的按钮按下?

[英]How can I detect a button press reported by osascript in a calling shell?

I'm currently working on a script to notify a user when their password will expire.我目前正在编写一个脚本,用于在用户密码到期时通知用户。 The prompt appears, but no matter what button I press, it results to the same outcome, "Change Later was chosen".出现提示,但无论我按下哪个按钮,都会导致相同的结果,“选择了稍后更改”。 Any ideas?有任何想法吗?

#!/bin/bash
button=$(osascript -e 'tell application "System Events" to display dialog "Change password now or later?" buttons {"Change Later", "Change Now"} default button 1 with title "Password Update Required" with icon caution')

if [[ $button = "Change Now" ]]; then
    open /System/Library/PreferencePanes/Accounts.prefPane
    echo "Opening Preferences"
else
    echo "Change Later was chosen"
    exit 0
fi

osascript doesn't simply output the name of the button you press; osascript不只是输出您按下的按钮的名称; it outputs a more "descriptive" string, prefixed with button returned: .它输出一个更具“描述性”的字符串,以button returned:为前缀button returned: You need to account for that in your check:您需要在支票中说明这一点:

if [[ $button = "button returned:Change Now" ]]

Also worth considering is that you are free to perform the check that determines which button was pressed in the AppleScript portion of the code as well, which in some ways makes more sense, as you can open System Preferences with it too:另外值得考虑的是,您也可以自由执行检查,以确定在代码的 AppleScript 部分中按下了哪个按钮,这在某些方面更有意义,因为您也可以使用它打开系统偏好设置

#!/usr/bin/env bash
osascript << OSA 2>/dev/null && exit 0 || echo "Change Later was chosen"
display dialog "Change password now or later?" buttons ¬
        {"Change Later", "Change Now"} default button 1 ¬
        with title "Password Update Required" with icon caution

if the button returned of the result ¬
        is "Change Later" then error

tell application id "com.apple.SystemPreferences"
        reveal pane id "com.apple.preferences.users"
        repeat until the id of the current pane is ¬
                "com.apple.preferences.users"
                delay 0.5
        end repeat
        activate
end tell
OSA

Here, rather than saving the outcome of the script to a variable, the exit status of osascript reflects the user's choice: "Change Later" terminates osascript with an error, thus returning an exit status of 1 ;在这里, osascript的退出状态不是将脚本的结果保存到变量中, osascript反映了用户的选择:“稍后更改”会osascript错误而终止osascript ,从而返回退出状态1 "Change Now" allows the script to progress onward and opens System Preferences to the Users & Groups pane, before returning an exit status of 0 . “立即更改”允许脚本继续前进并在返回退出状态0之前将系统偏好设置打开到Users & Groups窗格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM