简体   繁体   中英

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

#!/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...

./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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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