11.04.2013 Views

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

exit 0<br />

Capitolo 4. Introduzione alle variabili ed ai parametri<br />

# (Ve<strong>di</strong> il capitolo sul "Quoting.")<br />

Assegnamento <strong>di</strong> variabile utilizzando $(...) (metodo più recente rispetto agli apici inversi). In realtà<br />

si tratta <strong>di</strong> una forma particolare <strong>di</strong> sostituzione<strong>di</strong> comando.<br />

# Dal file /etc/rc.d/rc.local<br />

R=$(cat /etc/redhat-release)<br />

arch=$(uname -m)<br />

4.3. Le variabili <strong>Bash</strong> non sono tipizzate<br />

A <strong>di</strong>fferenza <strong>di</strong> molti altri linguaggi <strong>di</strong> programmazione, <strong>Bash</strong> non <strong>di</strong>fferenzia le sue variabili per “tipo”.<br />

Essenzialmente le variabili <strong>Bash</strong> sono stringhe <strong>di</strong> caratteri, ma, in base al contesto, la shell consente le<br />

operazioni con interi e i confronti <strong>di</strong> variabili. Il fattore determinante è se il valore <strong>di</strong> una variabile sia<br />

formato, o meno, solo da cifre.<br />

Esempio 4-4. Intero o stringa?<br />

#!/bin/bash<br />

# int-or-string.sh: Intero o stringa?<br />

a=2334 # Intero.<br />

let "a += 1"<br />

echo "a = $a " # a = 2335<br />

echo # Intero, ancora.<br />

b=${a/23/BB} # Sostituisce "23" con "BB".<br />

# Questo trasforma $b in una stringa.<br />

echo "b = $b" # b = BB35<br />

declare -i b # Dichiararla come intero non aiuta.<br />

echo "b = $b" # b = BB35<br />

let "b += 1" # BB35 + 1 =<br />

echo "b = $b" # b = 1<br />

echo<br />

c=BB34<br />

echo "c = $c" # c = BB34<br />

d=${c/BB/23} # Sostituisce "BB" con "23".<br />

# Questo trasforma $d in un intero.<br />

echo "d = $d" # d = 2334<br />

42

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!