首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >cp { fileList }* dir_name,其中fileList包含文件和目录

cp { fileList }* dir_name,其中fileList包含文件和目录
EN

Stack Overflow用户
提问于 2015-01-28 23:17:54
回答 1查看 70关注 0票数 0

因此,我正在编写一个赋值,它要求我在bash中编写一个shell脚本,它将使用2个现有目录名作为其前2个参数,并将2的内容复制到第3个参数指定的目录中。如果这两个目录只包含常规文件,但是如果它们包含任何目录,我就会遇到一个"cp: contain‘{所有文件名}’“错误。如何修复此错误?

这是我的整个剧本。任何帮助都将不胜感激。

代码语言:javascript
复制
#! /bin/bash

shopt -s expand_aliases
alias error='echo "usage: cpdirs.sh source_directory1 source_directory2 dest_directory"'

if [ $# -ne 3 ]
then
    error
    exit
fi

if [ -d $1 -a -d $2 ]
then
    ls1=`ls "$1"`
    ls2=`ls "$2"`
else
    error
    exit
fi

CD=`pwd`

if [ ! -d "$3" ]
then
    mkdir "$3"
fi

cd "$3"
thrd=`pwd`
cd "$CD"
cd "$1"

ls1=${ls1//
/ }

if [ -n "$ls1" ]
then
    cp -R "$ls1" "$thrd"
fi

cd "$CD"
cd "$2"

ls2=${ls2//
/ }

if [ -n "$ls2" ]
then
    cp -R "$ls2" "$thrd"
fi
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-28 23:45:14

要复制的单个文件需要作为单个参数传递给cp。您要在单个参数中传递一个空格分隔的文件名列表 --这意味着cp试图找到一个文件名,该文件的名称是将目录中的所有单独文件名连接在一起的结果(因为这些名称由ls处理)。

简短的回答:不要这样做。 programatically,特别是don't try to put multiple arguments in a single scalar variable。如果要在变量中存储多个文件名,请使用数组:

代码语言:javascript
复制
filenames=( * )

...expanded为:

代码语言:javascript
复制
cp -- "${filenames[@]}" /path/to/destination
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28204281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档