shell - Comment vérifier si une variable est définie dans Bash

Mots clés : bashshellvariablesbash

meilleur 5 Réponses shell - Comment vérifier si une variable est définie dans Bash

vote vote

92

if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi 
if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fi 
vote vote

86

if [ -n "$1" ] 
if [ -n "$1" ]; then   echo "You supplied the first parameter!" else   echo "First parameter not supplied." fi 
vote vote

80

+--------------------+----------------------+-----------------+-----------------+ |   Expression       |       parameter      |     parameter   |    parameter    | |   in script:       |   Set and Not Null   |   Set But Null  |      Unset      | +--------------------+----------------------+-----------------+-----------------+ | ${parameter:-word} | substitute parameter | substitute word | substitute word | | ${parameter-word}  | substitute parameter | substitute null | substitute word | | ${parameter:=word} | substitute parameter | assign word     | assign word     | | ${parameter=word}  | substitute parameter | substitute null | assign word     | | ${parameter:?word} | substitute parameter | error, exit     | error, exit     | | ${parameter?word}  | substitute parameter | substitute null | error, exit     | | ${parameter:+word} | substitute word      | substitute null | substitute null | | ${parameter+word}  | substitute word      | substitute word | substitute null | +--------------------+----------------------+-----------------+-----------------+ 
+--------------------+----------------------+-----------------+-----------------+ |   Expression       |  FOO="world"         |     FOO=""      |    unset FOO    | |   in script:       |  (Set and Not Null)  |  (Set But Null) |     (Unset)     | +--------------------+----------------------+-----------------+-----------------+ | ${FOO:-hello}      | world                | hello           | hello           | | ${FOO-hello}       | world                | ""              | hello           | | ${FOO:=hello}      | world                | FOO=hello       | FOO=hello       | | ${FOO=hello}       | world                | ""              | FOO=hello       | | ${FOO:?hello}      | world                | error, exit     | error, exit     | | ${FOO?hello}       | world                | ""              | error, exit     | | ${FOO:+hello}      | hello                | ""              | ""              | | ${FOO+hello}       | hello                | hello           | ""              | +--------------------+----------------------+-----------------+-----------------+ 
vote vote

64

[[ -v foo ]]; echo $? # 1  foo=bar [[ -v foo ]]; echo $? # 0  foo="" [[ -v foo ]]; echo $? # 0 
vote vote

50

if [ -z "$1" ] 

Questions similaires