Bash to Applescript to Bash

So I recently had a need to wrap a script up with a nice GUI, however the script needed to execute a command with admin privs ie. sudo

I normally just use Platypus to wrap a bash script, maybe incorporate cocoaDialog or Pashua as well.

Anyway I thought that by clicking the Run with Administrator Privileges in Platypus, this would allow the script to execute as root or via sudo.

Screen Shot 2015-02-26 at 11.29.21 am

However this is not the case. See GitHub issue for Platypus here: “Require Administrative Privileges” not delegating authentication

I needed a way to prompt the user for their username and password and then execute the specific command. What I came up with is to invoke osascript in the bash script and have it to run the command ‘with administrator privileges’

This was also somewhat more difficult in that I needed to pass the command I was now having osascript run a variable that is defined in the original bash script.

I tried all sorts of combinations of escaping quotes and what not but in the end this is what I came up with that seems to do the job.

What I found interesting was that I had to export the variable before osascript would be able to pick it up.

Note that I’ve added some line breaks here to make it easier to read.

variable_name="Hello World! This is a string"
export variable_name
osascript -e \
    'do shell script "defaults write /Library/Preferences/ Text1 -string \"$variable_name\"" \
    with administrator privileges'

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s