How do I convert this Applescript to Terminal osascript?
I'm trying to convert this AppleScript into osascript format that can be run from terminal:
tell application "System Preferences" to activate
tell application "System Preferences"
reveal anchor "input" of pane id "com.apple.preference.sound"
end tell
tell application "System Events" to tell process "System Preferences"
repeat until exists tab group 1 of window "Sound"
end repeat
tell table 1 of scroll area 1 of tab group 1 of window 1
select (row 1 where value of text field 1 is "Internal Microphone")
end tell
end tell
quit application "System Preferences"
What is the appropriate syntax to do this? Do I have to type osascript -e
before every line?
There are several ways to accomplish the goal. Here is the method I would use...
In Terminal run the following compound command, e.g.:
f="myscript"; touch "$f"; open -e "$f"; chmod +x "$f"
- Note: Change
myscript
to the name you'd like.
In the new blank TextEdit document that opens, add the following as the first line:
#!/usr/bin/osascript
Then add your AppleScript code under the shebang you just added.
Save the document.
Now to use it in Terminal, e.g.:
./myscript
Or:
/path/to/myscript
Or place in in a directory that is within the defined PATH
and then simply use its name, e.g.:
myscript
This method also works; however it's not practical for long scripts:
osascript -e 'tell application "System Preferences" to activate' -e 'tell application "System Preferences"' -e 'reveal anchor "input" of pane id "com.apple.preference.sound"' -e 'end tell' -e 'tell application "System Events" to tell process "System Preferences"' -e 'repeat until exists tab group 1 of window "Sound"' -e 'end repeat' -e 'tell table 1 of scroll area 1 of tab group 1 of window 1' -e 'select (row 1 where value of text field 1 is "Internal Microphone")' -e 'end tell' -e 'end tell' -e 'quit application "System Preferences"'
Please read the manual page for osascript
for additional information. In Terminal:
man osascript
On a separate note, if you omit the following line of code you'll not have to see the System Preferences window flash on the screen:
Saved as as script, remove:
tell application "System Preferences" to activate
In the very long drawn out command line, remove:
-e 'tell application "System Preferences" to activate'