GNU/Linux >> LINUX-Kenntnisse >  >> Linux

Warum funktioniert die Variablenerweiterung ohne $ in Ausdrücken?

#!/bin/bash

VALUE=10

if [[ VALUE -eq 10 ]]
then
    echo "Yes"
fi

Zu meiner Überraschung gibt dies „Ja“ aus. Ich hätte erwartet, dass es [[ $VALUE -eq 10 ]] erfordert . Ich habe die CONDITIONAL EXPRESSIONS gescannt Abschnitt von man bash , aber ich habe nichts gefunden, um dieses Verhalten zu erklären.

Akzeptierte Antwort:

[[ ist ein bash-reserviertes Wort, daher werden spezielle Erweiterungsregeln wie arithmetische Erweiterung angewendet, nicht wie im Fall von [ . Auch arithmetischer Binäroperator -eq wird genutzt. Daher sucht die Shell nach einem ganzzahligen Ausdruck und wenn Text beim ersten Element gefunden wird, versucht sie, ihn als Parameter zu erweitern. Es wird arithmetische Erweiterung genannt und ist in man bash enthalten .

RESERVED WORDS
       Reserved words are words that have a special meaning to the shell.  
       The following words are recognized as reserved 
       …
       [[ ]]

[[ expression ]]
       Return  a  status  of 0 or 1 depending on the evaluation of 
       the conditional expression expression.  Expressions are 
       composed of the primaries described below under CONDITIONAL 
       EXPRESSIONS.  Word splitting and pathname expansion are not 
       performed on the words between the  [[  and  ]];  tilde 
       expansion, parameter and variable expansion, >>>_arithmetic 
       expansion_<<<, command substitution, process substitution, and 
       quote removal are performed.  

Arithmetic Expansion
       …
       The evaluation is performed according to the rules listed below 
       under ARITHMETIC EVALUATION.

ARITHMETIC EVALUATION
       …
       Within an expression, shell variables may also be referenced 
       by name without using the parameter expansion syntax.

Also zum Beispiel:

[[ hdjakshdka -eq fkshdfwuefy ]]

wird immer true zurückgeben

Aber dieser wird einen Fehler zurückgeben

$ [[ 1235hsdkjfh -eq 81749hfjsdkhf ]]
-bash: [[: 1235hsdkjfh: value too great for base (error token is "1235hsdkjfh")

Auch Rekursion ist verfügbar:

$ VALUE=VALUE ; [[ VALUE -eq 12 ]]
-bash: [[: VALUE: expression recursion level exceeded (error token is "VALUE")

Linux
  1. Warum funktioniert der reguläre Ausdruck in X, aber nicht in Y?

  2. Warum funktioniert die Bash-Prozesssubstitution bei einigen Befehlen nicht?

  3. Linux – Warum funktioniert Setuid nicht?

  4. Linux – Warum funktioniert Locale Es_mx, aber nicht Es?

  5. Ssh – Wie funktioniert TCP-Keepalive in Ssh?

Rm-Befehl im Bash-Skript funktioniert nicht mit Variablen?

Warum funktioniert `exit &` nicht?

Was ist der Grep-Befehl unter Linux? Warum wird es verwendet und wie funktioniert es?

Warum funktioniert Tomcat mit Port 8080, aber nicht mit 80?

Warum funktioniert `\d` nicht in regulären Ausdrücken in sed?

Warum funktioniert find -mtime bei Dateien mit unterschiedlichen Zeitzonen nicht wie erwartet?