web-dev-qa-db-fra.com

Script shell: options -z et -n avec if

J'ai un script Shell où nous avons les lignes suivantes if [ -z "$xyz" ] et if [ -n "$abc" ], mais je ne sais pas quel est leur but. Quelqu'un peut-il expliquer?

70
user3173953

Vous pouvez trouver une référence très agréable pour les opérateurs de bash ici . Si vous utilisez un autre Shell, recherchez simplement <my Shell> operators et vous trouverez tout ce dont vous avez besoin. Dans votre cas particulier, vous utilisez:

-n
   string is not null.

-z
  string is null, that is, has zero length

Pour illustrer:

$ foo="bar";
$ [ -n "$foo" ] && echo "foo is not null"
foo is not null
$ [ -z "$foo" ] && echo "foo is null"
$ foo="";
$ [ -n "$foo" ] && echo "foo is not null"
$ [ -z "$foo" ] && echo "foo is null"
foo is null
84
terdon

man test ou man [ vous donnera toutes les options pour tester la commande. Dans ce cas, -n teste pour voir si le contenu de $ abc a une longueur non nulle et -z teste pour voir si le contenu de $ xyz est une chaîne de longueur nulle.

4
doneal24

Pour étendre réponse de terdon , j'ai trouvé que nix/Linux - Opérateurs de base Shell sur Tutorials Point inclut également les opérateurs liés aux fichiers (ainsi que d'autres opérateurs utiles).

-b file     Checks if file is a block special file; if yes, then the condition becomes true.    [ -b $file ] is false.
-c file     Checks if file is a character special file; if yes, then the condition becomes true.    [ -c $file ] is false.
-d file     Checks if file is a directory; if yes, then the condition becomes true.     [ -d $file ] is not true.
-f file     Checks if file is an ordinary file as opposed to a directory or special file; if yes, then the condition becomes true.  [ -f $file ] is true.
-g file     Checks if file has its set group ID (SGID) bit set; if yes, then the condition becomes true.    [ -g $file ] is false.
-k file     Checks if file has its sticky bit set; if yes, then the condition becomes true.     [ -k $file ] is false.
-p file     Checks if file is a named pipe; if yes, then the condition becomes true.    [ -p $file ] is false.
-t file     Checks if file descriptor is open and associated with a terminal; if yes, then the condition becomes true.  [ -t $file ] is false.
-u file     Checks if file has its Set User ID (SUID) bit set; if yes, then the condition becomes true.     [ -u $file ] is false.
-r file     Checks if file is readable; if yes, then the condition becomes true.    [ -r $file ] is true.
-w file     Checks if file is writable; if yes, then the condition becomes true.    [ -w $file ] is true.
-x file     Checks if file is executable; if yes, then the condition becomes true.  [ -x $file ] is true.
-s file     Checks if file has size greater than 0; if yes, then condition becomes true.    [ -s $file ] is true.
-e file     Checks if file exists; is true even if file is a directory but exists.  [ -e $file ] is true.
2
JDQ