Shell d条件表达式的奇怪行为
我的KornShell(ksh)手册说,如果文件存在并且是目录,Shell d条件表达式的奇怪行为,shell,unix,scripting,ksh,Shell,Unix,Scripting,Ksh,我的KornShell(ksh)手册说,如果文件存在并且是目录,-d表达式返回true。 因此,如果[[-d file]]是一个目录,那么if[[-d file]]应该返回TRUE。但就我而言,这不是它的工作原理。如果文件存在且不是目录,则返回TRUE,但shell的手册上显示“并且它是目录”。那么,有人知道为什么它的工作原理与它应该的相反吗?它工作得很好;是你的期望错了。在shell中,0返回值为true,而非零返回值为false $ true ; echo $? 0 $ false ; ec
-d
表达式返回true。
因此,如果[[-d file]]是一个目录,那么
if[[-d file]]
应该返回TRUE。但就我而言,这不是它的工作原理。如果文件存在且不是目录,则返回TRUE,但shell的手册上显示“并且它是目录”。那么,有人知道为什么它的工作原理与它应该的相反吗?它工作得很好;是你的期望错了。在shell中,0返回值为true,而非零返回值为false
$ true ; echo $?
0
$ false ; echo $?
1
ksh文件运算符|如果:
- -存在一个|文件
- -d | file是一个目录
- -f |文件是常规文件(即,不是目录或其他特殊类型的文件)
- -r |您已获得文件的读取权限
- -s |文件存在且不为空
- -您有文件写入权限
- -x |您对文件具有执行权限,如果是目录,则具有目录搜索权限
- -O |归档您自己的文件
- -G | file您的组ID与file的组ID相同
#***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."
}
参考:?如果您尝试
[-d文件]&回显“是”
?什么操作系统/版本?在osx 10.7.5上适用于我。请注意,如果我们能够确定它存在,并且在遵循符号链接后它是一个目录,那么这是正确的。因此,对于指向目录的符号链接,它返回true;对于位于您无权访问的目录中的目录,它返回false。您正在查看$?
?更新您的问题,向我们展示一些显示意外行为的代码。推测似乎合理,但OP没有说他正在检查$?
。