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'"
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.
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.
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
Just to keep @sphil happy , 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)