2010-11-09 19 views

risposta

8

Questo è una specie di kludge, usa -eq per qualcosa di diverso da ciò a cui era destinato, ma controlla un intero, se non trova un int restituisce sia un errore che puoi lanciare a/dev/null e un valore di falso.

read input 
if [ $input -eq $input 2>/dev/null ] 
then 
    echo "$input is an integer" 
else 
    echo "$input is not an integer" 
fi 
+1

Presuppone che/dev/null esista – Xofo

+1

Presuppone anche che l'argomento non sia vuoto –

21

Un modo è verificare se contiene caratteri non numerici. Sostituisci tutti i caratteri numerici con nulla e controlla la lunghezza - se c'è lunghezza ci sono caratteri non numerici.

if [[ -n ${input//[0-9]/} ]]; then 
    echo "Contains letters!" 
fi 

Un altro approccio è verificare se la variabile, valutata in contesto aritmetico, è uguale a se stessa. Questo è specifico bash

if [[ $((foo)) != $foo ]]; then 
    echo "Not just a number!" 
fi 
+0

Pulito ed elegante – Xofo

+0

risposta dolce e semplice, grazie! – Felipe

+0

Se l'input è 5b, ad esempio, fallirà il controllo. –

3

BASH FAQ entry #54

+0

Questa domanda frequente è intitolata "Come posso sapere se una variabile contiene un numero valido?" - Fornisce un sacco di possibili modi per identificare. –

7

È possibile verificare utilizzando espressioni regolari

if ! [[ "$yournumber" =~ ^[0-9]+$ ]] ; 
then exec >&2; echo "error: Not a number"; exit 1 
fi 
+0

Questo è il più letterale, e quindi più facile da ricordare. –

0

Ecco un altro modo di farlo. Probabilmente è un po 'più elaborato del necessario nella maggior parte dei casi, ma gestirà anche i decimali. Ho scritto il codice qui sotto per ottenere il numero arrotondato. Controlla anche l'input numerico nel processo.

#--- getRound -- Gives number rounded to nearest integer ----------------------- 
    # usage: getRound <inputNumber> 
    # 
    # echos the rounded number 
    # Best to use it like: 
    #  roundedNumber=`getRound $Number` 
    #  check the return value ($?) and then process further 
    # 
    # Return Value: 
    #  2 - if <inputNumber> is not passed, or if more arguments are passed 
    #  3 - if <inputNumber> is not a positive number 
    #  0 - if <inputNumber> is successfully rounded 
    # 
    # Limitation: Cannot be used for negative numbers 
    #------------------------------------------------------------------------------- 
    getRound(){ 
     if [ $# -ne 1 ] 
     then 
      exit 2 
     fi 

     #--- Check if input is a number 
     Input=$1 
     AB=`echo A${Input}B | tr -d [:digit:] | tr -d '.'` 
     if [ "${AB}" != "AB" ] #--- Allow only '.' and digit 
     then 
      exit 3 
     fi 
     DOTorNone=`echo ${Input} | tr -d [:digit:]` #--- Allow only one '.' 
     if [ "${DOTorNone}" != "" ] && [ "${DOTorNone}" != "." ] 
     then 
      exit 3 
     fi 

     echo $Input | awk '{print int($1+0.5)}' #--- Round to nearest integer 
    } 

    MyNumber=`getRound $1` 
    if [ $? -ne 0 ] 
    then 
     echo "Empty or invalid input passed" 
    else 
     echo "Rounded input: $MyNumber" 
    fi 
Problemi correlati