简体   繁体   English

从命令行参数使用bash脚本复制多个文件?

[英]Copy multiple files with bash script from command line arguments?

I want to create a script that allows me to enter multiple filenames from the command line, and have the script copy those files to another directory. 我想创建一个脚本,该脚本允许我从命令行输入多个文件名,并使该脚本将这些文件复制到另一个目录。 This is what I am trying but I keep getting an error of 这是我正在尝试的方法,但我不断收到错误消息

line 10: binary operator expected 第10行:期望使用二进制运算符

#!/bin/bash

DIRECTORY=/.test_files
FILE=$*
if [ -e $DIRECTORY/$FILE ]; then
        echo "File already exists"
else
        cp $FILE $DIRECTORY
fi

So if the script was named copfiles.sh, I am writing... 因此,如果脚本名为copfiles.sh,我正在写...

./copyfiles.sh doc1.txt doc2.txt

It will move the files, but if they already exist, it won't read the error message. 它将移动文件,但是如果它们已经存在,它将不会读取错误消息。

Also I get the "line 10: binary operator expected" error regardless of it the files are there or not. 另外,无论文件是否存在,我都会收到“第10行:期望的二进制运算符”错误。 Can anyone tell me what I am doing wrong? 谁能告诉我我在做什么错?

As a possible problem, if you had a filename with a space or had multiple arguments $* would have spaces in it so [ -e $DIR/$FILE ] will expand to have lots of words, like [ -e /.test_files/First word and more ] and -e expects just 1 word after it. 可能的问题是,如果文件名带有空格或多个参数$ *包含空格,则[ -e $DIR/$FILE ]将扩展为包含许多单词,例如[ -e /.test_files/First word and more ]-e期望后面仅一个单词。 Try putting it in quotes like 尝试将其放在诸如

if [ -e "$DIRECTORY/$FILE" ]

Of course, you may only want to store $1 in $FILE to get just the first argument. 当然,您可能只想将$ 1存储在$ FILE中以获取第一个参数。

To test all the arguments you want to loop over the arguments and test each with something like 要测试所有参数,您需要遍历参数并使用类似的方法测试每个参数

for FILE in "$@"; do
    if [ -e "$DIRECTORY/$FILE" ]; then
        echo "$FILE already exists"
    else
        cp "$FILE" $DIRECTORY
    fi
done

Using quotes around $@ to preserve spaces in the original arguments as well 在$ @周围也使用引号来保留原始参数中的空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM