Is the directory NOT writable

user2021539 picture user2021539 · Apr 3, 2013 · Viewed 7.4k times · Source

Can anyone tell me why this is always saying that the directory is not writable, when it absolutely is?

    $dnam="/home/bryan/renametest/C D"

    # Is the directory writable
    err=0
    if [ ! -w $dnam ]
    then
        # Not writable. Pop the error and exit.
        echo "Directory $dnam is not writable"
        err=1
    fi

Answer

Gordon Davisson picture Gordon Davisson · Apr 3, 2013

You need double-quotes around $dnam -- without them, it's interpreted as two separate shell words, "/home/bryan/renametest/C" and "D", which makes an invalid test expression and hence fails. This should work:

if [ ! -w "$dnam" ]

@tink's suggestion of [[ ]] is a cleaner way of doing tests like this, but is only available in bash (and some other shells with extended syntax). The fact that you get [[: not found means you're using a fairly basic shell, not bash.