20.05.2015 Views

Télécharger - Site personnel de Serge Moutou

Télécharger - Site personnel de Serge Moutou

Télécharger - Site personnel de Serge Moutou

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

then<br />

# séquence exécutée si suite-<strong>de</strong>-comman<strong>de</strong>s rend une valeur 0<br />

bloc-instruction1<br />

else<br />

# séquence exécutée sinon<br />

bloc-instruction2<br />

fi<br />

Attention ! si then est placé sur la 1ère ligne, séparer avec un ;<br />

if comman<strong>de</strong>; then<br />

.....<br />

Exemples<br />

1. toto possé<strong>de</strong> t-il un compte ? On teste la présence d'une ligne commençant par toto dans /etc/passwd (<br />

>/<strong>de</strong>v/null pour détourner l'affichage <strong>de</strong> la ligne trouvée)<br />

if grep "^toto" /etc/passwd > /<strong>de</strong>v/null<br />

then<br />

echo "Toto a déjà un compte"<br />

fi<br />

2. Si toto a eu une bonne note, on le félicite<br />

note=17<br />

if [ $note -gt 16 ] ---> test vrai, valeur retournée : 0<br />

then echo "Très bien !"<br />

fi<br />

3. Avant d'exécuter un script, tester son existence.<br />

Extrait <strong>de</strong> $HOME/.bash_profile<br />

if [ -f ~/.bashrc ]<br />

then<br />

.~/.bashrc<br />

fi<br />

Conditionnelles imbriquées<br />

Pour imbriquer plusieurs conditions, on utilise la construction :<br />

if comman<strong>de</strong>1<br />

then<br />

bloc-instruction1<br />

elif comman<strong>de</strong>2<br />

then<br />

bloc-instruction2<br />

else<br />

# si toutes les conditions précé<strong>de</strong>ntes sont fausses<br />

bloc-instruction3<br />

fi<br />

Exemples<br />

1. toto a t-il fait son <strong>de</strong>voir lisiblement ?<br />

fichier=/home/toto/<strong>de</strong>voir1.html<br />

if [ -f $fichier -a -r $fichier ]<br />

84 /163

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

Saved successfully!

Ooh no, something went wrong!