如何在shell脚本中将多个文件作为参数传递给函数



当多个文件作为参数以Regex形式发送时,如何将文件逐一复制到目标路径

copyFiles()  
{  
for file in $@  
do  
echo "File:" $files  
cp -f $file $TARGET_DIR   #how to copy files one by one to destination path
done  
}  
TARGET_DIR=destinationPath/Dir  
copyFiles sourcePathFiles/filename.*         #How to handle this in copyFiles()

基本正确,但是:

(1)您正在使用$@。如果传递的参数包含空格,则会中断。你应该使用"$@"

(2)在echo命令中,您指的是未设置的变量files。在你的cp中,你正确地引用了file

实际上,你的函数可以简化一点:

copyFiles()  
{
cp -vf "$@" $TARGET_DIR
}

使用-v可以避免使用echo

最新更新