简体   繁体   English

Bash脚本,比较数字

[英]Bash script, comparing numbers

Is it possible to compare $ip_choice with a number without setting it before? 是否可以将$ip_choice与之前设置的数字进行比较?

#!/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 :-). 它的工作就是这样 - 只有我想知道是否有更优雅的可能性:-)。

#!/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

You could make use of until : 您可以使用until

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

Quoting from help until : help until引用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM