Linux – Use shell scripts to make multiple copies of files

Use shell scripts to make multiple copies of files… here is a solution to the problem.

Use shell scripts to make multiple copies of files

I’m trying to write a small shell script to make multiple copies of a file. I can take the file name as input, but not the number of copies. This is what I wrote. But I can’t pass the NUMBER variable to the for loop.

echo -n "Enter filename: "
read FILENAME
echo -n "Number of copies to be made: "
read NUMBER
for i in {2..$NUMBER}
do
cp -f $FILENAME ${FILENAME%%.*}"_"$i.csv
done

Solution

Unfortunately, it doesn’t work that way. bash performs brace expansion before parameter expansion, so your curly braces will be expanded before evaluating $NUMBER. See also Bash Pitfall #33, which explains the problem.

One way to do this with your code is:

for i in $(eval echo {2..$NUMBER})
do
# ...
done

Or, shorter:

for i in $(seq 2 $NUMBER)
# ...

(Thanks, Glenn Jack Mann!)


Note that usually variables should be quoted. What if your filename is foo bar? Then your cp -f will copy foo and bar because the parameters are separated by spaces.

So, do something like this:

cp -f "$FILENAME" "${FILENAME%%.*}_${i}.csv"

While it may not matter if your file doesn’t contain spaces, referencing variables is something you should do automatically to prevent any surprises in the future.

Related Problems and Solutions