Test whether shell script will have permission to write to a folder?

I have a script that runs a command-line utility that creates a file. This fails if the folder where the file is to be created is outside the user’s own folder structure (e.g. in a folder with a name like /Files/Notes). Is there a simple way that a script can test whether it will be able to write to that folder, and warn the user in advance?

Thanks for any help with this.

I suppose the simple answer to my own question is:

do shell script "echo hello > /possibly/forbidden/folder/hello.txt"

and test for an error message. If there is no error, then clean up with:

do shell script "rm /possibly/forbidden/folder/hello.txt"

If there’s anything more direct than this, I’ll be glad to hear about it.

This should do it. According to the docs, it determines “whether the current process (as determined by the EUID) can write to the resource”:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"

set thePath to "/System" -- whatever
set theURL to current application's |NSURL|'s fileURLWithPath:thePath
set {theResult, canWrite} to theURL's getResourceValue:(reference) forKey:(current application's NSURLIsWritableKey) |error|:(missing value)
canWrite as boolean

Shane,

Thank you. That does the job perfectly.

For the sake of long-term beginners like me, the next lines of the script should be something like:

if not canWrite then
		display dialog "Apple won't let me work with the folder that contains your file." 
		error number -128
end if

Thanks again!

You could also make your shell script more complete :slight_smile:

set shellScript to "if [[ -w /Library ]]
then
	#execute command line utility
	
	exit 0
else
	#we don't have write permission
	echo \"Cannot write to folder\"
	exit 1
fi"


try
	do shell script shellScript
on error ErrMsg number ErrNr
	if ErrNr = 1 then
		display dialog "Apple won't let me work with the folder that contains your file."
		error number -128
	end if
end try

Very nice indeed!