【发布时间】:2018-04-10 01:42:15
【问题描述】:
在这里猛击。希望编写一个脚本:
- 将绝对/相对目标目录作为其唯一输入参数并循环遍历其内容
- 如果其直接子项之一是文件,我希望它回显“
Found a file called $file!”(其中$file是文件名) - 否则,如果它的一个直接子级本身就是一个目录,我希望它回显“
Found a directory named $dir”(其中$dir是目录的名称),然后我想要它在该目录中以相同的确切逻辑递归执行,最后我希望它继续循环遍历目标目录的其余部分
因此给出以下目标目录结构:
~/testDir/
1.txt
2.txt
childDirA/
foo.png
3.txt
childDirB/
buzz.gif
childDirC/
foo.bar
4.txt
脚本的输出是:
Found a file called 1.txt!
Found a file called 2.txt!
Found a directory named childDirA
Found a file called foo.png!
Found a file called 3.txt!
Found a directory named childDirB
Found a file called buzz.gif!
Found a directory named childDirC
Found a file called foo.bar!
Found a file called 4.txt!
到目前为止,我能想到的最好的是:
#!/bin/bash
for file in $1;
do echo "Found a file called $file";
done
但是,如果我将其指向我的 testDir,我得到的唯一输出是:
Found a file called testDir
有什么想法会出错吗?
【问题讨论】:
-
我会尝试使用
find。这就是它的设计目的。 -
我可以使用 find 但我的脚本实际上不仅仅是回显文件名和目录,我只是想先找出递归问题。
-
find可以做的不仅仅是回显名称。重新发明轮子没有意义。 -
具体看
find的-exec参数。 -
ls -R可以打印您想要的相同信息