how to interpret bash variables in applescript command - bash

I am trying to write a bash script that reloads a given chrome tab, and I am passing the variable POSITION_STRING to applescript to dynamically determine the definition of the statement (as I thought thats what heredocs notations are used to do).
But it seems applescript rejects this type of connotation, help?
declare -A POSSIBLE_POSITIONS
POSSIBLE_POSITIONS=(
["1"]="first"
["2"]="second"
["3"]="third"
["4"]="fourth"
["5"]="fifth"
["6"]="sixth"
["7"]="seventh"
["8"]="eighth"
["9"]="ninth"
["10"]="tenth"
)
# echo "${POSSIBLE_POSITIONS[$1]}"
POSITION=$1
POSITION_STRING=${POSSIBLE_POSITIONS[$POSITION]}
# echo $POSITION_STRING
/usr/bin/osascript <<EOF
log "$POSITION_STRING" # this works!
tell application "Google Chrome"
tell the "$POSITION_STRING" tab of its first window
# reload
end tell
end tell
EOF

AppleScript's object specifiers accept integer-based indexes just fine. There's absolutely no need to use first, second, etc keywords, and you're digging yourself a hole trying to munge them into AppleScript code.
When using osascript, the correct way to pass arguments into your AppleScript is to put them after the file name (if any). osascript will then pass these arguments to your AppleScript's run handler as a list of text values, which you can then extract, check, coerce, etc. as appropriate.
Example:
POSITION=1
/usr/bin/osascript - "$POSITION" <<'EOF'
on run argv -- argv is a list of text
-- process the arguments
set n to item 1 of argv as integer
-- do your stuff
tell application "Google Chrome"
tell tab n of window 1
reload
end tell
end tell
end run
EOF

Quoting rules are different in here docs than in the body of a bash script. This line in your here doc:
tell the "$POSITION_STRING" tab of its first window
…expands to (for example) this:
tell the "first" tab of its first window
…which is not syntactically valid. Remove the quotes around $POSITION_STRING on that line and it should work. However:
As #foo says, AppleScript understands numeric indexes just fine; there is no need to use English word indexes. Use tab $POSITION instead and it will work with any number, not just one through ten, and your script will be shorter besides.
Again echoing #foo, trying to substitute variables into a script text is usually a losing game. (For integers you can get away with it, but it becomes problematic for strings because quoting.) Make your script take arguments of its own and then pass them to osascript(1) — the man page shows how to do this. Note that arguments will always come in as strings, so you will need to coerce them if you need a number:
/usr/bin/osascript - "$POSITION" <<'EOF'
on run argv -- argv is a list of text
set n to item 1 of argv as integer
tell application "Google Chrome"
tell tab n of window 1 …
If your bash script is just turning around and calling osascript(1), you can go one step further: osascript functions perfectly well as an Unix interpreter, so you could rewrite your script like this:
#!/usr/bin/osascript
on run argv
set n to item 1 of argv as integer
tell application "Google Chrome"
tell tab n of window 1 …
Save that in a file by itself, mark it executable, and Bob's your uncle. (Unless you needed a bash function, in which case a here doc is a reasonable choice.)

osascript -e can accept newlines and variables. There may be reasons to use HEREDOCs, but I'm not aware of them and I find this a bit easier to work with.
Example:
TEST='Hello, World!'
osascript -e '
on run argv
display dialog item 1 of argv
end run
' $TEST

Related

Applescript Occasionally Freezes Automator

