Shell directory tests [ -d ] and permissions

I have a simple shell script that looks like this :

#!/bin/bash

AMAVIS_VIRUSMAILS="/var/lib/amavis/virusmails"

if [ -d "${AMAVIS_VIRUSMAILS}" ]; then
        echo "ok"
fi

/var/lib/amavis and its sub-directories are, of course, owned by the amavis user. Which means that I get :

   $ ls /var/lib/amavis/virusmails
    ls: cannot access /var/lib/amavis/virusmails: Permission denied

When I run the ls command as another user without root or sudo privileges.

However. If I run the above shell script, it doesn’t print “ok”. Which, in other words, means the shell script is telling me the directory does not exist. Which is of course not true, it does exist, but I just don’t have the permissions to access it.

I get the same result with #!/bin/sh

I therefore have two questions :

  1. Is this the as expected and “as designed” behavior of the -d test ?
  2. How should I best work around the problem so as to avoid false negatives ?

If it makes any difference, this is Ubuntu 14.04LTS, 3.13.0-53-generic. Which means I’m running GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu), or dash(sh) version 0.5.7-4ubuntu1


Source: linux

Leave a Reply