Ce document d’accompagnement du stage
« Programmation Shell et Langages de Scripts » rappelle les points principaux à retenir concernant la programmation pour shells Bourne et Korn.
Évaluation des expressions
variable=valeur
tableau[rang]=valeur
!
${variable}
" #
${tableau[rang]}
" #
${variable-valeur}
" #
${variable=valeur}
#
${variable?valeur}
!
${#variable}
" #
${variable#motif}
"
$ #
${variable%motif}
"
$ #
${variable##motif} ${variable%%motif}
$ $ % !
~utilisateur/
" #
ab{c,d,e}fg
abcfg abdfg abefg
$(commande)
" #
$((expression))
" " & '
!
Protection des caractères spéciaux
"$var1 $var2"
( " ) %
# '$var1 $var2'
( * " " +#
\$var
' $ & ""
' * " " +!
Structures de contrôle
Boucles
while cmd_1 ; do commandes done
, ' & *+!
until cmd_1 ; do commandes done
, ' & $!
for variable in liste ; do commandes
done
, ' "
" !
break
" % for#while until!
continue
- % !
Tests
if cmd_1 ; then cmd_2
elif cmd_3 ; then cmd_4
else cmd_5 fi
$ !
# $ # $ !
case expression in
motif_1 ) cmd_1 ;;
motif_2 | motif_3 ) cmd_2 ;;
* ) cmd_3 ;;
esac
# $ #
# $ #
$ !
Fonctions
fonction_1 () {
commandes…
}
!
fonction_1 valeur_1 valeur_2...
. "
$1#$2/ "% $#!
local variable
% -
return valeur
" 0 !
Motifs du shell
*
" & ( ' *"1" +#
?
" & ' #
\* \? \\
' *#?#\#
[liste]
' l#i#s#t#e [b-e]
' b#c#d#e
[^liste]
2 " & '
Redirections
commande < fichier
# commande > fichier
# commande >> fichier
3 #
commande 2> fichier
# commande 2>> fichier
3 #
commande 2>&1
& - #
commande <<- ETIQUETTE lignes à envoyer vers l’entrée standard de la commande
ETIQUETTE
" 0 !
Exécution des commandes
Ligne shebang
#! /bin/sh
% !
Pipeline
commande | commande | commande 3
Liste de pipelines pipeline ; pipeline
*$ & +
pipeline & pipeline
*$ ' +
pipeline && pipeline
*$ +
pipeline || pipeline
*$ +
Commandes composées { liste de pipelines }
* " "" +
( liste de pipelines )
* 4 +
Commandes internes essentielles
echo
echo arguments
" !
-n "
-e ' & !
read
read variables…
" "
* 5 % IFS+!
6 ' % ) & ! #
% REPLY! , $ !
exec
exec commande
" * + !
exec redirections
& & !
source
source script . script
' !
exit
exit valeur
" * + 0 !
test
test condition [ condition ]
, !
" " & 5
-eq/ -/
-ne/ /
-lt*-le+/ * +-/
-gt*-ge+/ * +-/
7 ( 5
-n
-z !
" ( 5
8# 8# 9# :
7 5
-a $ #
-b & " % #
-c & ' #
-d #
-f " #
-g% 4;<6 #
-G #
-h 0"% & # -k% =0 #
-N" ' #
-O - #
-p % "" * +#
-r 1 #
-s 4 #
-S = #
-u% 4><6 #
-w 1 #
-x 1 $ !
" 5
-ef/ "1" 0 & & / #
-nt/ " "" & / #
-ot/ " " & /
7 5
-t "
cd
cd repertoire
#
cd – #
cd $ !
pwd
! export
export variable
7 ' " &
" $ !
env
"
set set
% " #
set options
"' 5
-a $ %
-u %
-v "" $
-x " $
unset
unset variable
! getopts
while getopts "ab:c" variable ; do case $variable in
a) echo "opt° –a";;
b) echo "opt° –b, arg. $OPTARG";;
c) echo "opt° –c";;
*) echo "opt° invalide"; exit 1;;
esac done
shift $((OPTIND – 1)) echo "arguments restants :"
echo "$@"
exit 0
0 ""
! " *?: '
+# " OPTARG! >
# " "
" OPTIND!
shift shift n
" "" 5
$0 # $n+1 $1# $n+2 $2#
!
@@AAA!% ! @