1

How would I redefine and/or define new conditional expression primaries in bash? For example, I would like a primary that tests for the existence of an empty directory. Of course, it would be preferable to do this with only one primary, but if that is not possible, then two primaries is also acceptable. As an example, I would like to be able to accomplish this:

    if [ -DZ $HOME/dir ]; # true if directory the path is an empty directory
      then echo "$HOME/dir doesn't have any non-hidden files or directories!"
    fi
3

To add your own test predicates, you would have to modify the bash sources for the built-in [ command. This is probably not what you want to do, as it would result in hopelessly non-portable scripts. You may instead employ a shell function:

isemptydir () (
    shopt -s nullglob
    shopt -s dotglob

    if [ -z "$1" ]; then
        echo 'isemptydir: Empty or missing argument' >&2
        return 1

        # could instead do: set .
        # this would use the current directory as the "default" one
    fi

    if [ -d "$1" ]; then
        # note: above test fails on inaccessible dirs --> "not empty"

        set -- "${1%/}"/*
        [ "$#" -eq 0 ]
        # note: above test succeeds on unlistable dirs --> "empty"           
    fi
)

if isemptydir "$mydir"; then
    printf 'Directory "%s" is empty\n' "$mydir"
else
    printf '"%s" is not a directory, or is not empty\n' "$mydir"
fi

The function tests whether the given argument is the name of a directory. If it is, it counts the number of names (not just files) that are available in the directory, including hidden names, and compares this to zero. The return status of the test that is performed last is the return status of the function.


You could possibly overload the [ or test commands with your own functions, but that would also potentially be problematic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.