刚写了一个bash脚本,简化如下:
#!/bin/sh
for file in $1/*
do
echo it is $file
if [ -d "$file" ] && echo is it true;then
cd $file
echo it is a d
pwd
echo it is $file
elif [ -f "$file" ]; then
echo it is a f
fi
done
exit 0
然后加运行,driver_code中有文件名为3到22的那么几个文件夹,得到结果如下:
[root@localhost tmp]# ./ft.sh driver_code
it is driver_code/03
is it true
it is a d
/home/gm/tmp/driver_code/03
it is driver_code/03
it is driver_code/04
it is driver_code/05
it is driver_code/06
it is driver_code/07
it is driver_code/08
it is driver_code/09
it is driver_code/10
it is driver_code/11
it is driver_code/12
it is driver_code/13
it is driver_code/14
it is driver_code/15
it is driver_code/16
it is driver_code/17
it is driver_code/18
it is driver_code/19
it is driver_code/20
it is driver_code/21
it is driver_code/22
[root@localhost tmp]#
从结果分析,也就是 if [ -d "$file" ] && echo is it true只判断了一次!这是为什么啊?为什么for语句在第二个参数遇到if就没有进去判断呢?搞不懂啊
wucongdonglai 于 2011-01-10 08:37:34发表:
3# deepwhite
原来如此,我说为何有这么奇怪的现象呢! 加一对圆括号就好了
刘仙阳 于 2011-01-08 13:31:42发表:
我也来请教请教
naruto01 于 2011-01-07 17:07:21发表:
[code]echo it is $file
cd ..[/code]随便说的。 - -#
deepwhite 于 2011-01-07 16:44:37发表:
输入的是相对路径的话, 得到的 $file 也是相对路径;你 cd 到某个目录下,执行一些操作,最后没有退回到最初的目录,以后对 $file 的判断实际上是在你第一次 cd 到的那个目录底下进行的,而由于 $file 是相对路径,在不正确的目录下对他进行 -f 或者 -d 的判断,都不会返回正确的结果。
也就是说, if 判断起作用了,但是你的 cd 命令用的不成对, 误导了你的程序。
Linux_zhanzhi 于 2011-01-07 15:18:33发表:
占个位子学习下