1

This works as intended:

for rcount in {0..10}; do
    echo "${rcount}"
done

But I have a variable that I want to use as a loop range:

var1=10

These don't work:

Trial 1:

for rcount in {0..var1}; do
    echo "${rcount}"
done

Trial 2:

for rcount in {0..${var1}}; do
    echo "${rcount}"
done

How can I do this?

maximusdooku
  • 5,242
  • 10
  • 54
  • 94
  • 1
    This is [BashPitfalls #33](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.7B1...24n.7D). – Charles Duffy Dec 06 '18 at 03:59
  • use $() instead of ${}, `for rcount in $(seq 0 $var); do echo $rcount; done` instead of double dots `..` you can use the command `seq`. – Ibn Rushd Dec 06 '18 at 11:09
  • @IbnRushd, `seq` isn't POSIX-standardized *or* part of bash. It's not guaranteed to be available or to have any particular behavior when it *is*, and since it's an external command, it costs a lot more to start up than using internal shell math. – Charles Duffy Dec 06 '18 at 16:51
  • @IbnRushd, ...compare the performance of `time { counter=0; for (( lcount=0; lcount<50; lcount++)); do for (( rcount=0; rcount<50; rcount++)); do ((++counter)); done; done; echo "$counter"; }` to the performance of `time { counter=0; for lcount in $(seq 50); do for rcount in $(seq 50); do ((++counter)); done; done; echo "$counter"; }`. – Charles Duffy Dec 06 '18 at 16:54
  • @CharlesDuffy I feel like one should keep an answer as close as possible to the OP (intiuitive) attempt to solve. Yes, it's not POSIX, slow and kinda outside the scope of bash programming. But I'd rather have OP follow their own journey. It hasn't helped me. I would read all Bash Pitfalls and feel really down. I'd rather give OP a sense of you were close. – Ibn Rushd Dec 07 '18 at 10:41
  • I can appreciate that *if and only if* it's coupled with an understanding of why what they attempted didn't work, why the thing that's close *does* work, *how* that thing works, and what limitations and constraints fall out from the mechanism. Otherwise, we're just teaching antipatterns -- practices that aren't robust across the full range of scripts one may be called to write -- without even providing a reasonable warning about the limitations embedded therein. – Charles Duffy Dec 07 '18 at 15:40
  • Our industry has an ongoing crisis caused by technology being built by people who don't fully understand the context, idioms and behaviors of the tools they use -- bad enough that while I build a security-critical product, I haven't been able to consistently find engineers who can write secure code and recognize antipatterns when they see them; I'm needing to hire folks and train them after they start. One can't ensure security without first understanding and ensuring *correctness* -- part of that is knowing how the idioms one is using work under-the-hood, what their side effects are, etc. – Charles Duffy Dec 07 '18 at 15:45

0 Answers0