0

I have a for loop like this:

    for i in {1..$number}
    do
    echo "Chose a file"
    git apply $(zenity --file-selection --file-filter='patch files (patch) | *.patch' --title="Select your patch file")
done

The purpose of the code is for the user to input a file, and it will patch that file. It is supposed to do it multiple times, but it only does it once. I will not post the output, since the error is from the "git apply" and not the for i in {1..$number"} I can't figure out what is wrong. Can anyone help?

  • What is the value of `$number`, where does it come from? – Gaël J Dec 26 '21 at 20:27
  • @Gaël J The value of $number varies. I have a "read number" line that asks for the amount of patches. I am also having a problem with that, but I might ask it later. In my test, I set $number to 5. –  Dec 26 '21 at 20:31
  • fix your title. Is weird not wierd. – JRichardsz Dec 26 '21 at 20:51
  • I assume you are using `bash`; brace expansion happens before parameter expansion, so the value of `$number` isn't known yet. – chepner Dec 26 '21 at 21:17

1 Answers1

-1

For-in loop with variable is something complex, not intuitive at all:

for i in $( eval echo {0..$number} )
do
    echo "Chose a file"
done

enter image description here

source:

https://stackoverflow.com/a/17181832/3957754

If you want something more readable use this:

for (( c=1; c<=$number; c++ ))
do  
   echo "Welcome $c times"
done

enter image description here

In this you will find more loop samples

https://www.cyberciti.biz/faq/bash-for-loop/

JRichardsz
  • 14,356
  • 6
  • 59
  • 94
  • There's no reason to use `eval` in place of the C-style `for` loop. – chepner Dec 26 '21 at 21:18
  • But the question is related to the use of variable in the **for-in** style – JRichardsz Dec 26 '21 at 21:20
  • And the solution is to *not* use the basic `for` loop. There's really no reason to *ever* use the basic `for` loop with brace expansions. Either the C-style loop is available, and you can iterate without having to create a potentially sizable list in memory before iterating, or the C-style loop is *not* available, in which case brace expansion probably isn't either and you need to use a `while` loop anyway. – chepner Dec 26 '21 at 21:28