Writing a bash for-loop with a variable top-end

后端 未结 3 1189
萌比男神i
萌比男神i 2021-01-04 01:00

I frequently write for-loops in bash with the well-known syntax:

for i in {1..10}  [...]

Now, I\'m trying to write one where the top is def

相关标签:
3条回答
  • 2021-01-04 01:11

    You can use for loop like this to iterate with a variable $TOP:

    for ((i=1; i<=$TOP; i++))
    do
       echo $i
       # rest of your code
    done
    
    0 讨论(0)
  • 2021-01-04 01:12

    If you have a gnu system, you can use seq to generate various sequences, including this.

    for i in $(seq $TOP); do
        ...
    done
    
    0 讨论(0)
  • 2021-01-04 01:36

    Answer is partly there : see Example 11-12. A C-style for loop.

    Here is a summary from there, but be aware the final answer to your question depends on your bash interpreter (/bin/bash --version):

    # Standard syntax.
    for a in 1 2 3 4 5 6 7 8 9 10
    
    # Using "seq" ...
    for a in `seq 10`
    
    # Using brace expansion ...
    # Bash, version 3+.
    for a in {1..10}
    
    # Using C-like syntax.
    LIMIT=10
    for ((a=1; a <= LIMIT ; a++))  # Double parentheses, and "LIMIT" with no "$".
    
    # another example
    lines=$(cat $file_name | wc -l)
    for i in `seq 1 "$lines"`
    
    # An another more advanced example: looping up to the last element count of an array :
    for element in $(seq 1 ${#my_array[@]})
    
    0 讨论(0)
提交回复
热议问题