Tom Bennett
Tom Bennett

Reputation: 179

creating multiple copies of a file in bash with a script

I am starting to learn how to use bash shell commands and scripting in Linux.

I want to create a script that will take a source file, and create a chosen number of named copies.

for example, I have the source as testFile, and I choose 15 copies, so it creates testFile1, 2, 3 ... 14, 15 in the same location.

To try and achieve this I have tried to make the following command:

for LABEL in {$X..$Y}; do cp $INPUT $INPUT$LABEL; done

However, instead of creating files from X to Y, it makes just one file with (for example) {1..5} appended instead of files 1, 2, 3, 4 and 5

How can I change it so it properly uses the variable as a number for the loop?

Upvotes: 9

Views: 10042

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753930

The brace expansion mechanism is a bit limited; it doesn't work with variables, only literals.

For what you want, you probably have the seq command, and could write:

INPUT=testFile
for num in $(seq 1 15)
do
    cp "$INPUT" "$INPUT$num"
done

Upvotes: 6

Gilles Quénot
Gilles Quénot

Reputation: 185161

Using a C-style for loop :

$ x=0 y=15
$ for ((i=x; i<=y; i++)); do cp "$INPUT" "$INPUT$i"; done

Upvotes: 2

Related Questions