0

I have a simple bash for loop and am trying to execute a command inside of it. The loop is so I can execute different file names.

the files are:

crystal0_cmin.pdb
crystal1_cmin.pdb
.
. 
.

the loop is:

for ((i=0;i<=10;i++))
do
cp Files/crystal$i_cmin.pdb Energy/
cp Files/crystal$i_cmin.psf Energy/
done

The problem is that I always get the following error message:

cp: cannot stat `Files/crystal.pdb': No such file or directory
cp: cannot stat `Files/crystal.psf': No such file or directory

but I never specify the files crystal.pdb and crystal.psf. It just ignores the $i extension for all i. That is, none of the files get copied.

Does anyone know how I can fix this.

Thanks!

1
  • 2
    It is easier to do: cp Files/crystal{0..10}_cmin.p{db,sf} Energy Commented Sep 14, 2012 at 20:56

2 Answers 2

6

The problem is that bash is interpreting $i_cmin as a variable. To fix it, use braces to tell bash that $i is a variable and should be interpreted as such:

cp Files/crystal${i}_cmin.pdb Energy/
cp Files/crystal${i}_cmin.psf Energy/
Sign up to request clarification or add additional context in comments.

Comments

2

The immediate fix is to use braces as suggested by Adam to limit the parameter name to i:

for ((i=0; i<=10; i++)); do
    cp Files/crystal${i}_cmin.pdb Energy/
    cp Files/crystal${i}_cmin.psf Energy/
done

The next step is to realize that you don't need to use a C-style for-loop to iterate over generated file names; you can use brace expansion to iterate over the desired files directly (this is the half-way point between your loop and William's comment:

for f in Files/crystal{0..10}_cmin.p{db,sf}; do
    cp "$f" Energy/
done

The last step is to realize you don't need a for-loop at all, because the list of files generated by the brace expansion can be used as the file list passed to cp directly (William's comment):

cp Files/crystal{0..10}_cmin.p{db,sf} Energy/

Comments

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.