2012-01-17 7 views
17

Qual è il significato di una variabile bash utilizzato in questo modo:

${Server?} 

risposta

23

Funziona quasi la stessa (dal bash manpage):

${parameter:?word}
Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

Quello particolari verifiche delle varianti per garantire che la variabile esista s (è sia definito che non nullo). Se è così, lo usa. In caso contrario, visualizza il messaggio di errore specificato da word (o uno adatto se non è presente il numero word) e termina lo script.

La differenza reale tra questo e la versione non colon può essere trovato nel bash manpage sopra la sezione indicata:

Quando non si esegue espansione sottostringa, utilizzando i moduli documentati sotto, bash test per un parametro non impostato o nullo. L'omissione dei due punti restituisce un test solo per un parametro non impostato.

In altre parole, la sezione sopra può essere modificato per leggere (praticamente eliminando i bit "nulli"):

${parameter?word}
Display Error if Unset. If parameter is unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

La differenza è illustrato così:

pax> unset xyzzy ; export plugh= 

pax> echo ${xyzzy:?no} 
bash: xyzzy: no 

pax> echo ${plugh:?no} 
bash: plugh: no 

pax> echo ${xyzzy?no} 
bash: xyzzy: no 

pax> echo ${plugh?no} 

pax> _ 

In questo caso, è possibile notare che mentre entrambe le variabili nulle e si risolvono in un errore con :?, è possibile annullare solo un errore con ?.

+0

E senza parola, c'è un messaggio di errore predefinito "parametro null o non impostato" (stesso messaggio con o senza due punti). –

10

significa che lo script dovrebbe interrompere se la variabile non è definita

Esempio:

#!/bin/bash 
echo We will see this 
${Server?Oh no! server is undefined!} 
echo Should not get here 

Questo script stamperà il primo eco e il messaggio di errore "Oh no! ...".

Vedi tutte le sostituzioni variabili per bash qui: http://tldp.org/LDP/abs/html/parameter-substitution.html

Problemi correlati