I'm trying to use this applescript to modify a file path written to a text file, copy the modified path to the clipboard, set it as variable thePath, use it to pull a Google Drive link from a list, and then copy that link to the clipboard.
Running it within Automator, it sometimes works perfectly but other times it stalls while running this applescript and crashes textedit, and then eventually times out without any specific error messages. Are there any issues with my code that would be causing Automator to freeze?
Note that I've substituted the actual links with link1, link2, etc. for privacy reasons.
on run {input, parameters}
tell application "TextEdit" to activate
tell application "System Events"
key code 125
key code 123 using shift down
key code 123 using shift down
key code 123 using shift down
key code 123 using shift down
key code 123 using shift down
key code 123 using shift down
key code 123 using shift down
key code 123 using shift down
keystroke "x" using command down
keystroke "a" using command down
key code 51
keystroke "v" using command down
keystroke "s" using command down
keystroke "w" using command down
delay 2
end tell
set thePath to the clipboard
set myList to {"link1","link2","link3","link4","link5","link6","link7","link8","link9","link10","link11","link12","link13","link14","link15","link16","link17","link18","link19","link20","link21","link22","link23","link24","link25","link26","link27","link28","link29","link30","link31","link32","link33","link34","link35","link36","link37","link38","link39","link40","link41","link42","link43","link44","link45","link46","link47","link48","link49","link50","link51","link52","link53","link54","link55","link56","link57","link58","link59","link60","link61","link62","link63","link64","link65","link66","link67","link68","link69","link70","link71","link72","link73","link74","link75","link76","link77","link78","link79","link80","link81","link82","link83","link84","link85","link86","link87","link88","link89","link90","link91","link92","link93","link94","link95","link96","link97","link98","link99","link100","link101","link102","link103","link104","link105","link106","link107","link108","link109","link110","link111","link112","link113","link114","link115","link116","link117","link118","link119","link120","link121","link122","link123","link124","link125","link126","link127","link128","link129","link130","link131","link132","link133","link134","link135","link136","link137","link138","link139","link140","link141","link142","link143","link144","link145","link146","link147","link148","link149","link150","link151","link152","link153","link154","link155","link156","link157","link158","link159","link160","link161","link162","link163","link164","link165","link166","link167","link168","link169","link170","link171","link172","link173","link174","link175","link176","link177","link178","link179","link180","link181","link182","link183","link184","link185","link186","link187","link188","link189","link190","link191","link192","link193","link194","link195","link196","link197","link198","link199","link200","link201","link202","link203","link204","link205","link206","link207","link208","link209","link210","link211","link212","link213","link214","link215","link216","link217","link218","link219","link220","link221","link222","link223","link224","link225","link226","link227","link228","link229","link230","link231","link232","link233","link234","link235","link236","link237","link238","link239","link240","link241","link242","link243","link244","link245","link246","link247","link248","link249","link250","link251","link252","link253","link254","link255","link256","link257","link258","link259","link260","link261","link262","link263","link264","link265","link266","link267","link268","link269","link270","link271","link272","link273","link274","link275","link276","link277","link278","link279","link280","link281","link282","link283","link284","link285","link286","link287","link288","link289","link290","link291","link292","link293","link294","link295","link296","link297","link298"}
set the clipboard to item thePath of myList
return input
end run
You could do this with AppleScript, but it would be much more sensible to do this with a shell script, by way of the Run Shell Script action in Automator, selecting the option to pass the input "as arguments". The default shell in macOS is zsh, so stick with that.
The script is short and sweet:
( PATH=/usr/bin:$PATH
basename "$1" | bc
) 2>/dev/null
basename extracts last path component, which, in this case, is the name of the folder, even if the path ends with a trailing slash. The result of this command is then piped through to bc, which performs basic calculations: this is purely to parse the folder name as a number, so that "00007" simply returns "7".
How to make use of this value is entirely dependent on how and where you store the various links from which it selects. Here's one suggestion, which is reasonably simple:
This allows you to hard-code your 300 or so links into a single Automator variable, which a second shell script reads and returns the specific link associated (by line number) with the value obtained from the previous shell script. The link then placed onto the clipboard.

Send multiple lines of quoted text to IPython in Terminal Window

