Bash – Check if Directory Writable
Back to the basics, a.k.a. the Bourne Again Shell.
How to check in a script whether a directory is writable? Many would suggest the
if [ -w $DIR ]; then echo Do semething; fi
way, but it just checks the writable flag, which may be set on something on a read-only-mounted device. It’s much better to effectively try it.
Do something if $DIR is not writable
touch ${DIR}/foo && rm -f ${DIR}/foo || echo Do something
Do something if $DIR is writable
touch ${DIR}/foo && rm -f ${DIR}/foo && echo Do something
Do something if $DIR is writable, otherwise suppress the error message
touch ${DIR}/foo 2>/dev/null && rm -f ${DIR}/foo && echo Do something
Do something if $DIR is writable, otherwise print a custom diagnostic message
touch ${DIR}/foo 2>foo && rm -f ${DIR}/foo && echo Do something cat foo | sed 's/.*/Directory not writable!/' && rm -f foo
The above case is a bit special. Let’s see what happens:
- touch attempts to create file “foo” in $DIR
- it’s potential error message is redirected to file “foo” in currect dir
- the commands afters “&&” are only executed if touch has succeeded
- if so, file “foo” in $DIR is removed and we “Do something”
- the error message stored in “foo” is replaced by our own, using sed
- file “foo” with the original error message is removed.
Note: the sed-pipeline cannot be integrated into the first line, because pipelines only fail if their last command does, so we would forget whether “touch” has failed or not.