I'm on macOS. I have a script that, after asking for confirmation using read
in Terminal, uses grep
to check whether /dev/disk1 is mounted, then formats that disk. That's a dangerous script, hence why asking if it's okay first is vital.
Eventually, I would like to have this script be an executable that the user can double-click on. But rather than having the user type "y" and Return into a Terminal window, I would rather a display dialog appear with "yes" and "no" buttons, have them choose, then have the script run based on their answer. Is this possible in bash?
I'm working in an environment in which I don't have administrative access, so while I can write an AppleScript Service to accomplish what I want to do and to integrate this elegantly into the user interface, I can't integrate that Service into the environment without the admin password (since I can't edit ~/Library/Services for the user without it). Also, I cannot download or install any new libraries, applications — anything, really — in the environment; I must only use native bash in Mac OS X.
Here is what I have:
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
Thanks very much for your help.
Yes, it is possible in bash to take the output of an osascript dialog. Here’s an example with a Yes/No dialog box:
#!/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
If you run this script, the script should echo the appropriate line depending on which button was pressed.
It also shows how to set the default button, which I am assuming for the example is “No”.
If you have a more complex dialog, you would most likely use a regex to detect the responses, as you do in your own sample; though depending on your use case you might want to guard against spoofing responses.
If you're happy with a text-mode (but cross-platform and proven) solution, try using ncurses, and in particular a utility called dialog
.
dialog --yesno "Are you sure you want to partition this disk?" 5 50
answer=$? # Returns: 0 == yes, 1 == no
More details in this tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With