Open File Dialog from the Shell (Mac)

Written 07:09 am 11/15/2012 Modifed 12:15 pm 11/21/2012

I'm not going to say that I'm an evil genius, or that I'm even a genius, but it was remarkably difficult to find any resources on prompting an open file dialog from the mac shell. We can use Applescript to give us some GUI elements within a bash script. For linux users, see the "dialog" command.

I wanted to make my minecraft modloader easier for users who don't really understand the shell. I have seen scripts curl scripts, then piping them through bash, so I decided on doing that.

The problem is that users needed to be able to specify a file location. Using the curl to bash method, I had to prompt the user for a mod's location. I could do that via the shell, or I could try to figure out a way to prompt users with an open file dialog. Out of curiosity, I spent some time researching a way to prompt a dialog from the shell.

After finding nothing with any built in commands, I turned to Applescript. Margaret Magnus has a handy guide on how to do some tricky things with AppleScript, one of which was opening a file dialog. If we modify the Margaret's applescript to talk to "Terminal" instead of "Filemaker", we can accomplish what we want without leaving the shell.

file=`osascript -e 'tell app (path to frontmost application as Unicode text) to set new_file to POSIX path of (choose file with prompt "Select A File" of type {"ZIP", "JAR"})'  2> /dev/null`

The above script will get a filename from applescript, then format it so that we can use it. To allow a user to provide a filename as an argument, otherwise prompt with a dialog, we can wrap it all together with the following code (in bash)

if [ 1 -eq "$#" ]; then 
    zip=$arg1;
else
    clear;
    echo -e "\033[5;36mPlease Select a Zip File\033[0m";
    sleep 1
    osascript -e 'tell app "Terminal" to activate' 2> /dev/null 
    zip=`osascript -e 'tell app (path to frontmost application as Unicode text) to set new_file to POSIX path of (choose file with prompt "Select A Zip" of type {"ZIP"})'  2> /dev/null`
    clear
fi
Posted by in his speech as Father-of-the-Bride, the same day you got mairred (I am paraphrasing) "People will tell you marriage takes work I don't necessarily agree with that, but I do think it requires attention, that is, both of you need to pay attention to e on February 21st, 2016, 8:09 am Reply

in his speech as Father-of-the-Bride, the same day you got mairred (I am paraphrasing) "People will tell you marriage takes work I don't necessarily agree with that, but I do think it requires attention, that is, both of you need to pay attention to each other and your marriage it's not easy, but it's not work." A fine distinction I thought and one it's taken us many years to realize all the best. Sharon I.