1

I have a problem when i try to run a for loop in a for loop.

I try to make 24 files with ips with step of 10.

To explain more in the first file i need to have all ips that ends betwen 1-10 and second 11 to 20 and so on.

I try to use:

    for i in {1..240}
    do
    for r in {1..24}
    do
        if [ "$i" -le "$r0" ]
        then
            echo "4.2.2.$i" >> "server-$r"
        fi
    done
done

The error i recived is when i run bash -xv script_name:

script_name: line 5: [: : integer expression expected
+ for r in '{1..24}'
+ '[' 240 -le '' ']'
script_name: line 5: [: : integer expression expected
+ for r in '{1..24}'
+ '[' 240 -le '' ']'
script_name: line 5: [: : integer expression expected

The filenames are server-$r, ie server-1,server-2, so on until server-24

Any advice?

Thank you.

2 Answers 2

3

The error is in the following:

if [ "$i" -le "$r0" ]

You don't have a variable r0, which causes the error. Say:

if [ "$i" -le "${r}0" ]

instead so as to avoid ambiguity.


Since you wanted to multiply the number by 10, you could write it mathematically as:

if [ "$i" -le $((r*10)) ]

or even

(( i <= r*10 ))
Sign up to request clarification or add additional context in comments.

2 Comments

The $((...)) is redundant inside ((...)): (( i <= r*10 )).
It's woking, but in the files i found progresiv all the ips, not just those 10 ips. in 1st are 1 to 10 in secod 1 to 20 and the final 1 to 240. How can i limit just 10 of the ips.
1

This isn't the bash-native / idiomatic way to do things anyhow.

for ((i=1; i<=240; i++)); do
    for ((r=1; r<=24; r++)); do
        if (( i <= (r * 10) )); then
            echo "4.2.2.$i"
        fi
    done >"server-$r"
done

Opening the server-$r file only once per value of $r is far more efficient than opening it for each individual echo (otherwise you're opening and closing the file every time it needs to be accessed), and using expansions such as {1..3} is inflexible (only supported with literal numbers, not variables) and expands to a wordlist that gets iterated over, thus using more memory than using a C-style for loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.