Home > Mobile >  AppleScript do shell script returns error for "which" command
AppleScript do shell script returns error for "which" command

Time:12-31

I'm writing an AppleScript that will ask a user which remote cloud service and then which bucket they would like to mount in Mac OS using rclone. But in order to run the rclone command in an AppleScript, you need to include the entire path to the app. For me that is: /usr/local/bin/rclone

I want to include, as a variable, the location of rclone using the which command in a shell script like this:

set rcloneLOC to paragraphs of (do shell script "which rclone")

But I get a script error stating "The command exited with a non-zero status." This happens even if I just try to run do shell script "which rclone" by itself. If I type which rclone into terminal, I get the result I expect.

How do I get this to work?

CodePudding user response:

As @GordonDavisson suggests, you can view your path using echo $PATH.

To change your applescript's path (and view the change) try this:

do shell script "export PATH=/usr/local/bin:$PATH ; echo $PATH" 

The first part of the shell command (up to the semi-colon) will prepend /usr/local/bin to your default path. The second part will return your updated path. The semi-colon has the second part run after the first part is finished.

It's important to note that this change is temporary and only in effect for this shell script and only while it is operating. This is why you need the combined commands in order to see the effect.

I'll use 'rsync' as an example since I don't have rclone; substitute 'rclone' to get its path. To get its path, you combine the export command with which, like so:

do shell script "export PATH=/usr/local/bin:$PATH ; which rsync"

The result is /usr/local/bin/rsync.

To clarify a couple of things… the environment is a set of conditions that apply for each user. You can get a basic rundown of it by running man 7 environ in Terminal. There is an env command which lists your settings and allows you to edit them; man env will provide info on it. At the bottom of these man pages, you should see references to related commands which you can also look up. Meanwhile, from within Script Editor, you could run a 1-line script with do shell script "env" and see the corresponding environment for applescript's shell.

Based on Apple's documentation (or my interpretation of it), they chose this setup because it is relatively secure and portable. You know what you get every time you run a shell script. You don't need to use a more modern shell to run the which command. You can modify the environment as needed, the same way you would while using the terminal.

Finally, Apple has provided Technical Note 2065 which provides info on using shell scripts with applescript. Also, you can likely get more info here or on the unix stack exchange.

NB All of the above is just my understanding, which is limited.

  • Related