Test if file is writable?

I seem to be making an absurd beginner’s mistake. This command produces the correct results in the terminal:

test -w filename && echo "Writable" || echo "Not Writable"

But this script always produces “false”:

set myFile to choose file
set myPosix to POSIX path of myFile
set writable to do shell script "test -w" & space & myPosix

What am I missing? Probably something embarrassingly obvious.

PS: But this script works correctly:

set myFile to choose file
set myPosix to POSIX path of myFile
set writable to do shell script "test -w" & space & myPosix & space & "&& echo 'Writable' || echo 'Not Writable'"

Have you tried quoted form of myPosix?

Same result, I’m afraid

Try this:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

set myFile to choose file
set myPosix to quoted form of POSIX path of myFile
set writable to do shell script "test -w " & myPosix & "; echo $?"

I am a real shell script novice, but I find that:
set writable to do shell script "test -w " & myPosix & "; echo $?"
returns the opposite of what I would expect.

It returns:
“0” – if file IS writeable
"1" – if file is NOT writeable.

This seems opposite of this reference:

The following operators returns true if file exists:
-w FILE
FILE exists and write permission is granted

So, I changed your script to be logical (for me):

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

set myFile to choose file
set myPosix to quoted form of POSIX path of myFile

--- Returns bool true IF file is writable ---
set writable to (do shell script "test -w " & myPosix & "; echo $?") = "0"

This works in my testing, but then I’m probably missing something. :wink:

Here’s a very similar solution that works:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions

set myFile to choose file
set myPosix to quoted form of POSIX path of myFile

--- Returns bool true IF file is writable ---
set writable to (do shell script "test -w " & myPosix & "; echo $?") = "0"

--- This Seems to Work More Logically ---
--  Returns "TRUE" if the file is writable

set cmdStr to "[ -w " & myPosix & " ] && echo \"TRUE\" || echo \"FALSE\""
log cmdStr

set isWritable to do shell script cmdStr

return isWritable


Based on:
Bash Shell: Check File Exists or Not

Just to keep @sphil happy :slight_smile:, here’s an alternative:

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

set myFile to POSIX path of (choose file)
set theURL to current application's |NSURL|'s fileURLWithPath:myFile
set {theResult, isWritable} to theURL's getResourceValue:(reference) forKey:(current application's NSURLIsWritableKey) |error|:(missing value)

Yes, more code. But it does make a difference:

Very grateful for all these replies - and, as always, in this forum, I’ve learned a lot about AppleScript and about logic in the process. Thank you!