我对Bash编写非常陌生,并且要进行一些练习,我试图编写一个包含源目录和目标目录的脚本。该脚本将搜索源目录并将其子目录结构复制到目标目录(所有文件将被忽略,仅目录本身将被复制)。源目录可以在任意深度具有任意数量的子目录。实现此目标的最佳方法是什么?我首先尝试编写一个递归函数,如果找到目录,则在该目录上递归调用该函数。但是,由于我缺乏脚本编写经验,所以我很沮丧。
这是我到目前为止的内容:
#! /bin/bash
if [ ! $# -eq 2 ]; then
echo "ERROR: Script needs 2 arguments: $0 source/directory/ target/directory/"
exit
fi
SOURCE_DIR=$1
TARGET_DIR=$2
function searchForDirectory {
for FILE in ls $SOURCE_DIR/*; do #should be 'ls *current_directory*'
if [ -d $FILE ]; then
searchForDirectory #call function recursively onto $FILE
#Do stuff here to create copy of this directory in target dir
fi
done
}
if [ ! -d $SOURCE_DIR ]; then
echo "ERROR: Source directory does not exist"
exit
else
searchForDirectory
fi
我知道这只是一个基本功能,需要做很多工作,但是我只是在寻找进一步的指导,以了解这是否是正确的解决方法,然后再继续。如果是这样,我的下一步是什么?如何将目录传递到函数中?
编辑:这是我的解决方案,感谢#下方Ivan的帮助!/ bin / bash
if [ ! $# -eq 2 ]; then
echo -e "\nERROR: Script needs 2 arguments:\n$0 source/directory/ target/directory/\n"
exit
fi
function recursiveDuplication {
for file in `ls $1`; do
if [ -d $1/$file ] && [ ! -d $2/$file ]; then
mkdir $2/$file
recursiveDuplication $1/$file $2/$file
elif [[ $1/$file == *.png ]]; then
convert $1/$file $2/$file
fi
done
}
if [ ! -d $1 ]; then
echo -e "\nERROR: $1 does not exist\n"
exit
elif [ -d $2 ] && [ ! -w $2 ]; then
echo -e "\nERROR: You do not have permission to write to $2\n"
exit
elif [ ! -d $2 ]; then
echo -e "\nSUCCESS: $2 has been created"
mkdir $2
fi
recursiveDuplication $1 $2
此解决方案有两个问题:
正如Rany Albeg Wein在下面解释的那样,使用'ls'并不是一个很好的解决方案-我已经知道了为什么目录/*.png名称中有空格。
我还尝试将任何* .png文件从源复制到目标,并将其转换为目标中的* .jpg图像。我怎样才能做到这一点?我正在尝试使用ImageMagick的convert image.png image.jpg
命令,但是当image.png
被称为时不知道该怎么做$file
?
#!/bin/bash
# 1st argument - source dir, 2nd - destination
function rrr {
for i in `ls $1`
do
if [ -d $1/$i ]
then
mkdir $2/$i
rrr $1/$i $2/$i
fi
done
}
rrr $1 $2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句