Domanda

Come posso verificare se una variabile è vuota in Bash?

È stato utile?

Soluzione

In bash, almeno le seguenti prove comando se $ var è vuoto :

if [[ -z "$var" ]]; then
   #do what you want
fi

Il man test comando è tuo amico.

Altri suggerimenti

Supponendo bash:

var=""

if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi

Ho visto anche

if [ "x$variable" = "x" ]; then ...

che è ovviamente molto robusto e guscio indipendente.

Inoltre, v'è una differenza tra "vuoto" e "disinserito". Vedere Come dire se una stringa non è definita in uno script di shell bash? .

if [ ${foo:+1} ]
then
    echo "yes"
fi

stampe yes se è impostata la variabile. ${foo:+1} restituirà 1 quando si imposta la variabile, altrimenti restituirà stringa vuota.

if [[ "$variable" == "" ]] ...
[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}

Questo restituirà true se una variabile è impostata o impostata alla stringa vuota ( "").

if [ -z "$MyVar" ]
then
   echo "The variable MyVar has nothing in it."
elif ! [ -z "$MyVar" ]
then
   echo "The variable MyVar has something in it."
fi

IL domanda chiede come verificare se una variabile è una stringa vuota e le migliori risposte sono già state date per questo.
Ma sono arrivato qui dopo un periodo passato a programmare in php e quello che stavo effettivamente cercando era un controllo come il funzione vuota in php lavorando in una shell bash.
Dopo aver letto le risposte mi sono reso conto che non stavo pensando correttamente a bash, ma comunque in quel momento a una funzione simile vuoto in php sarebbe stato davvero utile nel mio codice bash.
Poiché penso che questo possa succedere ad altri, ho deciso di convertire la funzione php vuota in bash

Secondo il manuale php:
una variabile è considerata vuota se non esiste o se il suo valore è uno dei seguenti:

  • "" (una stringa vuota)
  • 0 (0 come numero intero)
  • 0.0 (0 come float)
  • "0" (0 come stringa)
  • un array vuoto
  • una variabile dichiarata, ma senza valore

Naturalmente il nullo E falso i casi non possono essere convertiti in bash, quindi vengono omessi.

function empty
{
    local var="$1"

    # Return true if:
    # 1.    var is a null string ("" as empty string)
    # 2.    a non set variable is passed
    # 3.    a declared variable or array but without a value is passed
    # 4.    an empty array is passed
    if test -z "$var"
    then
        [[ $( echo "1" ) ]]
        return

    # Return true if var is zero (0 as an integer or "0" as a string)
    elif [ "$var" == 0 2> /dev/null ]
    then
        [[ $( echo "1" ) ]]
        return

    # Return true if var is 0.0 (0 as a float)
    elif [ "$var" == 0.0 2> /dev/null ]
    then
        [[ $( echo "1" ) ]]
        return
    fi

    [[ $( echo "" ) ]]
}



Esempio di utilizzo:

if empty "${var}"
    then
        echo "empty"
    else
        echo "not empty"
fi



Dimostrazione:
il seguente frammento:

#!/bin/bash

vars=(
    ""
    0
    0.0
    "0"
    1
    "string"
    " "
)

for (( i=0; i<${#vars[@]}; i++ ))
do
    var="${vars[$i]}"

    if empty "${var}"
        then
            what="empty"
        else
            what="not empty"
    fi
    echo "VAR \"$var\" is $what"
done

exit

uscite:

VAR "" is empty
VAR "0" is empty
VAR "0.0" is empty
VAR "0" is empty
VAR "1" is not empty
VAR "string" is not empty
VAR " " is not empty

Detto che in una logica bash i segni di spunta sullo zero in questa funzione possono causare problemi collaterali, chiunque utilizzi questa funzione dovrebbe valutare questo rischio e magari decidere di tagliare quei segni di spunta lasciando solo il primo.

Si consiglia di distinguere tra le variabili non impostate e le variabili che sono impostate e vuoti:

is_empty() {
    local var_name="$1"
    local var_value="${!var_name}"
    if [[ -v "$var_name" ]]; then
       if [[ -n "$var_value" ]]; then
         echo "set and non-empty"
       else
         echo "set and empty"
       fi
    else
       echo "unset"
    fi
}

str="foo"
empty=""
is_empty str
is_empty empty
is_empty none

Risultato:

set and non-empty
set and empty
unset

A proposito, mi consiglia di utilizzare set -u che causerà un errore durante la lettura di variabili non impostata, questo può salvare da disastri come

rm -rf $dir

Si può leggere su questo e altri best practice per una "rigorosa modalità" qui .

Per verificare se la variabile v non è impostata

if [ "$v" == "" ]; then
   echo "v not set"
fi
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top