0

I am new to bash scripting and would like to call a program 22 times. for 22 different files.

file names look something like this: filename_chr1_test filename_chr2_test filename_chr3_test ... filename_chr22_test

this is my for loop so far:

#!/bin/bash

for chr_num in {1:22}:
    do
       /path/to/plink --file filename_chr$chr_num_test --exampletest
    done

For some reason I'm getting an error back. I'm not exactly sure why. Can someone help me debug?

Thanks for your help!!

5
  • you have to post a clear question. Commented Apr 14, 2017 at 17:10
  • 1: for chr_num in {1..22} 2: Use ${chr_num} instead of $chr_num so that the interpreter will work correctly.. Commented Apr 14, 2017 at 17:11
  • @BradBales Hi brad. OH! Do I include ( ) around chr_num in the for loop statement AND in where I list the file name? Commented Apr 14, 2017 at 17:12
  • Oh, and it's "#!/bin/bash" Commented Apr 14, 2017 at 17:13
  • 2
    Please take a look: shellcheck.net Commented Apr 14, 2017 at 17:13

2 Answers 2

3

I suggest:

#!/bin/bash

for chr_num in {1..22}; do
  /path/to/plink --file filename_chr${chr_num}_test --exampletest
done
Sign up to request clarification or add additional context in comments.

Comments

3

Don't use brace expansion; use a C-style for loop:

for((i=1;i<=22;i++)); do
  /path/to/plink --file filename_chr${chr_num}_test --exampletest
done

This doesn't require the entire sequence to be expanded in memory at once (not a big deal for a short sequence).

3 Comments

I suggest to replace three i by chr_num or one chr_num by i.
Thanks @chepner - what is the motivation to use a C-style loop over brace expansion?
@Sheila The main benefit is that you don't have to hard code the number. You can do n=42; for ((i=1; i<=n; i++)) but you can't do for i in {1..n} . It's also more efficient once you start counting to thousands or millions

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.