Run UNIX commands in an AppleScript

10:44 am Mac Tips

Leopard Logo If you want to easily encapsulate a shell script or a UNIX command in an AppleScript, but that command must be executed as root (through a sudo), just do the following (all one line):

do shell script "unix_command" password "your_password" with administrator privileges

where unix_command is the actual command you want to execute. In my case, this was to set the Sharing hostname to match the actual DNS hostname of the computer, which looked like this:

do shell script "sudo scutil --set ComputerName `hostname`" password "NoWayJose" with administrator privileges

By the way, if you do intend to set the Sharing name to the computer’s hostname, make sure to include the backticks (located under the ~ sign at the top left of most keyboards) around the word hostname, otherwise you’ll just name your computer ‘hostname’ rather than its DNS name.

It’s important to note that this a) leaves your password in the script, and b) runs silently. If you just want to be prompted for a password, add the following lines before and after your script, like this:

tell application "Terminal"
do script "sudo scutil --set ComputerName `hostname`"
end tell

This will launch Terminal, which will then prompt you for your password in order to sudo.

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.