I want to send a selected group of lines to my current ipython window from a texteditor (It's TextMate in this case, but that's largely irrelevant.) The script uses a bash call so it can accept the variable and then an Applescript call to push the code to the window.
This current script works, but it can only send a single non-nested line at a time. Is there a way to fix this so I can send multiple non-nested lines of code at once?
#!/bin/bash
QUOTED_TEXT=${TM_SELECTED_TEXT//\"/\\\"}
echo "$QUOTED_TEXT"
osascript <<- APPLESCRIPT
tell application "Terminal"
set currentTab to (selected tab of (get first window))
set tabProcs to processes of currentTab
set theProc to (end of tabProcs)
if theProc is not "Python" then
set currentTab to (do script "ipython")
end if
do script "$QUOTED_TEXT \n" in currentTab
end tell
APPLESCRIPT
I don't use either TM or ipython myself so can't provide an immediate answer to your exact problem, but here's some general thoughts on calling AppleScript from Terminal:
Never pass arguments to AS like that: it's a mis-quoting accident just waiting to happen. Wrap your AS code in an on run argv ... end run handler, then append your extra arguments to the osascript command when calling it in bash. osascript will then pass those arguments directly to AppleScript as a list of strings assigned to the argv variable. Safe and simple.
Rather than wrap your AS code in a bash script, just add #!/usr/bin/osascript at the top of your AS code, save it as a plain text file in an appropriate location (e.g. somewhere on your shell's $PATH, such as /usr/local/bin), then do chmod +x /path/to/script to make it executable. This will allow you to run it directly from Terminal.
If you want to access STDIN or environment variables directly within an AppleScript-based shell script, use the AppleScript-ObjC bridge to call NSFileHandle's fileHandleWithStandardInput()'s readDataToEndOfFile() and NSProcessInfo's processInfo()'s environment() respectively. To access ARGV, use an explicit run handler as described above.
By default, osascript automatically writes the value returned by the run handler to STDOUT; alternatively, you can write directly to STDOUT at any time via NSFileHandler (you can put a plain return statement at the end of run handler to ensure it returns nothing else). And osascript automatically writes the results of log commands to STDERR, and sets the return code to non-zero when your script throws an uncaught exception (e.g. use an error ERROR_STRING number ERROR_NUMBER statement to raise an exception directly in your AS code).
(BTW, I wrote a File library not long ago that includes a bunch of very nice handlers for writing AS-based shell scripts. I no longer develop or support it myself; however, various folks have already forked it, so if you do much AS+shell work you may find it a helpful source of AS code to cut-and-paste or even to use as-is.)

Invoke copy & paste commands from terminal

Is is possible to invoke a copy command (as if the user pressed Cmd+C) from a bash script? Basically I want to write a simple script that I run with a global hotkey and it should take the current selection from the active app, replace something and paste the result. Is this possible?
The best I could come up so far is using pbpaste and pbcopy, but I'd like to automate that if possible.
If you're just trying to modify a text selection, you could use AppleScript.
osascript -e 'try
set old to the clipboard
end try
try
delay 0.3
tell application "System Events" to keystroke "c" using command down
delay 0.2
set text item delimiters to linefeed
set input to (paragraphs of (the clipboard as text)) as text
set the clipboard to do shell script "shopt -u xpg_echo; echo -n " & quoted form of input & " | rev" without altering line endings
tell application "System Events" to keystroke "v" using command down
delay 0.05
end try
try
set the clipboard to old
end try'
The first delay is for releasing modifier keys if the script is run with a shortcut that has other modifier keys than command. The second delay could also be reduced to something like 0.05, but long selections or for example web views often need a longer delay. Without the third delay, the clipboard would sometimes be set to old before the text would get pasted.
the clipboard as text and do shell script convert line endings to carriage returns by default. shopt -u xpg_echo is needed because the echo in sh interprets backslashes inside single quotes by default. If the input is longer than getconf ARG_MAX bytes, you can't use echo and have to either write it to a temporary file or use pbpaste.
pbpaste and pbcopy replace non-ASCII characters with question marks by default in the environment used by do shell script You can prevent that by setting LC_CTYPE to UTF-8.
Telling System Events to click menu bar items would often be even slower, and it wouldn't work in applications that don't have a menu bar or in full screen windows.
Another option would be to create an Automator service. But they also have small delays before they are run. There's a bug where the shortcuts for services don't always work until the services menu has been shown once on the menu bar. And the services aren't available when the frontmost application doesn't have a menu bar or a services menu.

Converting to one line AppleScript

I have a series of AppleScript commands I need to implement into a single line of AppleScript. The code is below.
delay 2
tell application "System Events" to keystroke "foo"
tell application "System Events" to keystroke return
You can combine the two keystroke commands into a single one by concatenating your strings together:
tell app "System Events" to keystroke "foo" & return
But that still leaves you with one command and a statement (delay and tell … to …).
Effectively, AppleScript’s statement separator is a line break. In modern AppleScript the line breaks can be either CR, LF, or CRLF (respectively: old-Mac-, Unix-, or DOS-style). There is no convenient way write a multi-statement line (like foo; bar; baz; in C, Perl, Ruby, et cetera).
For your specific request, you can combine the two in a really ugly way by using delay as a part of an expression.
tell application "System Events" to keystroke "" & (delay 2) & "foo" & return
This is ugly because delay technically returns no value, but we are able to concatenate it with an empty string without causing an error.
The problem is that such a construction is not very “general purpose”. You may not always be able to turn any command into an expression in the same way (and you can not use statements like tell as a part of an expression1). For a bit more brevity (and obfuscation), you can write the last bit as "foo" & return & (delay 2). It still runs in the same order (delay first) because each part of the concatenation expression must be evaluated before it can be built into a single value for the keystroke command.
1 Short of putting them in a string given to run script that is. Even then, some statements (loops, try/catch, etc.) are always multi-line; though you can get around that by using escaped line breaks or concatenation and one of the line break constants (as follows).
You could use run script with a string argument and use the backslash2 escapes to represent the line breaks.
run script "delay 0.1\ntell app \"System Events\" to keystroke \"foo\" & return"
AppleScript Editor may translate the escape notation into a literal unless you have “Escape tabs and line break in string” enabled in its Editing preferences (available in 10.5 and later). You could always use the return constant and concatenation instead of the in-string-literal/escape-notation.
run script "delay 0.1" & return & "tell app \"System Events\" to keystroke \"foo\" & return"
2 If you are going to represent such strings inside an Objective C string literal (as one of your comments might imply), then you will have to escape the backslashes and double quotes for Objective C, also (…& \"tell app \\\"System…).
Or, if you are ultimately trying to run the code with osascript, then you can use the fact that each instance of -e will become a separate line to put it all on a single shell command line.
osascript -e 'delay 2' -e 'tell app "System Events" to keystroke "foo" & return'
osascript with several -e 'line1' -e 'line2' -e 'line3' ...
The manpage for osascript suggests to use several -e to build up a multi-line script.
-e statement
Enter one line of a script. If -e is given, osascript will not look for a filename in the argument list.
Multiple -e options may be given to build up a multi-line script.
Because most scripts use characters
that are special to many shell programs (for example, AppleScript uses single and double quote marks, “(”,
“)”, and “*”), the statement will have to be correctly quoted and escaped to get it past the shell intact.
Answer already given by Chris Johnsen, but is contained in a longer answer and therefore can be overlooked.

Programmatically launch Terminal.app with a specified command (and custom colors)

I can launch an xterm from the command line (or a program, via a system call) like so:
/usr/X11/bin/xterm -fg SkyBlue -bg black -e myscript
That will launch an xterm with blue text and a black background, and run an arbitrary script inside it.
My question: How do I do the equivalent with Terminal.app?
You can open an app by bundle id too, and give other parameters.
If there's an executable script test.sh in the current directory, the following command will open and run it in Terminal.app
open -b com.apple.terminal test.sh
The only down side that I can find is that Terminal doesn't appear to inherit your current environment, so you'll have to arrange another way to pass parameters through to the script that you want to run. I guess building the script on the fly to embed the parameters would be one approach (taking into account the security implications of course...)
Assuming you already have the colors you want in one of your Terminal profiles, here's what I came up with (with some help from Juha's answer and from this Serverfault answer).
Update:
On reflection, I think this echo business is too complicated. It turns out you can use osascript to make an executable AppleScript file with a shebang line:
#!/usr/bin/osascript
on run argv
if length of argv is equal to 0
set command to ""
else
set command to item 1 of argv
end if
if length of argv is greater than 1
set profile to item 2 of argv
runWithProfile(command, profile)
else
runSimple(command)
end if
end run
on runSimple(command)
tell application "Terminal"
activate
set newTab to do script(command)
end tell
return newTab
end runSimple
on runWithProfile(command, profile)
set newTab to runSimple(command)
tell application "Terminal" to set current settings of newTab to (first settings set whose name is profile)
end runWithProfile
Save that as term.scpt, make it executable with chmod +x, and use it the same way as below, e.g. term.scpt "emacs -nw" "Red Sands".
Original answer:
Assuming we save the script below as term.sh...
#!/bin/sh
echo '
on run argv
if length of argv is equal to 0
set command to ""
else
set command to item 1 of argv
end if
if length of argv is greater than 1
set profile to item 2 of argv
runWithProfile(command, profile)
else
runSimple(command)
end if
end run
on runSimple(command)
tell application "Terminal"
activate
set newTab to do script(command)
end tell
return newTab
end runSimple
on runWithProfile(command, profile)
set newTab to runSimple(command)
tell application "Terminal" to set current settings of newTab to (first settings set whose name is profile)
end runWithProfile
' | osascript - "$#" > /dev/null
...it can be invoked as follows:
term.sh
opens a new terminal window, nothing special
term.sh COMMAND
opens a new terminal window, executing the specified command. Commands with arguments can be enclosed in quotes, e.g. term.sh "emacs -nw" to open a new terminal and run (non-windowed) emacs
term.sh COMMAND PROFILE
opens a new terminal window, executing the specified command, and sets it to the specified profile. Profiles with spaces in their names can be enclosed in quotes, e.g. term.sh "emacs -nw" "Red Sands" to open a new terminal and run (non-windowed) emacs with the Red Sands profile.
If you invoke it with a bad command name, it'll still open the window and set the profile, but you'll get bash's error message in the new window.
If you invoke it with a bad profile name, the window will still open and the command will still execute but the window will stick with the default profile and you'll get an error message (to stderr wherever you launched it) along the lines of
525:601: execution error: Terminal got an error: Can’t get settings set 1 whose name = "elvis". Invalid index. (-1719)
The invocation is slightly hacky, and could probably be improved if I took the time to learn getopt (e.g., something like term.sh -p profile -e command would be better and would, for instance, allow you to easily open a new terminal in the specified profile without invoking a command). And I also wouldn't be surprised if there are ways to screw it up with complex quoting. But it works for most purposes.
Almost all (every?) osx program can be launched from command line using:
appName.app/Contents/MacOS/command
For terminal the command is:
/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal
You can use the autocomplete (tab) or ls to find the correct filenames. ".app" is basically a folder.
To change the colors and run a script... I think you cannot do it with shell scripts as Terminal does not accept arguments ("Terminal myScript.sh" does not launch myScript). With iTerm this works.
Workaround is to use applescript (wrapped in a shell script):
#!/bin/sh
osascript -e '
tell application "Terminal"
activate
tell window 1
do script "sleep 5; exit"
set background color to {0, 11111, 11111}
set win_id to id
end tell
set w_ids to (id of every window)
repeat while w_ids contains win_id
delay 1
set w_ids to (id of every window)
end repeat
end tell'
Ok, now it should behave exactly the same as the xterm example. The drawback is the constant polling of the window ids (which is bad programming).
edit: A bit more elegant applescript would use the 'busy' property of Terminal. I will leave the original code as is works for a general program (not just terminal).
tell application "Terminal"
tell window 1
do script "sleep 2"
set background color to {0, 11111, 11111}
repeat while busy
delay 1
end repeat
close
end tell
end tell
Also for perfectly correct program, one should check that whether the terminal is running or not. It affects the number of windows opened. So, this should be run first (again a nasty looking hack, that I will edit later as I find a working solution).
tell application "System Events"
if (count (processes whose name is "Terminal")) is 0 then
tell application "Terminal"
tell window 1
close
end tell
end tell
end if
end tell
br,
Juha
You can also go into terminal GUI, completely configure the options to your heart's content, and export them to a ".terminal" file, and/or group the configurations into a Window Group and export that to a terminal file "myGroup.terminal". Then
open myGroup.terminal
will open the terminal(s) at once, with all your settings and startup commands as configured.
you can launch terminal with the following command, not sure how to specify colors:
open /Applications/Utilities/Terminal.app/
The answer from #david-moles above works but run the terminal and command in ~ rather the current working directory where term was launched. This variation adds a cd command.
#!/usr/bin/env bash
# based on answer by #david-moles in
# https://stackoverflow.com/questions/4404242/programmatically-launch-terminal-app-with-a-specified-command-and-custom-colors
echo "
on run argv
if length of argv is equal to 0
set command to \"\"
else
set command to item 1 of argv
end if
set command to \"cd '"$PWD"' ;\" & command
if length of argv is greater than 1
set profile to item 2 of argv
runWithProfile(command, profile)
else
runSimple(command)
end if
end run
on runSimple(command)
tell application \"Terminal\"
activate
set newTab to do script(command)
end tell
return newTab
end runSimple
on runWithProfile(command, profile)
set newTab to runSimple(command)
tell application \"Terminal\" to set current settings of newTab to (first settings set whose name is profile)
end runWithProfile
" | osascript - "$#" > /dev/null
There may be a way to set PWD this with applescript.
Note: When I use this, I sometimes two Terminal windows, one a shell running in ~ and a second which runs the cd command and command from argv[1]. Seems to happen if Terminal is not already running; perhaps it is opening old state (even tho I had no open terminals when I closed it).

Resources