[英]How to write a linux script that copies all the files and directories under one directory to another directory?
I am having a bit of a problem with a script I am trying to create.我尝试创建的脚本有点问题。
This script should take two arguments which are the source directory and the destination directory and if the user enters less than 2 arguments it should print out an error message and exit.此脚本应采用两个参数,即源目录和目标目录,如果用户输入的参数少于 2 个,则应打印出错误消息并退出。 In addition this script should check if the source directory exists or not, if not it should print out an error message and exit.
此外,此脚本应检查源目录是否存在,如果不存在,则应打印出错误消息并退出。 Also the script should check if the destination directory exists or not, if not it should create that directory.
此外,脚本应检查目标目录是否存在,如果不存在,则应创建该目录。 Finally the script should copy the files from the source directory to the destination directory.
最后,脚本应该将文件从源目录复制到目标目录。
This is my attempt so far:到目前为止,这是我的尝试:
if (( $# < 2 ));
echo "Error: Too few arguments supplied"
exit 1
if [ -d "src_dir" ]
then
echo "Directory src_dir exists."
else
echo "Error: Directory src_dir does not exist."
fi
if [ -d "dst_dir" ]
then
echo "Directory dst_dir exists."
else
mkdir dst_dir
cp -r src_dir/* dst_dir
fi
Any help would be really appreciated.任何帮助将非常感激。 Thanks in advance!
提前致谢!
For checking the correct number of arguments: Check number of arguments passed to a Bash script检查参数的正确数量: 检查传递给 Bash 脚本的参数数量
if [ "$#" -ne 2 ]; then
echo "Error: Too few arguments supplied"
exit 1
fi
For checking if the directory exists or not: Check if a directory exists in a shell script检查目录是否存在: 检查shell脚本中是否存在目录
if [ ! -d "$1" ]; then
echo "Error: Directory $1 does not exist."
exit 1
fi
For making the dir on second argument: How to use Bash to create a folder if it doesn't already exist?用于在第二个参数上创建目录:如果文件夹不存在,如何使用 Bash 创建文件夹?
mkdir -p $2
Finally, just copy them all:最后,只需将它们全部复制:
cp -r $1/* $2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.