日期:2014-05-16  浏览次数:20770 次

Linux shell脚本里判断式的问题
写了个脚本,判断指定目录下所有文件的类型:

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

read -p "input the dir:" dir
if [ "$dir" == "" -o ! -d "$dir" ]; then
echo  "not dir"
exit 1
fi
filelist=$(ls $dir)
for file in $filelist
do
if [ -f "$file" ]; then
echo "File: $file"
elif [ -d "$file" ]; then
echo "Dir: $file"
else 
echo "Others : $file"
fi
done


现在的问题是,如果指定的目录是该脚本所在的目录,上面的脚本执行就没问题,但如果指定的目录是其他目录,上面的[ -f "$file" ]、[ -d "$file" ]判断式就都无法正常判断文件类型了(结果全部为假),所有文件都输出的Others:

Others : Audiobooks
Others : desktop
Others : IBM
Others : libgooglepinyin
Others : maple
Others : maple12
Others : Podcasts
Others : Program
Others : rational
Others : reg
。。。。。


这是为什么呢?怎么样能让它总是正确执行呢?
linux?shell 判断式

------解决方案--------------------
呵呵,你脚本里面加一句,刚一进去判断目录没问题的话,就cd $dir应该就行了。
因为脚本在当前目录,但ls的结果是其它目录下的,所以不认识它就认识它是other了。


------解决方案--------------------
ls列出来的都是相对路径,应该记住脚本目录,cd进去,测试完,在退出来。
------解决方案--------------------
引用:
呵呵,你脚本里面加一句,刚一进去判断目录没问题的话,就cd $dir应该就行了。
因为脚本在当前目录,但ls的结果是其它目录下的,所以不认识它就认识它是other了。


+1,对头,不指定目录的话默认是当前目录的