In a shell script, how do I easily and non-invasively test for write access to a file without actually attempting to modify the file?I could parse the output of stat, but that seems really complex, and perhaps brittle, though I'm not sure how much stat output differs across implementations and time.I could append to the end of the file and see if that succeeds, but that's potentially dangerous, for two reasons I can think of:I now have to remove the addition, and in case some other process writes to the file, this immediately becomes non-trivial as my line is no longer the last one.Any process reading the file may have arbitrary requirements on the contents of that file, and I may just have broken that application.
How to non-invasively test for write access to a file?
shell script;files;permissions;scripting
Just use the -w flag of the test utillity:[ -w /path/to/file ] && echo writeable || echo write permission deniedNote that if you're going to write to the file later, it's still possible that you won't be able to write to it. The file may have moved, the permissions may have changed, etc. It can also happen that -w detects write permissions but some other factor intervenes to make the file not writable.