Home > Mobile >  editing loop in bash script to only run over 3 files
editing loop in bash script to only run over 3 files

Time:08-12

I havent really used bash before so I'm unsure how to manipulate code to my use.

I have the following:

cmd=""
for i in {1..22}
do
  bgenix -g file1${i}_t.bgen -incl-range list.txt > c${i}.bgen
  cmd=$cmd"c${i}.bgen "
done

however I only need to do this to 3 out of the 22 files.

Am I able to use something like the code below

for i in {1, 3, 17}

to select only these files instead?

Thank you!

CodePudding user response:

Removing the curly braces as follows should work:

for 1 3 17 ; do
    bgenix -g file1${i}_t.bgen -incl-range list.txt > c${i}.bgen
    cmd=$cmd"c${i}.bgen "
done

CodePudding user response:

Since you say you're new to bash, I'll also just point you to a slight side-issue that I spotted.

By default, the bash interpreter treats spaces as field separators. So if there's a space character in your cmd variable, and you reuse it, bash will do word-splitting which might give you some unexpected results. In order to retain and handle the space character, you'll have to be carefully to use enclosing double quotes over the whole assigned part.

Actually it's good practice to do this even when a variable doesn't yet contain spaces (or any other unknown, future field separator). So,

cmd=""
for i in 1 3 17
do
  bgenix -g file1"${i}"_t.bgen -incl-range list.txt > c"${i}".bgen
  cmd="${cmd}c${i}.bgen "
done

You might ask, why double quote the "${i}"? It's all about good habits.

Also, your case demonstrates exactly why curly braces are used. Without them bash would be looking for a variable called $cmdc! Good luck.

  • Related