5

Is it possible to compare $ip_choice with a number without setting it before?

#!/bin/bash
ip_choice=999
while ! (( $ip_choice <= 233 ))
  do 
    read -p "Enter a valid IP (1-256): " ip_choice
  done

It work's like that - only I want to know if there is a more elegant possibility :-).

2 Answers 2

7
#!/bin/bash

while read -r -p "Enter a valid IP (1-256): " ip_choice; do
     (( ip_choice >= 1 && ip_choice <= 256 )) && break
done    
echo "${ip_choice}"

$ ./t.sh
Enter a valid IP (1-256): -1
Enter a valid IP (1-256): 0
Enter a valid IP (1-256): 257
Enter a valid IP (1-256): abc
Enter a valid IP (1-256): 20
20
Sign up to request clarification or add additional context in comments.

Comments

5

You could make use of until:

until ((ip_choice >=1 && ip_choice <= 256)); do
  read -p "Enter a valid IP (1-256): " ip_choice;
done

Quoting from help until:

until: until COMMANDS; do COMMANDS; done

Execute commands as long as a test does not succeed.

Expand and execute COMMANDS as long as the final command in the
`until' COMMANDS has an exit status which is not zero.

Exit Status:
Returns the status of the last command executed.

For example:

$ until ((ip_choice >=1 && ip_choice <= 256)); do
>   read -p "Enter a valid IP (1-256): " ip_choice;
> done
Enter a valid IP (1-256): 0
Enter a valid IP (1-256): 298
Enter a valid IP (1-256): 242

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.