递归复制文件夹:Shell

时间:2019-06-21 18:38:26

标签: shell directory copy

我的代码从用户那里接受两个参数。我的目标是找到用户给定的文件夹(第一个参数),并根据需要复制尽可能多的副本(第二个参数)。截至目前,我的代码以递归方式打印出所有子目录和子目录中的文件...我的代码还按用户指定的次数复制文件。但是,这就是我的问题,我的复制功能仅适用于文件,而不适用于文件夹...我想知道如何修改我的复制功能(或代码的任何其他部分),以便它以递归方式复制指定的文件夹及其所有文件夹。原始内容

我知道代码底部的cp函数需要更改为 -r ./sourceFolder ./destFolder,但是鉴于传入的参数,我不知道该怎么做。毕竟,目标文件夹名称将只是原始文件夹,并在其末尾增加一个数字。

#!/bin/bash


read -p "Your folder name is $1 and the number of copies is $2. Press Y for yes N for no " -n 1 -r
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
echo
echo "Rerun script and pass in the folder and how many copies yo would like (e.g folder 4)"
exit
fi
echo 
echo "-------------COPY FILE----------------"

FOLDER=$1
for f IN $folder
do
if [ ! -f "$FOLDER" ]
then
echo "folder "$FOLDER" does not exist"
exit 1 
fi 
done

DIR="."

function list_files()
{

cd $1
echo; echo "$(pwd)":; #Display Directory name

for i in *
do
if test -d "$i" #if dictionary
then 
list_files "$i" #recursively list files
cd ..
else
echo "$i"; #Display File name
fi

done
}

j=$2
for i in "$*"
do
DIR=$1 
list_files "$DIR"

 for ((i=1; i<J; i++))
do
cp "$1" "$1$i"; #copies the file i amount of times, and creates new files with names that increment by 1
done
shift 1
done

1 个答案:

答案 0 :(得分:0)

如果要复制递归,可以使用cp -r <source folder> <destination folder>。 这会将源文件的内容复制到目标文件夹。

#!/bin/bash

read -p "Your folder name is $1 and the number of copies is $2. Press Y for yes N for no " -n 1 -r
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
echo
echo "Rerun script and pass in the folder and how many copies yo would like (e.g folder 4)"
exit
fi
echo 
echo "-------------COPY FILE----------------"

FOLDER=$1
if [ ! -d "$FOLDER" ]
then
echo "folder  $FOLDER does not exist"
exit 1 
fi

j=$2
for ((i=1; i<=j; i++))
do
cp  -r "$1" "$1$i"; #copies the file i amount of times, and creates new files with names that increment by 1
echo "folder $1 copied to $1$i"
done

我将文件夹检查从-f更改为-d,更改了变量名(大小写),删除了list_files函数,并在最后一个for循环中更改了{{1 }}到i<$j,因为循环从i<=j开始。然后我添加了-r,并且可以正常工作。