Jump to content

spaces removed when using osascript

Recommended Posts

echo $argv > ~/Desktop/deleteme.txt
osascript ~/Scripts/Alfred/filemaker/show_last_invoice.scpt $argv

Contents of deleteme.txt

"some text  with spaces"



Relevant code of show_last_invoice.scpt:

on run arg
set the clipboard to arg as text
end run

Contents of clipboard: 


--note that the spaces have been removed. I want to know how to avoid this.



Running this command from Terminal.app

osascript ~/Scripts/Alfred/filemaker/show_last_invoice.scpt "some text with spaces"


 Contents of clipboard: 

some text with spaces

Link to comment

There are a couple of issues with your code. What's happening is that you're actually calling show_last_invoice.scpt with multiple arguments because you're not quoting $argv in your bash. Instead of complaining, AppleScript silently joins the arguments (without spaces) when you set the clipboard.
That is to say, the command you're calling isn't equivalent to what you posted:

osascript ~/Scripts/Alfred/filemaker/show_last_invoice.scpt "some text with spaces"

but rather:

osascript ~/Scripts/Alfred/filemaker/show_last_invoice.scpt some text with spaces

i.e. There are 4 arguments, not 1.
Your bash should look like this. Note the double quotes. Without the quotes, bash interprets spaces as argument delimiters and passes multiple arguments: 

/usr/bin/osascript script.scpt "$q"

 That's enough to fix your script (now you're only passing one argument, it doesn't matter that AppleScript is joining all the arguments without spaces), but it's still not technically correct.
The argument passed to on run in AppleScript is also a sequence of strings, not a single string. Correctly, your AppleScript should be: 

on run argv
    set the clipboard to (first item of argv as text)
end run

If you want your AppleScript to be able to handle multiple arguments, you need to join argv into a string. In your script, you could just do:

on run argv
    set AppleScript's text item delimiters to " "
    set the clipboard to argv as text
end run

A more general solution is:

on implode(delimiter, theList)
    set TIDs to AppleScript's text item delimiters
    set AppleScript's text item delimiters to delimiter
    set output to "" & theList
    set AppleScript's text item delimiters to TIDs
    return output
end implode

on run argv
    set theString to implode(" ", argv)
    set the clipboard to theString as text
end run
Edited by deanishe
Add shorter solution
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...