0

I'm trying to write a for loop in bash so that I can iterate numbers from 1 to a number larger than 10. In the cases where the number has only one digit, a zero should be added to its left (as in 01).

The solution I found for that was this:

for i in 0{1..9} {10..43}; do echo "stuff$i.txt" done 

This works, but I wanted to have the upper limit as a variable, so I tried this:

max_test=43 for i in 0{1..9} {10..$max_test}; do echo "stuff$i.txt" done 

When running this, the script prints out

stuff01.txt

stuff02.txt

...

stuff09.txt

stuff{10..43}.txt

I found this answer, but in my situation I'd need 2 for loops due to that one-digit number condition. What is the best way to do what I want?

Thank you in advance

3
  • How is this a duplicate question? My issue is not having a variable as the top limit of an iteration, it is doing so given the context explained in the question. Commented Apr 11, 2019 at 10:42
  • 1
    I saw your edit, the -w ensured the 0 padding so you can use simply one $(seq -w 1 "$max_test"). Commented Apr 11, 2019 at 10:58
  • 1
    First, {01..43} will get you zero-padded two-digit numbers, at least in bash 4 and up (for example, try: echo {0005..12}). Second, you know by now that brace expansion is evaluated before anything else (as stated by the second paragraph of the "EXPANSION" section of the bash man page). You can get around this using eval (for example, eval "echo {05..$n}") or arithmetic (for ((i=5;i<=n;i++)); do printf '%02d ' $i; done). Commented Apr 11, 2019 at 11:37

1 Answer 1

1

You can't use a variable in brace expansion because brace expansion is done before variable expansion. You can use seq for example:

max=43 seq -w 1 "$max" 
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this isn't a bash answer, and the seq utility is not guaranteed to be installed on every system that includes bash.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.