shell脚本来遍历目录 [英] Shell script to traverse directories
问题描述
我的工作,需要大量的图像文件的批量处理的项目。为了方便起见,我写了一个脚本,将创建 N
目录和基于移动 M
文件给他们用户输入。
I'm working on a project that requires batch processing of a large number of image files. To make things easier, I've written a script that will create n
directories and move m
files to them based on user input.
我的问题是到现在为止通过shell脚本理解目录遍历。
My issue is to now understand directory traversal via shell script.
我在上面
dirlist=$(find $1 -mindepth 1 -maxdepth 1 -type d)
for dir in $dirlist
do
cd $dir
echo $dir
ls
done
当我跑它Pano2文件夹,whcih包含两个内部文件夹里面,我总是得到一个错误
When I ran it inside a Pano2 folder, whcih contains two inner folders, I always got an error
./dirTravel: line 9: cd: Pano2/05-15-2012-2: No such file or directory
不过,在那之后,我得到的文件从指定的目录列表。
However, after that, I get the file listing from specified directory.
有什么警告背后的原因是什么?如果我 LS之后添加
我进去Pano2 /,而不是文件的文件夹上市他们自己。 CD ../
What is the reason behind the warning? If I add cd ../
after ls
I get the listing of the folders inside Pano2/, but not the files themselves.
推荐答案
我的猜测是,你会在两个层次深,但只回来了一个级别。尝试 LS后加入
,或使用 CD ../..
PUSHD
和 POPD
来代替。
My guess is that you're going in two levels deep, but only coming back up one level. Try adding a cd ../..
after the ls
, or use pushd
and popd
instead.
例如:
for dir in $dirlist
do
pushd $dir
echo $dir
ls
popd
done
由于@shellter指出,如果这些目录中有空格,那么这样的事情可能会更好地工作:
As @shellter points out, if those directories have spaces, then something like this might work better:
find $1 -mindepth 1 -maxdepth 1 -type d | while read -r dir
do
pushd "$dir" # note the quotes, which encapsulate whitespace
echo $dir
ls
popd
done
这篇关于shell脚本来遍历目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!