Georgi Georgiev
Georgi Georgiev

Reputation: 1623

Strange behaviour of -d conditional expression

My KornShell (ksh) manual says that -d expression returns true if the file exists and it is a directory. So if [[ -d file ]] should return TRUE if file is a directory. But in my case this is not how it works. It returns TRUE if the file exists and is NOT a directory, but the manual of the shells says "and it is a directory". So does anyone have any idea why it is working in the opposite of what it should be?

Upvotes: 1

Views: 67

Answers (2)

javaPlease42
javaPlease42

Reputation: 4963

ksh File Operator | True if:

  • -a | file exists
  • -d | file is a directory
  • -f | file is a regular file (i.e., not a directory or other special type of file)
  • -r | You have read permission on file
  • -s | file exists and is not empty
  • -w | You have write permission on file
  • -x | You have execute permission on file, or directory search permission if it is a directory
  • -O | file You own file
  • -G | file Your group ID is the same as that of file

kshFileOperatorsFunction.ksh

#***Function to demo ksh file Operators.***#
fileOperators(){
    echo "Entering fileOperators function."
    if [[ ! -a $1 ]]; then
        print "file $1 does not exist."
        return 1
    fi
    if [[ -d $1 ]]; then
        print -n "$1 is a directory that you may "
        if [[ ! -x $1 ]]; then
            print -n "not "
        fi
        print "search."
    elif [[ -f $1 ]]; then
         print "$1 is a regular file."
    else
         print "$1 is a special type of file."
    fi
    if [[ -O $1 ]]; then
        print 'you own the file.'
    else
        print 'you do not own the file.'
    fi
    if [[ -r $1 ]]; then
        print 'you have read permission on the file.'
    fi
    if [[ -w $1 ]]; then
        print 'you have write permission on the file.'
    fi
    if [[ -x $1 && ! -d $1 ]]; then
        print 'you have execute permission on the file.'
    fi
    echo "Exiting fileOperators function."
}

Reference : O'Reilly, Learning the KornShell Volume 1

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798884

It's working fine; it's your expectations that are wrong. In shells, a 0 return value is true, and a non-zero return value is false.

$ true ; echo $?
0
$ false ; echo $?
1

Upvotes: 3

Related Questions