In the following bash loop, I want to redirect content into a variable filename.

for i in {1..22};do echo $i > $i_output.txt; done

Unfortunately the files are not created. What I originally want to do is to grep on chromosomes in a file and create a file per chromosome. But this is less testable:

for i in {1..22}; grep -E "[a-z]+[0-9]+\t$i\t" rawdata.txt > $i_chr.txt;done

How can we redirect output in a for loop to a variable filename?

1 Answer 1


You have to use curly braces or double-quotes around your variable name. The following loop works.
Otherwise the shell will try to expand the variable $i_output.

for i in {1..22};do echo ${i} > ${i}_output.txt; done
for i in {1..22};do echo "$i" > "$i"_output.txt; done

In your case curly braces might be the better choise, as you already use double-quotes and your shell will have a problem with sorting out the inner and outer double-quotes.

for i in {1..22}; grep -E "[a-z]+[0-9]+\t${i}\t" rawdata.txt > ${i}_chr.txt;done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.