【问题标题】:How to write a linux script that copies all the files and directories under one directory to another directory?如何编写一个将一个目录下的所有文件和目录复制到另一个目录的linux脚本?
【发布时间】:2016-08-17 13:12:18
【问题描述】:

我尝试创建的脚本有点问题。

这个脚本应该接受两个参数,即源目录和目标目录,如果用户输入的参数少于 2 个,它应该打印出错误消息并退出。此外,此脚本应检查源目录是否存在,如果不存在,则应打印出错误消息并退出。此外,脚本应检查目标目录是否存在,如果不存在,则应创建该目录。最后,脚本应该将文件从源目录复制到目标目录。

这是我目前的尝试:

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

任何帮助将不胜感激。提前致谢!

【问题讨论】:

  • 你有什么问题?会发生什么,您期望会发生什么?
  • 将您的代码粘贴到shellcheck.net(在顶部添加“she-bang”行,即#!/bin/bash。)祝您好运。

标签: linux


【解决方案1】:

检查参数的正确数量:Check number of arguments passed to a Bash script

if [ "$#" -ne 2 ]; then
    echo "Error: Too few arguments supplied"
    exit 1
fi

用于检查目录是否存在:Check if a directory exists in a shell script

if [ ! -d "$1" ]; then
    echo "Error: Directory $1 does not exist."
    exit 1
fi

用于在第二个参数上创建目录:How to use Bash to create a folder if it doesn't already exist?

mkdir -p $2

最后,将它们全部复制:

cp -r $1/* $2/

【讨论】:

    猜你喜欢
    • 2020-12-08
    • 2012-02-15
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多