Bash脚本,比较数字

时间:2014-04-15 09:22:55

标签: bash shell ubuntu

是否可以在不设置之前将$ip_choice与数字进行比较?

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

它就像那样 - 只有我想知道是否有更优雅的可能性: - )。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:5)

您可以使用until

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

引自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.

例如:

$ 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