hiimreverie
hiimreverie

Reputation: 43

Running a bash script from within Applescript

I'm having an issue getting a bash script to execute from within Applescript. What I need is for the Applescript file to prompt for the username and password so that the bash script runs with sudo permissions, as it is doing tasks that cannot be done as an Administrator, such as writing to /etc/.

As this script (packaged inside a .dmg file using Platypus) will be distributed to a number of users, I can't rely on absolute paths, and instead need to get the path of the Applescript file when it runs, get sudo permissions, and run the bash script from within the same directory.

So far, everything I have been able to come up with, via SO posts and other sites, has resulted in osascript complaining that it can't find the bash script. Any ideas?

It seems that this might work, but it syntax errors:

set wd to do shell script "pwd"

tell application "Terminal"
    set run_cmd to "/bin/bash " & wd & "/osx.sh"
    do script run_cmd with administrator privileges
end tell

Upvotes: 3

Views: 1913

Answers (1)

pbell
pbell

Reputation: 3095

If your script is saved as application, it must include :

Set myPath to path to me

The variable myPath will be the complete path to your app. From there, you just have to add you sub folder, like "Contents:Resources:my_shell_script" to know where your shell script is. Don't forget to convert your path to posix (Unix) path for the do shell script command.

To ask user password, you can use display dialog with hidden option to not display typed characters :

set myInput to display dialog "Enter your password" default answer "" with hidden answer
set myPwd to text returned of myInput

To get user name, there are many possible methods; this is just one :

set UserName to do shell script "/usr/bin/whoami"

However, if this user has not admin privilèges, you will still have to ask for admin user name.

Last, but not least, your shell script can be run using do shell script (as Vadian says)

Set R to do shell script "my_script-here"

Upvotes: 1

Related Questions