r/applescript • u/matt_smog • May 23 '23
Reading path name with spaces
I have assigned a keyboard shortcut to run this AppleScript which reopens the last closed Finder location. This works perfectly on folder locations without spaces, but not on folders with spaces.
If I close the folder "/Users/username/Desktop/Folder With Space" then run the script, I get the error:
The action “Run AppleScript” encountered an error: “The files
/Users/username/Desktop/Folder and /With and /Space do not exist.”I understand that a double backslash '\\' can be used to read a directory with spaces? But I'm not sure how to alter the script to account for this. Essentially what I'm trying to insert is:
if thePath contains " "
then replace " " with "\\"
elseI don't have much experience with AppleScript, so any help is appreciated! 🙏
2
u/matt_smog May 23 '23
Pasting the full script here for convenience:
2
u/copperdomebodha May 23 '23
quoted form of "your/path with spaces in it/goes here/"
1
u/stephancasas May 23 '23
Here's a version of your script, written in the JavaScript version of AppleScript (JXA), that can handle paths containing whitespace characters:
Instead of writing our own logic to handle the data un-marshal process, we can use the macOS APIs for handling bookmarks directly by using the Objective-C bridge in JXA to call methods on
NSURL. This is a cleaner and more reliable way of handling such data.To use this, set the dropdown in the upper-left corner of Script Editor to "JavaScript" instead of "AppleScipt." You can then paste the code, and run it like you would your previous script.
Cheers.