我正在尝试模拟cp -R Linux命令。我写了下面的脚本,该脚本可以正常工作,但是后来我创建了一个新的树目录来再次对其进行测试,并且它的行为很奇怪,我不知道我的错误在哪里。
该脚本采用两个参数,即要复制的目录和目标。我想传递目录“ test_myLookup”作为第一个参数(要复制的目录),将第二个参数传递到目标路径(可以在下面看到两者)。
知道为什么我会出现这种奇怪的行为吗?谢谢
脚本:
#
src=${1}
dst=${2}
#CREATE DIRECTORIES
function directories() {
IFS=
dirs="$1"/*
for d in ${dirs}
do
if [ -d "${d}" ]; then
mkdir -p "${dst}${d}"
chmod 777 "${dst}/${d}"
directories "${d}"
fi
done
IFS=' \t\n'
}
#COPY FILES
function files(){
dirs="$1"/*
IFS=
for d in ${dirs}
do
if [ -f "${d}" ]; then
cp "${d}" "${dst}${d}"
chmod 660 "${dst}/${d}"
fi
done
IFS=' \t\n'
IFS=
for d in ${dirs}
do
if [ -d "${d}" ]; then
files "${d}"
fi
done
IFS=' \t\n'
}
function main(){
directories ${src} ${dst}
files ${src} ${dst}
}
main "${src}${dst}"
chmod 777 "${dst}/${src}"
结果到另一个目录:
命令:
$ ./copy_v2 "test_myLookup" "/home/carlos/Documents/operating_systems/project_1/working_commands/test_myCopy/"
输出:
cp: cannot open '/swapfile' for reading: Permission denied
chmod: cannot access '/home/carlos/Documents/operating_systems/project_1/working_commands/test_myCopy///swapfile': No such file or directory
cp: cannot open '/vmlinuz' for reading: Permission denied
chmod: cannot access '/home/carlos/Documents/operating_systems/project_1/working_commands/test_myCopy///vmlinuz': No such file or directory...
一直打印这些错误...
它创建目录树,但不复制文件,而是出现一些奇怪的文件。
我正在测试的目录是新目录,我只是出于测试目的创建了目录,试图从错误消息中复制这些奇怪的文件?
编辑:
如果我在函数main中注释行文件$ {src} $ {dst}并使其运行良好,这很奇怪,然后我取消注释,这次注释目录$ {src} $ {dst}并运行它,脚本执行了应该执行的操作。
如果我运行原始脚本,同时调用这两个函数,那就是崩溃。
它通过引用传递给main的参数$ src进行了固定(不需要删除另一个参数。我忘记了传递此参数时要使用“”。当传递路径作为参数“”时,不要丢失空格和路径中的特殊字符。