Home > Uncategorized > Bash – Check if Directory Writable

Bash – Check if Directory Writable

February 28th, 2010 subogero

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.

Categories: Uncategorized Tags: , ,
  1. gergo
    March 6th, 2010 at 09:08 | #1
    #!/usr/bin/python
    from sys import argv
    from tempfile import TemporaryFile
    try:
      t = TemporaryFile(dir=argv[1])
      t.write('foo')
      t.close()
    except OSError:
      print 'Nearp!'
    else:
      print 'Yearp!'
    
  2. March 6th, 2010 at 20:19 | #2

    @gergo
    One has to admit, even a toddler can read Python.
    And it beats the Bourne Again Shell even in Jack Rabbit Slim’s world famous Number-Of-Lines contest. By eleven to one, Ladies and Gentlemen.

    Still, I just can’t suppress an odd sympathy towards old bash. I must be religiously prejudiced.

Comments are closed.