1

I'm trying to produce a rather simple bash script with a single for loop whose range should be passed when calling it.

This is what I have:

#!/bin/bash

for i in {$1..$2}
  do
    file=file_$i.txt
    echo $file
  done

which I call using: ./my_script.sh 01 06.

The output I'm after is:

file_01.txt
file_02.txt
file_03.txt
file_04.txt
file_05.txt
file_06.txt

(notice that there's a leading 0, this is important) but what I get with the above script is:

file_{01..20}.txt

What am I doing wrong?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gabriel
  • 40,504
  • 73
  • 230
  • 404
  • possible duplicate of [Range with leading zero in bash](http://stackoverflow.com/questions/13376396/range-with-leading-zero-in-bash) – timrau Jun 07 '15 at 14:42
  • possible duplicate of [How do I iterate over a range of numbers defined by variables in bash?](http://stackoverflow.com/questions/169511/how-do-i-iterate-over-a-range-of-numbers-defined-by-variables-in-bash) – zw324 Jun 07 '15 at 14:44
  • I don't think my question is a duplicate of neither of those posts. It's rather an amalgamation of the questions in both. Thanks for pointing me to them, I'll try to combine them into a single answer. – Gabriel Jun 07 '15 at 14:46
  • 1
    Do you want trailing or leading zeros? – Cyrus Jun 07 '15 at 15:31
  • Gah it's leading, thanks for bringing my attention to that @Cyrus! Corrected now. – Gabriel Jun 07 '15 at 15:32

1 Answers1

1

Combining the answers in the questions Range with leading zero in bash and How do I iterate over a range of numbers defined by variables in Bash? (thanks timrau & Ziyao Wei for pointing me to them) I got:

#!/bin/bash

for i in $(seq -w $1 $2)
  do
    file=file_$i.txt
    echo $file
  done

which outputs exactly what I needed.

Community
  • 1
  • 1
Gabriel
  • 40,504
  • 73
  • 230
  • 404