Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script, comparing numbers

Tags:

bash

shell

ubuntu

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 :-).

like image 206
tobi Avatar asked Apr 15 '14 09:04

tobi


People also ask

How do I compare two variables in bash?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.

What is $1 and $2 in bash?

$0 is the name of the script itself (script.sh) $1 is the first argument (filename1) $2 is the second argument (dir1)


1 Answers

#!/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
like image 167
Adrian Frühwirth Avatar answered Oct 14 '22 12:10

Adrian Frühwirth