【问题标题】:Copy Folders Recursively: Shell递归复制文件夹:Shell
【发布时间】:2019-11-04 14:56:09
【问题描述】:

我的代码从用户那里获取两个参数。我的目标是找到用户提供的文件夹(第一个参数)并制作尽可能多的副本(第二个参数)。截至目前,我的代码递归地打印出所有子目录和子目录中的文件......我的代码还复制了用户指定的文件次数。但是,这是我的问题,我的复制功能只适用于文件而不是文件夹......我想知道如何修改我的复制功能(或代码的任何其他部分),以便它递归地复制指定的文件夹及其所有原创内容

我知道代码底部的 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

【问题讨论】:

  • 你试过if test -d "$1"吗?
  • 是...错误状态 cp: cannot stat 'folder' - no such file or directory found... 而且我很确定我传入的文件夹存在

标签: shell directory copy


【解决方案1】:

如果你想复制递归,你可以使用cp -r &lt;source folder&gt; &lt;destination folder&gt;。 这会将源文件的内容复制到目标文件夹。

#!/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 循环中将i&lt;$j 更改为i&lt;=j,因为循环以1 开头。然后我添加了 -r 并且它起作用了。

【讨论】:

  • 我试过了....不幸的是没用。代码仍然运行,但没有任何反应。现在没有复制任何东西
  • 我认为它不起作用,因为你改变了变量的大小写(例如你初始化j(小写)并在for循环中使用它作为J'(大写)) .
  • 当我将文件夹传递到您的代码中时,我收到错误 cp:cannot stat 'testfolder': No such file or directory....
  • 您确定该文件夹存在吗?
猜你喜欢
  • 2011-01-12
  • 2018-02-07
  • 2015-12-03
  • 2012-11-26
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
相关资源
最近更新 更多