9

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?

1

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

I tried that command but got this error: ./copymany.sh: line 14: ${seq 1 15}: bad substitution
I removed all of my code and literally just pasted your command, and it says "cp: missing destination file operand after '1' (and every other number to 15"
I used parentheses (()); you initial code shows {} braces. You didn't show how $INPUT was set, so I couldn't set it, but the error messages imply that your cp command is seeing only the number, which in turn means that $INPUT is not set. You need to add that to your code. Also, it would be a good idea to enclose the file names in double quotes. It shouldn't matter since you presumably don't have spaces etc in the names, but it is easily arguably better to be safe than sorry.
2

Using a C-style for loop :

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

5 Comments

Awesome, thank you very much. Is there a way to modify that to let it take letters (A-Z) as well as numbers?
Also, why does this work if I enter it in the command line, but if I try to run it as a script called copymany.sh it says "cp: cannot stat `': No such file or directory"
for i in {a..z}; do ...
You have to do in your script : cd /path/to/dir/where/file_is
I like bash arithmetic evaluation a lot. One can even use C++ style prefix increment in for-loops ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.