0

I was using the following in my current script

for x in {07..10}

Trying to pass the start,end variables to the script using

for x in $(seq $1 $2)

Since the sequence starts from 07, and 07 is a file name that I want to read, I cant change the variable to 7, as it happens when using the sequence. Can you please point me in the right direction as I don't have much experience with bash.

Sushant
  • 324
  • 2
  • 14

1 Answers1

0

Use printf to get the number format you want:

for (( x=7; x<=10; x++ )); do
   str=$( printf "%02d" "$x" )
   echo filename${str}.txt
done

Results look like this:

$ for (( x=7; x<=10; x++ )); do str=$( printf "%02d" "$x" ); echo filename${str}.txt; done
filename07.txt
filename08.txt
filename09.txt
filename10.txt

Works with variables, too:

$ start="07"
$ end="10"
$ for (( x=$start; x<=$end; x++ )); do str=$( printf "%02d" "$x" ); echo filename${str}.txt; done
filename07.txt
filename08.txt
filename09.txt
filename10.txt
Jack
  • 5,801
  • 1
  • 15
  • 20
  • 1
    Use `printf -v str "%02d" "$x"` to save a fork. – chepner Jul 06 '17 at 14:08
  • I have a dishwasher, so I don't mind using an extra fork here and there. – Jack Jul 06 '17 at 14:15
  • Being sloppy in your own code is excusable, but in the absence of any indication that the OP would like for the solution to be slightly inefficient, you should probably do your best to avoid unnecessary overhead inside a loop. – tripleee Jul 07 '17 at 03:24
  • If efficiency is that important, don't use bash. – Jack Jul 07 '17 at 13:33