0% ont trouvé ce document utile (0 vote)
37 vues445 pages

Cours Unix pour Étudiants Avancés

Le document présente un cours sur Unix et la programmation Shell, visant à renforcer les connaissances des utilisateurs des systèmes Unix. Il aborde des concepts fondamentaux tels que le système de fichiers, les processus, et la programmation en ligne de commande. Le cours est destiné aux étudiants ayant une expérience préalable avec Unix et inclut des travaux pratiques et des séances de cours.
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
37 vues445 pages

Cours Unix pour Étudiants Avancés

Le document présente un cours sur Unix et la programmation Shell, visant à renforcer les connaissances des utilisateurs des systèmes Unix. Il aborde des concepts fondamentaux tels que le système de fichiers, les processus, et la programmation en ligne de commande. Le cours est destiné aux étudiants ayant une expérience préalable avec Unix et inclut des travaux pratiques et des séances de cours.
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

Unix et Programmation Shell

Philippe Langevin

IMATH, USTV

Automne 

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  1 / 391
sommaire

1 Introduction 5 bash 9 redirection

2 shell unix 6 fichier 10 pipeline

3 manuel 7 permission 11 outils

4 login 8 processus

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  2 / 391
document

brouillon en révision

site du cours :
[Link]
localisation du fichier :
[Link]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  3 / 391
dernières modifications
upsh . t e x 2024−01−28 [Link].653614398 +0100
tools . tex 2024−01−28 [Link].653614398 +0100
term . t e x 2024−01−28 [Link].651614387 +0100
syntaxe . tex 2024−01−28 [Link].650614381 +0100
s h e l l . tex 2024−01−28 [Link].649614376 +0100
prologue . tex 2024−01−28 [Link].648614371 +0100
proc . tex 2024−01−28 [Link].646614360 +0100
pipe . tex 2024−01−28 [Link].645614355 +0100
perm . t e x 2024−01−28 [Link].645614355 +0100
man . t e x 2024−01−28 [Link].643614344 +0100
part . tex 2024−01−28 [Link].644614349 +0100
f i l e . tex 2024−01−28 [Link].642614338 +0100
d i r e c t . tex 2024−01−28 [Link].641614333 +0100
bash . t e x 2024−01−28 [Link].639614322 +0100
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  4 / 391
Introduction

1 - Introduction

notions abordées
partie cachée
programme
public et prérequis

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  5 / 391
Introduction notions abordées

Objectifs du cours
Il s’acquérir ou de compléter nos connaissances des systèmes unix du
point de vue utilisateur. Nous aborderons néanmoins quelques notions
fondamentales de ces systèmes d’exploitation :
système de fichier
processus, tube, redirection
environnement, permission
signaux, thread
pour appréhender l’usage :
ligne de commande,
programmation shell,
commandes usuelles,
applications populaires.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  6 / 391
Introduction partie cachée

partie cachée
La ligne de commande est la partie visible de l’iceberg. Les aspects
internes :
contexte d’exécution,
ordonnancement,
mémoire,
sémaphore,
ipc. . .
où les aspects externes
module,
matériels,
protocoles
seront évoqués à la demande mais sans jamais entrer dans les détails.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  7 / 391
Introduction programme

programme

L’unité d’enseignement I54 prévoit 30 HE, avec la répartion :


12H cours 6 séances
3H travaux dirigés 2 séances
15H travaux pratiques 5 séances
2H examen TP
2H examen CT
Intervenants :
Didier Malarino
Philippe Langevin

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  8 / 391
Introduction public et prérequis

Public

I54 est un cours de mise à niveau et/ou de perfectionnement qui


s’adresse idéalement aux étudiants ayant eu une expérience sur un
système unix, typiquement, un compte utilisateur sous linux.

Prérequis : manipulation de bases des fichiers et répertoires sur la


ligne de commande. Base du langage C et de la compilation avec
gcc.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  9 / 391
Introduction public et prérequis

documentation

Le cours est accessible à partir du site

[local] [Link]

marquer les pages


cahier de texte
liste de discussion

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  10 / 391
shell unix

2 - shell unix

origine
unices
GNU/linux
distribution
shell unix
GUI vs CLI
C-production

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  11 / 391
shell unix origine

naissance de unix

Parmi les nombreux hackers du 20e, deux pionniers des Bell labs
sont à l’origine du système unix :

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  12 / 391
shell unix origine

naissance de unix

Parmi les nombreux hackers du 20e, deux pionniers des Bell labs
sont à l’origine du système unix :

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  12 / 391
shell unix origine

naissance de unix

Parmi les nombreux hackers du 20e, deux pionniers des Bell labs
sont à l’origine du système unix :

1969 Ken Thompson crée le système UNICS

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  12 / 391
shell unix origine

naissance de unix

Parmi les nombreux hackers du 20e, deux pionniers des Bell labs
sont à l’origine du système unix :

1969 Ken Thompson crée le système UNICS


1971 Dennis Ritchie crée le langage C

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  12 / 391
shell unix origine

naissance de unix

Parmi les nombreux hackers du 20e, deux pionniers des Bell labs
sont à l’origine du système unix :

1969 Ken Thompson crée le système UNICS


1971 Dennis Ritchie crée le langage C
[PSLC] prog. système en langage C sous Linux, par C. Blaess.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  12 / 391
shell unix origine

naissance de unix

Parmi les nombreux hackers du 20e, deux pionniers des Bell labs
sont à l’origine du système unix :

1969 Ken Thompson crée le système UNICS


1971 Dennis Ritchie crée le langage C
[PSLC] prog. système en langage C sous Linux, par C. Blaess.
[EPI] unix et l’informatique pédagogique ont le même age !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  12 / 391
shell unix origine

MULTICS — UNICS — UNIX

1964 MIT, General Electric et les Bell Labs d’AT&T lancent le projet
MULTiplexed Information and Computing Service pour
développer un nouveau système d’exploitation à temps partagé.
1969 Les Bell Labs se retire du projet.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  13 / 391
shell unix origine

chronologie

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  14 / 391
shell unix unices

unix populaires

unix a donné naissance à une famille de systèmes, les unices dont les
plus populaires sont :
1983 System V Bell labs, AT&T.
1977 BSD Berkeley Software Distribution
1990 GNU/Linux Logiciel Libre
1999 OS X next, apple.
2003 android androı̈de, google.

L’ensemble des industriels acteurs du développemement du système


unix sont regoupés dans l’opengroup propriétaire de la marque unix
dont le Single UNIX Specification certifie les systèmes unix.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  15 / 391
shell unix unices

influences

Trois groupes influent sur la normalisation des systèmes unix :


POSIX : Portable Operating System Interface (IEEE).
BSD
GNU : Gnu is Not Unix, logiciel libre.
Je vous recommande
la description du projet GNU par R. Stallman
la lecture de la cathédrale et le bazar par E. Raymond.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  16 / 391
shell unix unices

dialecte
PS ( 1 ) L i n u x User ’ s Manual
NAME
ps − r e p o r t a snapshot o f the c u r r e n t p r o c e s s e s .

DESCRIPTION
ps d i s p l a y s i n f o r m a t i o n about a s e l e c t i o n o f the
a c t i v e p r o c e s s e s . I f you want a r e p e t i t i v e u p d a t e
o f t h e s e l e c t i o n and t h e d i s p l a y e d i n f o r m a t i o n ,
use top .

This ps v e r s i o n a c c e p t s s e v e r a l k i n d s o f o p t i o n s :
1 UNIX o p t i o n s , must be p r e c e d e d by a d a s h .
2 BSD o p t i o n s , must n o t be u s e d w i t h a d a s h .
3 GNU l o n g o p t i o n s , p r e c e d e d by two d a s h e s .
O p t i o n s o f d i f f e r e n t t y p e s may be f r e e l y mixed ,
Philippe Langevin (IMATH, USTV)
b u t c o n f l i c t s can Automne
Unix et Programmation Shell
a p p e 
ar . 17 / 391
shell unix GNU/linux

GNU/linux

Dans les salles de travaux-pratiques, vous utiliserez un système


d’exploitation GNU/linux, fusion des composantes du logiciel libre :
noyau linux (Linus Torvalds, 1991 ),
utilitaires GNU (Richard Stallman, 1983).
Plus précisément, une distribution ubuntu, basée sur debian. Il s’agit
d’un environnement de travail unix de qualité issu du logiciel libre ? !.
hurd : le noyau GNU n’est pas encore opérationnel.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  18 / 391
shell unix GNU/linux

GNU/linux
libérez unix!
Hello everybody out there using

minix
Le nom GNU/Linux fut utilisé pour la première fois par debian en
1994 pour le nom de leur distribution du système d’exploitation basé
sur le noyau Linux et des logiciels GNU.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  19 / 391
shell unix GNU/linux

le 27 septembre 1983 : libérez unix !


À partir de Thanksgiving je vais écrire un système logiciel complet
compatible avec Unix appelé GNU, et le distribuer librement à
quiconque voudra l’utiliser. Il y a grand besoin de contributions sous
forme de temps, d’argent, de programmes et d’équipement.
Pour commencer, GNU comprendra un noyau ainsi que tous les
utilitaires requis pour écrire et faire tourner des programmes C :
éditeur, interpréteur de commandes, compilateur C, éditeur de liens,
assembleur et quelques autres encore. Par la suite, nous ajouterons
un formateur de texte, un YACC, un jeu Empire, un tableur et des
centaines d’autres choses. À terme, nous espérons fournir tous les
composants utiles venant normalement avec un système Unix, ainsi
que tout autre composant utile, y compris de la documentation en
ligne et imprimée...
– Richard Stallman
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  20 / 391
shell unix GNU/linux

paquets gnu (2012)


a2ps acct acm adns aetherspace alive anubis archimedes aris aspell
auctex autoconf autoconf-archive autogen automake avl
ballandpaddle barcode bash bayonne bazaar bc bfd binutils bison bool
bpel2owfn c-graph ccaudio ccide ccrtp ccscript cflow cgicc chess cim
classpath classpathx clisp cobol combine commoncpp complexity
config coreutils cpio cppi cssc dap dc ddd ddrescue dejagnu denemo
dia dico diction diffutils dionysus dismal djgpp dmd dominion dotgnu
dotgnu-forum dotgnu-pnet dr-geo ed edma electric emacs
emacs-muse emms enscript eprints epsilon fdisk ferret findutils
fontutils freedink freefont freeipmi freetalk fribidi gama garpd gawk
gcal gcc gcide gcl gcompris gdb gdbm gengen gengetopt gettext
gforth ggradebook ghostscript gift gimp gleem glib global glpk glue
gmediaserver gmorph gmp gnash gnat gnats gnatsweb gnome
gnowsys gnu-arch gnu-c-manual gnu-crypto
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  21 / 391
shell unix GNU/linux

gnuae gnubatch gnubg gnubiff gnubik gnucap gnucash gnucomm


gnue gnufm gnugo gnuit gnujdoc gnujump gnukart gnulib gnumach
gnumed gnumeric gnump3d gnun gnunet gnupg gnupod
gnuprologjava gnuradio gnurobots gnuschool gnushogi gnuskies
gnusound gnuspeech gnuspool gnustandards gnustep gnutls
gnutrition gnuzilla goptical gorm gpaint gperf gprolog grabcomics
greg grep gretl groff grub gsasl gsegrafix gsl gsrc gss gtick gtk+
gtypist guile guile-dbi guile-gnome guile-gtk guile-ncurses guile-rpc
gurgle gv gvpe gxmessage gzip halifax health hello help2man hp2xx
httptunnel hurd hyperbole icecat idutils ignuit indent inetutils
intlfonts jacal java-getopt jdresolve jel jwhois kawa kopi leg less libc
libcdio libextractor libffcall libgcrypt libiconv libidn libmatheval
libmicrohttpd libredwg librejs libsigsegv libtasn1 libtool libunistring
libxmi lightning lilypond linux-libre liquidwar6 lispintro lrzsz lsh m4
macchanger mailman mailutils

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  22 / 391
shell unix GNU/linux

make marst maverik mc mcron mcsim mdk mediagoblin melting


metaexchange metahtml mifluz mig miscfiles mit-scheme moe motti
mpc mpfr mtools myserver nana nano ncurses nettle network ocrad
octave oleo orgadoc osip packaging panorama paperclips parallel
parted pascal patch paxutils pcb pdf pem pexec pgccfd
phantom-home phpgroupware pies pipo plotutils polyxmass
powerguru proxyknife pspp psychosynth pth pythonwebkit qexo
quickthreads radius rcs readline recutils reftex rottlog rpge rush
sather scm screen sed serveez sharutils shishi shmm shtool sipwitch
slib smalltalk smarteiffel snakecharmer social solfege sourceinstall
spacechart speex spell sqltutor src-highlite stalkerfs stow stump
superopt swbis sysutils talkfilters tar termcap termutils teseq
teximpatient texinfo texmacs thales time tramp trans-coord trueprint
units unrtf userv uucp vc-changelog vc-dwim vcdimager vera vmgen
vmslib w3 wb wdiff websocket4j webstump wget which womb xaos
xboard xhippo xlogmaster xmlat xnee xorriso zile
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  23 / 391
shell unix GNU/linux

On 25 August 1991, newsgroup [Link]


Hello everybody out there using minix.
I’m doing a (free) operating system (just a hobby, won’t be big and
professional like gnu) for 386(486) AT clones. This has been brewing since
april, and is starting to get ready. I’d like any feedback on things people
like/dislike in minix, as my OS resembles it somewhat (same physical
layout of the file-system (due to practical reasons) among other things).
I’ve currently ported bash(1.08) and gcc(1.40), and things seem to work.
This implies that I’ll get something practical within a few months, and I’d
like to know what features most people would want. Any suggestions are
welcome, but I won’t promise I’ll implement them :-)
Linus (torvalds@[Link])
PS. Yes – it’s free of any minix code, and it has a multi-threaded fs. It is
NOT portable (uses 386 task switching etc), and it probably never will
support anything other than AT-harddisks, as that’s all I have :-(. —Linus
Torvalds
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  24 / 391
shell unix GNU/linux

monolithique vs micro-noyau

Le système minix est système minimaliste créé en 1987 par Andrew


Tannenbaum pour illustrer son fameux cours sur les systèmes
d’exploitation.

To me, writing a monolithic system in 1991 is a truly poor idea.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  25 / 391
shell unix GNU/linux

monolithique vs micro-noyau

Le système minix est système minimaliste créé en 1987 par Andrew


Tannenbaum pour illustrer son fameux cours sur les systèmes
d’exploitation.

To me, writing a monolithic system in 1991 is a truly poor idea.


Je persiste à penser que concevoir un noyau monolithique en
1991 est une erreur fondamentale. Estime-toi heureux de ne pas
être un de mes étudiants. Tu n’obtiendrais pas une bonne note
pour une telle conception :-)

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  25 / 391
shell unix GNU/linux

monolithique vs micro-noyau

Le système minix est système minimaliste créé en 1987 par Andrew


Tannenbaum pour illustrer son fameux cours sur les systèmes
d’exploitation.

To me, writing a monolithic system in 1991 is a truly poor idea.


Je persiste à penser que concevoir un noyau monolithique en
1991 est une erreur fondamentale. Estime-toi heureux de ne pas
être un de mes étudiants. Tu n’obtiendrais pas une bonne note
pour une telle conception :-)

linux >2 est un noyau monolithique modulaire.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  25 / 391
shell unix GNU/linux

noyau linux

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  26 / 391
shell unix distribution

distribution
Le système GNU/linux est mis en forme au sein de plusieurs
distributions qui intègrent le noyau et les utilitaires avec
une politique de distribution,
un système de maintenance,
une communauté
uname −m −o −r −s
L i n u x 2 . 6 . 3 4 . 9 − 6 9 . f c 1 3 . i 6 8 6 i 6 8 6 GNU/ L i n u x

s s h pl@192 . 1 6 8 . 0 . 1 5 0 uname −mors


L i n u x 3 . 8 . 1 3 − 1 0 0 . f c 1 7 . i 6 8 6 . PAE i 6 8 6 GNU/ L i n u x

ssh pl@imath01
L i n u x 2 . 6 . 1 8 − 3 4 8 . 4 . 1 . e l 5 . c e n t o s . p l u s x 8 6 6 4 GNU/
Linux
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  27 / 391
shell unix distribution

uname –help ( man uname )

uname −−h e l p
U t i l i s a t i o n : uname [ OPTION ]
A f f i c h e c e r t a i n e s i n f o r m a t i o n s systeme
−a , −− a l l
−s , −−k e r n e l −name nom du noyau
−n , −−nodename hostname
−r , −−k e r n e l −r e l e a s e v e r s i o n du noyau
−v , −−k e r n e l −v e r s i o n v e r s i o n du k e r n e l
−m, −−machine materiel
−p , −−p r o c e s s o r t y p e de p r o c e s s e u r
−i , −−hard ware −p l a t f o r m p l a t e −f o r m e
−o , −−o p e r a t i n g −s y s t e m systeme

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  28 / 391
shell unix distribution

distribution

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  29 / 391
shell unix distribution

distribution

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  30 / 391
shell unix distribution

position

D’aprés la linux foundation, en juin 2012, 98% des supercalculateurs


du top500 sont essentiellement équipés d’un système linux :
2012
linux 92.4
unix 5
windows 0.4
BSD 0.2

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  31 / 391
shell unix distribution

systèmes des supercalculateurs

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  32 / 391
shell unix distribution

position

En 2013, United Space Alliance remplace les windows et


scientific linux des ordinateurs de la station spatiale ISS
par une distribution debian de GNU/linux.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  33 / 391
shell unix distribution

position

En 2013, United Space Alliance remplace les windows et


scientific linux des ordinateurs de la station spatiale ISS
par une distribution debian de GNU/linux.
La plupart des serveurs du réseau internet tournent sous un
système unix.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  33 / 391
shell unix distribution

position

En 2013, United Space Alliance remplace les windows et


scientific linux des ordinateurs de la station spatiale ISS
par une distribution debian de GNU/linux.
La plupart des serveurs du réseau internet tournent sous un
système unix.
matériel embarqué, matériel réseau

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  33 / 391
shell unix distribution

position

En 2013, United Space Alliance remplace les windows et


scientific linux des ordinateurs de la station spatiale ISS
par une distribution debian de GNU/linux.
La plupart des serveurs du réseau internet tournent sous un
système unix.
matériel embarqué, matériel réseau
tablette, téléphone

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  33 / 391
shell unix shell unix

shell ?

La terminologie de la communauté unix comprend quelques


bizarreries, sigles et acronymes plus ou moins célèbres :
Portable Operating System Interface X
foo, bar ? ?
biff
shell ? bash ! shabang ] !
[ESR’s jargon file]
[RFC-3092] International Engineering Task Force.
[FAQ] : unix Frequently Asked Questions.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  34 / 391
shell unix shell unix

cowsay -W30 ’it is easier...

−−−−−−−−−−−−−−−−−−−−−−−−
/ i t i s e a s i e r to port a \
| s h e l l than a s h e l l |
\ s c r i p t ( L a r r y Wal l ) /
−−−−−−−−−−−−−−−−−−−−−−−−
\ ˆ ˆ
\ ( oo ) \
( )\ ) \/\
||−−−−w |
|| ||
La déclaration de Wall fait référence au partage d’un shell unix sur
un système windows. Le hacker est l’inventeur d’un langage de
manipulation de fichiers textes. Lequel ?
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  35 / 391
shell unix shell unix

cowsay -W30 ’it is easier...

−−−−−−−−−−−−−−−−−−−−−−−−
/ i t i s e a s i e r to port a \
| s h e l l than a s h e l l |
\ s c r i p t ( L a r r y Wal l ) /
−−−−−−−−−−−−−−−−−−−−−−−−
\ ˆ ˆ
\ ( oo ) \
( )\ ) \/\
||−−−−w |
|| ||
La déclaration de Wall fait référence au partage d’un shell unix sur
un système windows. Le hacker est l’inventeur d’un langage de
manipulation de fichiers textes. Lequel ?
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  35 / 391
shell unix shell unix

système d’exploitation

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  36 / 391
shell unix shell unix

système d’exploitation

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  37 / 391
shell unix shell unix

Thompson shell

La notion de shell apparaı̂t dans le système MULTICS, il s’agit d’une


application à l’interface entre le noyau et les utilitaires. Le shell
développé au début des années 70 par Thompson est un interprète de
commandes qui introduit la syntaxe des deux opérateurs
fondamentaux des systèmes unix, la redirection :

commande > destination < source

et le pipeline de Douglas McIlroy

commande | commande

[man 1 sh]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  38 / 391
shell unix shell unix

shell unix

Un shell unix est une commande qui permet d’accéder aux


fonctionnalités du système d’exploitation :
utilisation des fichiers et commandes externes
contrôle des processus
Un shell est un langage de programmation qui traitent des variables :
globabe, locale et exportée au moyen de commande interne. Un
processus shell possède un des modes d’exécutions :
login (initialisation)
interactif (ligne de commande)
interpréte (script)

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  39 / 391
shell unix shell unix

traçage des appels


Les débogueurs ltrace et strace renseignent sur les appels
bibliothèques et systèmes effectués par un processus :
1 #include <stdio.h>
2 int main( void )
3 {
4 puts(”hello world”);
5 return 0;
6 }

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  40 / 391
shell unix shell unix

traçage des appels


Les débogueurs ltrace et strace renseignent sur les appels
bibliothèques et systèmes effectués par un processus :
1 #include <stdio.h>
2 int main( void )
3 {
4 puts(”hello world”);
5 return 0;
6 }

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  40 / 391
shell unix shell unix

puts("hello world")

1 #!/bin/bash
2 gcc −Wall hw.c
3 ltrace ./ a. out |& cut −c1−50 > [Link]
4 strace −e trace=read,write,file ./ a. out\
5 |& cut −c1−50 >> [Link]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  41 / 391
shell unix shell unix

puts("hello world")

l i b c s t a r t m a i n ( 0 x80483b4 , 2 , 0 x b f a 9 2 d b 4 , 0 x8048
puts (” h e l l o world ”) =
h e l l o world
+++ e x i t e d ( s t a t u s 0 ) +++
e x e c v e ( ” . / a . o u t ” , [ ” . / a . o u t ” ] , [ / ∗ 52 v a r s ∗ / ] ) =
a c c e s s ( ” / e t c / l d . s o . p r e l o a d ” , R OK) = −1 ENOEN
open ( ” / e t c / l d . s o . c a c h e ” , O RDONLY) = 3
open ( ” / l i b / l i b c . s o . 6 ” , O RDONLY) = 3
r e a d ( 3 , ”\177 ELF \1\1\1\3\0\0\0\0\0\0\0\0\3\0\3\0\1
w r i t e ( 1 , ” h e l l o w o r l d \n ” , 12 h e l l o w o r l d
) = 12

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  42 / 391
shell unix shell unix

echo hello world

Un exemple plus complexe


1 #/bin/bash
2 ltrace echo hello world |& \
3 cut −c1−50 >hello−[Link]
4
5 strace −e trace=open,read,write,file \
6 echo hello world |& \
7 cut −c1−50 >hello−[Link]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  43 / 391
shell unix shell unix

echo hello world


l i b c s t a r t m a i n ( 0 x8049070 , 3 , 0 x b f a 6 9 1 7 4 , 0 x804b
g e t e n v ( ” POSIXLY CORRECT ” ) =
s t r r c h r ( ” echo ” , ’ / ’ ) =
s e t l o c a l e (6 , ””) =
b i n d t e x t d o m a i n ( ” c o r e u t i l s ” , ”/ u s r / s h a r e / l o c a l e ” ) =
textdomain (” c o r e u t i l s ”) =
c x a a t e x i t ( 0 x804a000 , 0 , 0 , 0 x804e5b8 , 0 x b f a 6 9 0 c
f p u t s u n l o c k e d (0 xbfa695ad , 0 xc5e4e0 , 0 xc5c1e0 , 0 ,
f p u t s u n l o c k e d (0 xbfa695b3 , 0 xc5e4e0 , 0 xc5c1e0 , 0 ,
e x i t (0 <u n f i n i s h e d ... >
f p e n d i n g ( 0 xc 5 e4 e 0 , 0 x c 5 e 4 e 0 , 0 xb42a24 , 0 x b f a 6 8 f d
f c l o s e (0 x c 5 e 4 e 0 h e l l o world
) = 0
f p e n d i n g ( 0 xc5e580 , 0 x c 5 e 4 e 0 , 0 xb42a24 , 0 x b f a 6 8 f d
f c l o s e (0 xc5e580 ) =
+++ e x i t e d ( s t a t u s 0Unix
Philippe Langevin (IMATH, USTV)
) +++
et Programmation Shell Automne  44 / 391
shell unix shell unix

echo hello world

e x e c v e ( ” / b i n / echo ” , [ ” echo ” , ” h e l l o ” , ” w o r l d ” ] , [ /
a c c e s s ( ” / e t c / l d . s o . p r e l o a d ” , R OK) = −1 ENOEN
open ( ” / e t c / l d . s o . c a c h e ” , O RDONLY) = 3
open ( ” / l i b / l i b c . s o . 6 ” , O RDONLY) = 3
r e a d ( 3 , ”\177 ELF \1\1\1\3\0\0\0\0\0\0\0\0\3\0\3\0\1
open ( ” / u s r / l i b / l o c a l e / l o c a l e −a r c h i v e ” , O RDONLY | O
w r i t e ( 1 , ” h e l l o w o r l d \n ” , 12 h e l l o w o r l d
) = 12

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  45 / 391
shell unix shell unix

Bourne [Again] shell

Le Bourne shell est introduit dans le système UNIX V7. Il a été


développé par Stephen Bourne avec l’objectif de créer un outil de
scriptage des commandes pour faciliter l’administration du système.
sh est devenu populaire pour sa facilité d’emploi et sa rapidité,
standard des systèmes UNIX, c’est toujours le shell par défaut du
compte root, de certaines commandes make.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  46 / 391
shell unix shell unix

Bourne [Again] shell

Le Bourne shell est introduit dans le système UNIX V7. Il a été


développé par Stephen Bourne avec l’objectif de créer un outil de
scriptage des commandes pour faciliter l’administration du système.
sh est devenu populaire pour sa facilité d’emploi et sa rapidité,
standard des systèmes UNIX, c’est toujours le shell par défaut du
compte root, de certaines commandes make.
Le shell de base sh
Les alias, l’historique des commandes et le contrôle des processus
ne sont pas gérés par sh.

Le Bourne Again shell est un projet GNU bash démarré en 1980 par
Brian Fox, actuellement maintenu par Chet Ramey.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  46 / 391
shell unix shell unix

shell par défaut

/ b i n / sh
sh −4.1 $ e x i t
exit

w h i c h sh
/ b i n / sh

l s − l / b i n / sh
l r w x r w x r w x . 1 r o o t r o o t 4 9 a o u t 0 8 : 4 7 / b i n / sh
−> b a s h

echo $SHELL
/ b i n / bash

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  47 / 391
shell unix shell unix

shell par défaut

echo $SHELL
/ b i n / bash

echo −e ’ a l l : \ n\ t e c h o $ ( SHELL ) ’ > /tmp/


makefile

make −c /tmp
make : e n t r a n t d a ns l e r e p e r t o i r e /tmp
echo / b i n / sh
/ b i n / sh
make : q u i t t a n t l e r e p e r t o i r e /tmp

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  48 / 391
shell unix shell unix

shell populaires
Les shells font légion.
shell shabang
sh 6 490 000
bash 5 380 000
ash 345 000
ksh 323 000
csh 254 000
tcsh 116 000
zsh 86 000
Table – popularité de quelques shells

Ces slides concernent mon shell préféré bash. . .


Aprés le lambis bien entendu !
[comparatif des shells]
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  49 / 391
shell unix GUI vs CLI

Interfaces

L’utilisateur d’un ordinateur interagit avec le système d’exploitation


au moyen d’une interface graphique ou bien d’une interface texte.
Graphic User Interface
Command Line Interface
La notion de shell est étendue à l’ensemble des interfaces y compris
graphique :gnome, kde, lxde, xfce, awesome . . .
L’évolution des GUIs fait souvent débat !
Le monde des CLIs parait plus zen. . .
suggestion : essayez les interfaces !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  50 / 391
shell unix GUI vs CLI

CLI vs GUI

Le mode graphique se veut intuitif et facile d’emploi.


Le mode textuel est puissant mais peu intuitif.
Il n’y a pas lieu d’opposer les deux modes qui sont parfaitement
complémentaires, les tâches sur les fichiers textes sont plus faciles à
réaliser par la console.
En général, lors d’une session graphique, les utilisateurs ouvrent des
pseudos terminaux pour effectuer certaines tâches avec l’interprète de
commande.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  51 / 391
shell unix C-production

C-production

Evaluer une C-production


combien de lignes de codes C dans le répertoire ./CC ?

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  52 / 391
shell unix C-production

C-production

Evaluer une C-production


combien de lignes de codes C dans le répertoire ./CC ?

Pas de solution graphique !


Difficile d’interpréter cette question par des mouvements de souris. . .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  52 / 391
shell unix C-production

C-production

Evaluer une C-production


combien de lignes de codes C dans le répertoire ./CC ?

Pas de solution graphique !


Difficile d’interpréter cette question par des mouvements de souris. . .

Plusieurs solutions textuelles


Au fil des années, les applications unix ont été développées,
améliorées pour répondre efficacement ce type de questions.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  52 / 391
shell unix C-production

Une ligne de commande


$ f i n d ˜/CC −name ” ∗ . c ” | x a r g s c a t | wc − l

400942

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  53 / 391
shell unix C-production

Une ligne de commande


$ f i n d ˜/CC −name ” ∗ . c ” | x a r g s c a t | wc − l

400942
Une solution facile à comprendre plus difficile à reproduire sans
connaı̂tre les usages des commandes et arguments passés par la ligne
de commande.
find : outil pour la recherche de fichiers.
wc : compter les lignes, mots, octets.
Paul Rubin et David MacKenzie
xargs : construire et exécuter des lignes de commandes.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  53 / 391
shell unix C-production

Une ligne de commande


$ f i n d ˜/CC −name ” ∗ . c ” | x a r g s c a t | wc − l

400942
Une solution facile à comprendre plus difficile à reproduire sans
connaı̂tre les usages des commandes et arguments passés par la ligne
de commande.
find : outil pour la recherche de fichiers.
wc : compter les lignes, mots, octets.
Paul Rubin et David MacKenzie
xargs : construire et exécuter des lignes de commandes.
$ c a t $ ( f i n d ˜/CC −name ’ ∗ . c ’ ) 2>/dev / n u l l | wc
−l

400942
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  53 / 391
shell unix C-production

Une autre solution

Une solution basée sur le filtre awk ?

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  54 / 391
shell unix C-production

Une autre solution

Une solution basée sur le filtre awk ?


$ f i n d ˜/CC −name ” ∗ . c ” −e x e c wc − l {} \ ;
| awk ’ BEGIN { s =0} { s=s+$0 } END { p r i n t s } ’

400942

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  54 / 391
shell unix C-production

Une autre solution

Une solution basée sur le filtre awk ?


$ f i n d ˜/CC −name ” ∗ . c ” −e x e c wc − l {} \ ;
| awk ’ BEGIN { s =0} { s=s+$0 } END { p r i n t s } ’

400942
find : outil pour la recherche de fichiers.
wc : compter les lignes, mots, octets.
awk : commande d’ Alfred Aho, Peter Weinberger et Brian
Kernighan pour filtrer les lignes d’un fichier texte.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  54 / 391
shell unix C-production

script

Le rôle d’un informaticien est de réaliser des travaux avec une


machine, le plus souvent, dans un temps limité :-).
Il convient déviter des pertes de temps qui ont pour origine
erreurs
lacunes
Un script est un fichier de commandes pour le shell. La première ligne
du script peut préciser le shell d’exécution :
1 #!/bin/myshell
2 ...

c’est le fameux shabang.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  55 / 391
shell unix C-production

exemple
1 #!/bin/bash
2 sum=0
3 while read num rem
4 do
5 echo $num $rem
6 let sum+=$num
7 done < <(find $1 −name $2 −exec wc −l {} \;)
8 echo $sum

Aprés avoir sauvé ces lignes dans un fichier [Link] :


chmod u+x c o u n t . sh
pour rendre le script exécutable, on peut alors lancer
. / c o u n t . sh ˜/CC ’ ∗ . c ’
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  56 / 391
shell unix C-production

commande complexe

Avec de la pratique, il est possible de d’exécuter une tache complexe


directement en ligne de commande :
f i n d ˜ −name ” ∗ . t x t ” −e x e c wc − l {} \ ;
| ( sum=0; w h i l e r e a d num rem ;
do l e t sum+=$num ; done ; echo $sum ) > sum . t x t
Il s’agit d’une commande composée s’articulant sur des commandes
simples incluant un pipeline et une redirection.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  57 / 391
manuel

3 - manuel

man help
navigation
section
piège
a propos
exercice
format

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  58 / 391
manuel

documentation

On peut faire beaucoup de choses en mode texte :


commande [option-courte] [option–longue] [argument]
filtrer : grep, sed, find
compiler : make, gcc
calculer : bc, gmp
jouer : gnuchess
naviguer : lynx, links
etc. . .
Le manuel unix est un moyen efficace pour découvrir et retrouver les
options des commandes populaires, les prototypes des bibliothèques,
les paramètres de configuration.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  59 / 391
manuel man help

pages du manuel
Il existe de nombreuses ressources pour obtenir de l’aide sur les
commandes : livre, tutoriel, forum, moteur de recherche, howto,
wiki. . .
man renseigne sur les commandes externes.
help renseigne sur les commandes internes.
Avant d’aller plus loin, rappelons comment sortir d’un mauvais pas
sur la ligne de commande :
ctrl-c : tuer la commande en cours
ctrl-d : fermer l’entrée standard
ctrl-z : stopper la commande
ctrl-u : nettoyer la ligne de commande
ctrl-r : retrouver une commande
readline, bind, .inputrc
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  60 / 391
manuel navigation

man page
Les composants unix sont documentés de manière concise sous
forme de man page. Une information exploitable en ligne de
commande par la commande man.
Raccourci Action Parm.
h aide
q quitter
flèches navigation
space , b changer de page suivante, précedente
/? rechercher avant/arrière
n, N occurrence suivante, précédente
Table – commandes de less

La sortie du manuel est au format roff : un langage à balises léger et,


par défaut, elle est interprée par la commande less.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  61 / 391
manuel section

bien commencer : man man . . .

man man | wc − l
616

man man | c o l −b | g r e p −A2 AUTEUR


AUTEUR
John W. Eaton e s t l ’ a u t e u r h i s t o r i q u e
de man . F e d e r i c o L u c i f r e d i < f l u c i f r e d i @ a c m . org>
en a s s u r e a u j o u r d ’ h u i l a m a i n t e n a n c e .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  62 / 391
manuel section

bien commencer : man man . . .

man man | c o l −b | g r e p BUGS −C4

A manual page c o n s i s t s o f s e v e r a l s e c t i o n s .

C o n v e n t i o n a l s e c t i o n names i n c l u d e NAME,
SYNOPSIS , CONFIGURATION , DESCRIPTION ,
OPTIONS , EXIT STATUS , RETURN VALUE , ERRORS ,
ENVIRONMENT, FILES , VERSIONS , CONFORMING TO,
NOTES, BUGS , EXAMPLE, AUTHORS, and SEE ALSO .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  63 / 391
manuel section

section du manuel

1 commandes internes et externes.


2 appels système.
3 bibliothèque.
4 fichiers spéciaux.
5 formats des fichiers et conventions.
6 jeux.
7 divers (y compris les macropaquets et les conventions).
8 gestion du système.
9 Interface du noyau Linux.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  64 / 391
manuel section

man 1 intro

INTRO ( 1 ) Manuel de l ’ u t i l i s a t e u r L i n u x

NOM
i n t r o − I n t r o d u c t i o n aux commandes
utilisateur

DESCRIPTION
La s e c t i o n 1 du manuel d e c r i t l e s commandes
e t o u t i l s de l ’ u t i l i s a t e u r , comme l e s u t i l i t a i r e s
de m a n i p u l a t i o n de f i c h i e r s , l e s i n t e r p r e t e u r s de
commandes , l e s c o m p i l a t e u r s , l e s n a v i g a t e u r s web ,
l e s e d i t e u r s e t o u t i l s de v i s u a l i s a t i o n de f i c h i e r s
e t d ’ images , e t c . . .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  65 / 391
manuel section

Exemple de boucle
f o r x i n { 1 . . 8 } ; do man $x i n t r o | g r e p i n t r o
; done

i n t r o − I n t r o d u c t i o n aux commandes u t i l i s a t e u r
i n t r o − I n t r o d u c t i o n a l a s e c t i o n des appels
systeme
i n t r o − I n t r o d u c t i o n aux f o n c t i o n s de
bibliotheque
i n t r o − I n t r o d u c t i o n aux f i c h i e r s s p e c i a u x .
i n t r o − I n t r o d u c t i o n a l a s e c t i o n Formats de
fichiers
i n t r o − I n t r o d u c t i o n aux j e u x
i n t r o − I n t r o d u c t i o n a l a s e c t i o n panoramas ,
conventions , et
i n t r o − I n t r o d u c t i Unix
Philippe Langevin (IMATH, USTV)
o net Programmation
aux commandesShell
d ’ Automne  66 / 391
manuel piège

puzzle
1 char ∗p=”char ∗p=%c%s%c;
2 main(){printf (p,34, p,34);} ”;
3 main(){printf(p,34, p,34);}
quine.c

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  67 / 391
manuel piège

puzzle
1 char ∗p=”char ∗p=%c%s%c;
2 main(){printf (p,34, p,34);} ”;
3 main(){printf(p,34, p,34);}
quine.c

t r ’\n ’ ’ ’ < quine . c > q . c


cat q . c

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  67 / 391
manuel piège

puzzle
1 char ∗p=”char ∗p=%c%s%c;
2 main(){printf (p,34, p,34);} ”;
3 main(){printf(p,34, p,34);}
quine.c

t r ’\n ’ ’ ’ < quine . c > q . c


cat q . c
c h a r ∗p=”c h a r ∗p=%c%s%c ; main ( ) { p r i n t f ( p , 3 4 , p
, 3 4 ) ; } ” ; main ( ) { p r i n t f ( p , 3 4 , p , 3 4 ) ; }

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  67 / 391
manuel piège

puzzle
1 char ∗p=”char ∗p=%c%s%c;
2 main(){printf (p,34, p,34);} ”;
3 main(){printf(p,34, p,34);}
quine.c

t r ’\n ’ ’ ’ < quine . c > q . c


cat q . c
c h a r ∗p=”c h a r ∗p=%c%s%c ; main ( ) { p r i n t f ( p , 3 4 , p
, 3 4 ) ; } ” ; main ( ) { p r i n t f ( p , 3 4 , p , 3 4 ) ; }
g cc q . c
. / a . out
c h a r ∗p=”c h a r ∗p=%c%s%c ; main ( ) { p r i n t f ( p , 3 4 , p
, 3 4 ) ; } ” ; main ( ) { p r i n t f ( p , 3 4 , p , 3 4 ) ; }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  67 / 391
manuel piège

hint

Trois consultations du manuel permettent de comprendre ce qui se


passe :
man tr pour obtenir des détails sur le filtre tr.
man printf pour le mode d’emploi de la fonction printf.
man ascii pour un mémo sur le codage des caractères.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  68 / 391
manuel piège

man ascii
man a s c i i | g r e p ’ 3 0 4 0 ’ −A12 | c u t −c26−

30 40 50 60 70 80 90 100 110 120


−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
0: ( 2 < F P Z d n x
1: ) 3 = G Q [ e o y
2: ∗ 4 > H R \ f p z
3: ! + 5 ? I S ] g q {
4: ” , 6 @ J T ˆ h r |
5: # − 7 A K U i s }
6: $ . 8 B L V ‘ j t ˜
7: % / 9 C M W a k u DEL
8: & 0 : D N X b l v
9: ’ 1 ; E O Y c m w
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  69 / 391
manuel piège

printf du C ? ?
man p r i n t f
PRINTF ( 1 ) U s e r Commands
NAME
p r i n t f − f o r m a t and p r i n t d a t a

SYNOPSIS
p r i n t f FORMAT [ARGUMENT ] . . .
p r i n t f OPTION

DESCRIPTION
P r i n t ARGUMENT( s ) a c c o r d i n g t o FORMAT, o r
e x e c u t e a c c o r d i n g t o OPTION :

−−h e l p d i s p l a y t h i s h e l p and e x i t
[printf dans(IMATH,
Philippe Langevin le web]
USTV) Unix et Programmation Shell Automne  70 / 391
manuel piège

printf du C !

man 3 p r i n t f

PRINTF ( 3 ) L i n u x Programmer ’ s
Manual

NAME
printf , fprintf , sprintf , snprintf , vprintf ,
vfprintf , v sp ri nt f , v s n p r i n t f − formatted
output conversion

SYNOPSIS
#i n c l u d e < s t d i o . h>

i n t p r i n t f ( c on st char ∗ format , . . . ) ;

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  71 / 391
manuel exercice

exercice
Utiliser le manuel pour expliquer :
man man | c o l −b | g r e p −E ’ ˆ [ A−Z]+$ ’
NAME
SYNOPSIS
DESCRIPTION
EXAMPLES
OVERVIEW
DEFAULTS
OPTIONS
ENVIRONMENT
FILES
HISTORY

man man | c o l −b | g r e p −Ex ’ [ A−Z]+ ’


Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  72 / 391
manuel exercice

man man | g r e p EXAMPLES −A24


EXAMPLES
man l s
D i s p l a y t h e manual page f o r t h e i t e m l s .
man −a i n t r o
Display , in succession , a l l of the a v a i l a b l e

man −k p r i n t f
S e a r c h t h e s h o r t d e s c r i p t i o n s and manual
page
names f o r t h e keyword p r i n t f a s r e g u l a r
e x p r e s s i o n . E q u i v a l e n t t o a p r o p o s −r p r i n t f
.
man −f s m a i l
Lookup t h e manual p a g e s r e f e r e n c e d by s m a i l
and p r i n t o u t t h e s h o r t d e s c r i p t i o n s o f any
f o u n d . E q u i v a l e n t t o w h a t i s −r s m a i l .
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  73 / 391
manuel exercice

man -k RE
man −k ’ [ a−z ] { 3 } p r i n t f ’ | c u t c1 −40
vasprintf (3) − p r i n t to a l l o c a t e
vfwprintf (3) − f o r m a t t e d wide−ch
vfwprintf (3 p ) − wide−c h a r a c t e r f o
vsnprintf (3) − formatted output
vsnprintf (3 p ) − format output of
vswprintf (3) − f o r m a t t e d wide−ch
vswprintf (3 p ) − wide−c h a r a c t e r f o

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  74 / 391
manuel exercice

man -k RE
man −k ’ [ a−z ] { 3 } p r i n t f ’ | c u t c1 −40
vasprintf (3) − p r i n t to a l l o c a t e
vfwprintf (3) − f o r m a t t e d wide−ch
vfwprintf (3 p ) − wide−c h a r a c t e r f o
vsnprintf (3) − formatted output
vsnprintf (3 p ) − format output of
vswprintf (3) − f o r m a t t e d wide−ch
vswprintf (3 p ) − wide−c h a r a c t e r f o
man −k ’ [ a−z ] { 3 } p r i n t f ’ | s e d ’ s / −.∗/@/ ’
vasprintf (3) @
vfwprintf (3) @
vfwprintf (3 p ) @
vsnprintf (3) @
vsnprintf (3 p ) @
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  74 / 391
manuel exercice

printf

man −f p r i n t f
p r i n t f (3 p ) − p r i n t formatted output
p r i n t f (3) − formatted output conversion
p r i n t f (1) − f o r m a t and p r i n t d a t a
p r i n t f (1 p ) − w r i t e formatted output
whatis printf
Il y a donc
une fonction printf
une commande printf

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  75 / 391
manuel exercice

attention !
/ bin / p r i n t f
/ b i n / p r i n t f : o p e r a n d e manquant
S a i s i s s e z / b i n / p r i n t f −−h e l p p o u r p l u s
d ’ informations .

cd / b i n

printf
p r i n t f : u t i l i s a t i o n : p r i n t f [− v v a r ]
format [ args ]

./ p r i n t f
. / p r i n t f : o p e r a n d e manquant
S a i s i s s e z . / p r i n t f −−h e l p p o u r p l u s
Philippe Langevin (IMATH, USTV)
d ’ informations .
Unix et Programmation Shell Automne  76 / 391
manuel exercice

piege classique

Les commandes homonymes font que le manuel ne renseigne pas


toujours sur la commande que l’on croit ! ! !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  77 / 391
manuel exercice

echo
man echo

ECHO( 1 ) U s e r Commands
NAME
echo − d i s p l a y a l i n e o f t e x t
SYNOPSIS
echo [ SHORT−OPTION ] . . . [ STRING ] . . .
echo LONG−OPTION
DESCRIPTION
Echo t h e STRING ( s ) t o s t a n d a r d o u t p u t .
−n do n o t o u t p u t t h e t r a i l i n g n e w l i n e
−e e n a b l e i n t e r p r e t a t i o n o f b a c k s l a s h
−E d i s a b l e i n t e r p r e t a t i o n o f b a c k s l a s h
−−h e l p d i s p l a y t h i s h e l p and e x i t
...
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  78 / 391
manuel exercice

help

echo −−h e l p
−−h e l p

w h i c h echo
/ b i n / echo

/ b i n / echo −−h e l p
U t i l i s a t i o n : / b i n / echo [ SHORT−OPTION ] . . .
ou : / b i n / echo LONG−OPTION
...

t y p e −f echo
echo e s t une p r i m i t i v e du s h e l l

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  79 / 391
manuel exercice

help
h e l p echo

echo : echo [−neE ] [ a r g . . . ]


e c r i t l e s arguments s u r l a s o r t i e standard .

A f f i c h e l e s ARGs s u r l a s o r t i e s t a n d a r d ,
s u i v i s d ’ un r e t o u r a l a l i g n e .

Options :
−n ne p a s a j o u t e r de s a u t de l i g n e
−e a c t i v e l ’ i n t e r p r e t a t i o n d e s b a r r e s
c o n t r e −o b l i q u e s d ’ echappement c i −d e s s o u s
−E s u p p r i m e e x p l i c i t e m e n t l ’ i n t e r p r e t a t i o n
l e s b a r r e s c o n t r e −o b l i q u e s d ’ echappement
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  80 / 391
manuel exercice

enable

echo −−h e l p
−−h e l p

e n a b l e −n echo

echo −−h e l p
U t i l i s a t i o n : echo [ SHORT−OPTION [ STRING ]
ou : echo LONG−OPTION

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  81 / 391
manuel exercice

enable, head, tail

e n a b l e | head −7
enable .
enable :
enable [
enable a l i a s
e n a b l e bg
enable bind
enable break

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  82 / 391
manuel exercice

enable, head, tail

e n a b l e | head −7
enable .
enable :
enable [
enable a l i a s
e n a b l e bg
enable bind
enable break

e n a b l e | t a i l −3
enable unalias
enable unset
enable wait

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  82 / 391
manuel exercice

liste des commandes internes

e n a b l e | s e d ’ s / ˆ [ ˆ ] ∗ / / ’ | t r ’ \ n ’ ’ ’ | f o l d −sw50
. : [ a l i a s bg b i n d b r e a k b u i l t i n c a l l e r cd
command compgen c o m p l e t e compopt c o n t i n u e
declare
d i r s d i s o w n echo e n a b l e e v a l e x e c e x i t e x p o r t
f a l s e f c f g g e t o p t s ha sh h e l p h i s t o r y j o b s k i l l
l e t l o c a l l o g o u t m a p f i l e popd p r i n t f pushd pwd
read readarray readonly return set s h i f t shopt
source suspend t e s t times trap true type t y p e s e t

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  83 / 391
manuel exercice

liste des commandes internes

e n a b l e | s e d ’ s / ˆ [ ˆ ] ∗ / / ’ | t r ’ \ n ’ ’ ’ | f o l d −sw50
. : [ a l i a s bg b i n d b r e a k b u i l t i n
caller
cd command compgen c o m p l e t e compopt
continue declare d i r s d i s o w n echo e n a b l e
eval exec e x i t export false fc fg getopts
ha s h h e l p h i s t o r y j o b s kill let local
l o g o u t m a p f i l e popd p r i n t f pushd pwd r e a d
readarray readonly return set s h i f t shopt
source suspend t e s t times trap true type
t y p e s e t u l i m i t umask u n a l i a s u n s e t w a i t

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  84 / 391
manuel exercice

exercice

Utiliser l’aide en ligne de commande pour expliquer la différence


entre :
echo −E ’ \ r e t o u \ r c h a \ r i o t ’
et
echo −e ’ \ r e t o u \ r c h a \ r i o t ’

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  85 / 391
manuel exercice

Utiliser le manuel pour comprendre les lignes :


f i n d ˜/CC −name ” ∗ . c ” −e x e c wc − l {} \ ; f o o \
| awk ’ BEGIN { s =0} { s=s+$0 } END { p r i n t s } ’

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  86 / 391
manuel format

iliv ?

man i l i v

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  87 / 391
manuel format

iliv ?

man i l i v

ILIV (6)

NAME
i l i v − u n i x and s h e l l p r o g r a m s

SYNOPSIS
i l i v [−h|−a ] [− l s e ] [− v t y p e ] [ l i s t ]

DESCRIPTION
iliv p r o v i d e s i n f o r m a t i o n s on t h e i n t r o d u c t i o n
t o GNU/ l i n u x s y s t e m and Bash p r o g r a m s c o u r s e

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  87 / 391
manuel format

.\" exemple de page


.\" cours I54 USTV 2012
.TH ILIV 6 "falling 2012" "I54 Manual"
.SH NAME
iliv \- unix and shell programs
.SH SYNOPSIS
iliv
[\fB-h\fP|\fB-a\fP] [\fB-lse\fP] [\fB-v\fP \fItype\fP] [ list ]
.SH DESCRIPTION
iliv provides informations on the introduction to GNU/linux system and Bash programs courses.
.SH OPTIONS
The following options are supported
.TP
\fB-a\fP \fB-h\fP displays help
.TP
\fB-l\fP lecturer
.TP
\fB-s\fP slides
.TP
\fP-e\fP ecue
.SH LICENCE
Copyleft (!c) 2012 by Pavle Michko.
.SH AUTHOR
michko@[Link]
.SH SEE ALSO
Joseph (kernel) Emmanuel (tcp/ip)
.SH BUG
please, report bugs administrative autority.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  88 / 391
manuel format

format ROFF

Les pages du manuels sont écrites dans le langage de formatage roff.


Un langage à balises plus léger que LATEX utilisé pour les pages du
manuel.
groff −man −T a s c i i i l i v . 6
si OK alors
cp i l i v . 6 / u s r / s h a r e /man / .
Pour en savoir plus,
man 7 roff

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  89 / 391
login

4 - login

console
login
user, root
connexion à distance
tour de l’hôte
mot de passe

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  90 / 391
login console

origine

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  91 / 391
login console

MITRA 15

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  92 / 391
login login

console réelle

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  93 / 391
login login

login

login initialise les variables :


HOME, SHELL (/etc/passwd)
USER, LOGNAME (/etc/passwd)
PATH (/usr/local/bin :/bin :/usr/bin)
MAIL (répertoire)
avant l’action du shell.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  94 / 391
login login

pseudo terminal

tty
/ d e v / p t s /2

f u s e r −av / d ev / p t s /2
UTIL . PID ACCES COMMANDE
/ dev / p t s / 2 : pl 1567 F . . . . x f c e 4 −t e r m i n a l
pl 3041 F . . . . b a s h

p s −o p p i d , comm 3041
PPID COMMAND
1567 b a s h

p s −o p p i d , comm 1567
PPID COMMAND
1 x f c e 4 −t e r m i n a l

p s −o p p i d , comm 1
PPID COMMAND
0 systemd

p s −o p p i d , comm 0
e r r o r : p r o c e s s ID o u t o f r a n g e

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  95 / 391
login user, root

root, user

L’administrateur root est habilité à créer les comptes utilisateurs


user à partir de :
nom de login
nom complet
Un jeu de commande d’administration permet à root de paramétrer
les comptes utilisateurs.
unicité du super-utilisateur pour unix.
sudo : permet de lancer une commande as root.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  96 / 391
login user, root

création d’un compte

] u s e r a d d t o t o −c ’ Mr Toto ’ −g novice
] l s − a l /home/ t o t o /
t o t a l 28
drwx−−−−−−. 4 t o t o n o v i c e 4096
drwxr −xr −x . 9 r o o t r o o t 4096
−rw−r−−r −−. 1 t o t o n o v i c e 18 . bash logout
−rw−r−−r −−. 1 t o t o n o v i c e 193 . bash profile
−rw−r−−r −−. 1 t o t o n o v i c e 124 . bashrc
drwxr −xr −x . 2 t o t o n o v i c e 4096 . gnome2
.bash{ logout, profile,rc} configuration du shell
VOIR AUSSI
passwd , c r y p t ( 3 ) , u s e r d e l ( 8 ) , usermod ( 8 ) .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  97 / 391
login user, root

.bash profile

1 # .bash profile
2 # Get the aliases and functions
3 if [ −f ˜/.bashrc ]; then
4 . ˜/.bashrc
5 fi
6 # User specific environment and startup programs
7 export PATH=$PATH:$HOME/bin:$HOME/script
8 export TEXINPUTS=$TEXTINPUTS:$HOME/texinput
9 export HISTFILESIZE=2048
10 export HISTSIZE=512
11 export HISTFILE=˜/.compil history
12 export PS1=”\t pl@\W>”

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  98 / 391
login user, root

.bashrc

# . bashrc
# Source g l o b a l d e f i n i t i o n s
i f [ −f / e t c / b a s h r c ] ; t h e n
. / etc / bashrc
fi
s e t −o v i
a l i a s s s h n a b =’ s s h l a n g e v i n @ n a b o o . u n i v −t l n . f r ’
a l i a s s s h g p u =’ s s h pl@imath −gpu . u n i v −t l n . f r ’
a l i a s sshm1 =’ s s h p l @ s e r v e u r −i ma th 01 . u n i v −t l n . f r ’
a l i a s sshm2 =’ s s h p l @ s e r v e u r −i ma th 02 . u n i v −t l n . f r ’
# etc . . .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  99 / 391
login user, root

/etc/passwd

l s −a l d /home/ t ∗
drwx−−−−−−. 4 t i t i n o v i c e /home/ t i t i
drwx−−−−−−. 4 t o t o n o v i c e /home/ t o t o
t a i l −2 / e t c / passwd
t o t o : x : 1 0 0 2 : 1 0 0 2 : Mr Toto : / home/ t o t o : / b i n / bas h
t i t i : x : 1 0 0 3 : 1 0 0 2 : Mr T i t i : / home/ t i t i : / b i n / bas h
] passwd t o t o
] m a i l t o t o @ o u e s t . f r −s compte << −FIN
> s a l u t toto ,
> v o t r e compte e s t a c t i v e !
> bye
> −FIN

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  100 / 391
login connexion à distance

configuration ssh

[ toto@ouest ˜] $ l s . ssh /
authorized keys known hosts

[ t o t o @ o u e s t ˜ ] $ s s h −k e y g e n

[ toto@ouest ˜] $ l s . ssh /
authorized keys id rsa i d r s a . pub known hosts

[ t o t o @ o u e s t ˜ ] $ s s h −copy−i d t u r i n g . e u p h o r i a . f r

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  101 / 391
login connexion à distance

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  102 / 391
login connexion à distance

configuration ssh

[ toto@ouest ˜] $ ssh turing . euphoria . n i l

[ t o t o @ t u r i n g ˜ ] $ p s t r e e −aulpG
init ,1
!−− sshd , 4 1 9 7
! !
! !−− sshd , 2 7 7 8 1
! !
! !−− sshd , 2 7 7 8 3 , t o t o
! !
! !−− bash , 2 7 7 8 4
! !
! !−− p s t r e e , 6 7 1 8 −aulpG
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  103 / 391
login connexion à distance

commande distante
ssh toto@turing . euphoria . n i l
...
[ t o t o @ t u r i n g ˜ ] $ p s t r e e −aulpG
init ,1
!−− sshd , 4 1 9 7
! !
! !−− sshd , 2 7 7 8 1
! !
! !−− sshd , 2 7 7 8 3 , t o t o
! !
! !−− bash , 2 7 7 8 4
! !
! !−− p s t r e e , 6 7 1 8 −aulpG

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  104 / 391
login connexion à distance

console virtuelle
ps −C m i n g e t t y −o p i d , cmd
PID CMD
1291 / s b i n / m i n g e t t y / dev / t t y 2
1295 / s b i n / m i n g e t t y / dev / t t y 4
2108 / s b i n / m i n g e t t y / dev / t t y 3
alt-ctrl-F3, ouvre une console.
l o g i n : p l passwd : −−−
[ p l ] ps −C m i n g e t t y
PID TTY TIME CMD
1291 t t y 2 [Link] mingetty
1295 t t y 4 [Link] mingetty

[ pl ] tty
/ dev / t t y 3
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  105 / 391
login connexion à distance

shell de login

[ p l ] b a s h −c ’ ps −f ; s l e e p 5 ’
UID PID PPID TTY CMD
p l 2257 2158 t t y 3 −ba sh
p l 2317 2257 t t y 3 ba sh −c ps −f ; s l e e p 5
p l 2318 2317 t t y 3 ps −f
le ’-’ indique un shell de login.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  106 / 391
login connexion à distance

getty

[ p l ] p s t r e e −ap | g r e p −A7 −e ’| − l o g i n ’ > t t y .


txt
[ pl ] exit

alt-ctrl-F1, ferme la console.

cat tty . txt


|− l o g i n , 2 1 0 8
| ‘−bash , 2 1 4 3
| |− grep , 2 1 7 6 −A7 −e |− l o g i n
| ‘−p s t r e e , 2 1 7 5 −ap
|− m i n g e t t y , 1 2 9 1 / dev / t t y 2
|− m i n g e t t y , 1 2 9 5 / dev / t t y 4

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  107 / 391
login tour de l’hôte

découverte de l’hôte

[ t o t o @ t u r i n g ˜ ] $ uname −a
Linux t u r i n g . euphoria . f r 2.6.18 −53.1.4. el5 . . .
i 3 8 6 GNU/ L i n u x

[ t o t o @ t u r i n g ˜ ] $ g r e p −c p r o c / p r o c / c p u i n f o
4

[ toto@turing ˜] $ lscpu
Architecture : i686
CPU op−mode ( s ) : 32− b i t
CPU( s ) : 2 Thread ( s ) p a r c o e u r : 2

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  108 / 391
login tour de l’hôte

découverte de l’hôte

uptime
1 8 : 0 0 : 5 5 up 14 days , 2 2 : 2 1 , 1 u s e r ,
load average : 1.37 , 0.61 , 0.33

f r e e −g
t o t a l used f r e e shared b u f f e r s cached
Mem: 47 30 16 0 0 29
−/+ b u f f e r s / c a c h e : 1 46
Swap : 72 0 72

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  109 / 391
login tour de l’hôte

accès au réseau

[ toto@turing ˜] $ cat / etc / r e s o l v . conf


search euphoria . f r
nameserver [Link]
[ toto@turing ˜] $ / sbin / i f c o n f i g eth0
e t h 0 L i n k E t h e r n e t HWaddr 0 0 : 1A : 6 4 : 3 4 : C3 : FA
i n e t adr : 1 0 . 1 . 6 5 . 7 2 Bcast : 1 0 . 1 . 2 5 5 . 2 5 5
Masque : 2 5 5 . 2 5 5 . 0 . 0
a d r i n e t 6 : f e 8 0 : : 2 1 a : 6 4 f f : f e 3 4 : c 3 f a /64 . . .
[ toto@turing ˜] $ / sbin / route
T a b l e de r o u t a g e IP du noyau
Destination P a s s e r e l l e Genmask I face
[Link] ∗ [Link] U eth0
default blackjack 0 . 0 . 0 . 0 UG e t h 0

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  110 / 391
login tour de l’hôte

stockage
[ t o t o @ t u r i n g ˜ ] $ d f −h
Sys . de f i c h . T a i l . Occ . D i s p . %Occ . Monte s u r
/ dev / mapper / r o o t v g −r o o t v o l
7 , 7G 6 , 6G 715M 91% /
/ dev / mapper / l u n s y s t e m p 1
99M 28M 66M 30% / b o o t
tmpfs 1014M 0 1014M 0% / dev /shm
/ dev / s d a 2 63G 1 , 2G 58G 2% / v a r / l o g
/ dev / mapper / bd vg−b d l v
764M 502M 263M 66% / bd
/ dev / mapper / webdata vg −w e b d a t a l v
90G 46G 45G 51% / webdata
/ dev / mapper / web vg−w e b l v
2 , 8G 1 , 8G 1015M 64% /www
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  111 / 391
login tour de l’hôte

who

[ t o t o @ t u r i n g ˜ ] $ whoami
toto
[ t o t o @ t u r i n g ˜ ] $ wc − l / e t c / passwd
141 / e t c / passwd
[ toto@turing ˜] $ w
1 1 : 4 1 : 4 1 up 23 days , 1 6 : 0 2 , 1 u s e r ,
l o ad average : 0 ,18 , 0 ,23 , 0 ,30
USER TTY FROM LOGIN@ WHAT
t o t o p t s /0 s o l 8 3 −−− 1 1 : 2 3 sshd : toto
[ t o t o @ t u r i n g ˜ ] $ l a s t −n3
toto p t s /0 e u p h o r i a Sep 10 1 1 : 2 3 still
michko p t s /0 s o l 8 3 −−− Sep 10 1 1 : 0 3 − 1 1 : 1 5
n i c o l a s p t s /0 pc−n i c o Sep 6 1 6 : 2 6 − 1 6 : 2 8

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  112 / 391
login tour de l’hôte

machine pour le calcul

[ t o t o @ i m a t h ˜ ] $ g r e p −c p r o c / p r o c / c p u i n f o
24
[ toto@imath ˜] $ top
2 1 : 5 3 : 5 3 up 102 days , l o a d a v e r a g e : 2 . 0 0 , 2 . 0 0 , 2 . 0 0
T a s k s : 431 t o t a l , 3 r u n n i n g , 428 s l e e p i n g , 0 z o m b i e
Cpu ( s ) : 8.3% us , 0.0% sy , 0.0% n i , 91.7% i d , 0.0%wa
Mem: 98986172 k t o t a l , 73171416 k used , 25814756 k f r e e
Swap : 76218360 k t o t a l , 100900 k used , 76117460 k f r e e

PID USER PR NI S %CPU %MEM TIME+ COMMAND


14855 pv 25 0 R 100.0 0.0 1 0 2 7 6 : 0 6 kpc
14856 pv 25 0 R 99.8 0.0 1 0 2 6 3 : 1 5 kpc
1 root 15 0 S 0.0 0.0 41:40.06 i n i t
2 root RT −5 S 0.0 0.0 0:00.24
3 root 34 19 S 0.0 0.0 0:00.10

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  113 / 391
login tour de l’hôte

sécurisation des password

[ t o t o @ t u r i n g ˜ ] $ who
t o t o p t s /0 2012−09−01 1 7 : 5 4 ( o u e s t . n e t )

[ t o t o @ t u r i n g ˜ ] $ t a i l −2 / e t c / passwd
t o t o : x : 1 0 0 2 : 1 0 0 2 : Mr Toto : / home/ t o t o : / b i n / bas h
t i t i : x : 1 0 0 3 : 1 0 0 2 : Mr T i t i : / home/ t i t i : / b i n / bas h

[ t o t o @ t u r i n g ˜ ] $ c a t / e t c / shadow
c a t : / e t c / shadow : P e r m i s s i o n non a c c o r d e e

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  114 / 391
login mot de passe

/etc/passwd et /etc/shadow
l s − a l t / e t c / passwd

−rw−r−−r −−. 1 r o o t r o o t . . . 1 7 : 1 3 / e t c / passwd


l s − a l t / e t c / shadow
−−−−−−−−−−. 1 r o o t r o o t . . . 1 7 : 1 3 / e t c / shadow

[ r o o t @ l o c a l h o s t ˜]# t a i l −2 / e t c / shadow
t o t o : $6$6gznwvTA$6cM . B8GJvlBYN0QRDnYRU6Px/QQCFoy
bKhbl3Vr4q7XmycL . LYzldXu9eBtaBNTiOGzkBmwDXkwfAj9
K4jaTT0 : 1 5 5 8 4 : 0 : 9 9 9 9 9 : 7 : : :

t i t i : $6$QMF37bGZ$NfVuIaWrmlCi /cuNaeM . UXHyO9ZS1yw


BieI1LXaxOhAURnW . BwtAGcy6HEpuF93yQt . mxoJd3Dq23Zu
KMkReA0 : 1 5 5 8 4 : 0 : 9 9 9 9 9 : 7 : : :
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  115 / 391
login mot de passe

permission
l s − a l t / e t c / passwd
−rw−r−−r −−. 1 r o o t r o o t . . . 1 7 : 1 3 / e t c / passwd

l s − a l t / e t c / shadow
−−−−−−−−−−. 1 r o o t r o o t . . . 1 7 : 1 3 / e t c / shadow

[ r o o t @ l o c a l h o s t ˜]# t a i l −2 / e t c / shadow
t o t o : $6$6gznwvTA$6cM . B8GJvlBYN0QRDnYRU6Px/QQCFoy
bKhbl3Vr4q7XmycL . LYzldXu9eBtaBNTiOGzkBmwDXkwfAj9
K4jaTT0 : 1 5 5 8 4 : 0 : 9 9 9 9 9 : 7 : : :

t i t i : $6$QMF37bGZ$NfVuIaWrmlCi /cuNaeM . UXHyO9ZS1yw


BieI1LXaxOhAURnW . BwtAGcy6HEpuF93yQt . mxoJd3Dq23Zu
KMkReA0 : 1 5 5 8 4 : 0 : 9 9 9 9 9 : 7 : : :
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  116 / 391
login mot de passe

man crypt
CRYPT( 3 ) Manuel du programmeur L i n u x
NOM c r y p t − C h i f f r a g e de d o n n e e s ou de mot de p a s s e

SYNOPSIS
#d e f i n e XOPEN SOURCE #i n c l u d e <u n i s t d . h>
c h a r ∗ c r y p t ( c o n s t c h a r ∗ key , c o n s t c h a r ∗ s a l t ) ;
e d i t i o n des l i e n s avec l ’ option −l c r y p t .
DESCRIPTION
La f o n c t i o n c r y p t e s t c e l l e u t i l i s e e p o u r
l e c r y p t a g e d e s mots de p a s s e .
NOTES
un c r y p t r o g r a m m e e s t de l a f o r m e
$id$salt$encrypted :
1 : MD5 . . . 5 : SHA−256 , 6 : SHA−512

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  117 / 391
login mot de passe

fonction à sens unique

Le système converve les cryptogrammes (empreintes)


L’utilisateur doit fournir le clair.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  118 / 391
login mot de passe

salage

Le salage aléatoire renforce la sécurité du système.


Le même passe conduit à des empreintes différentes.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  119 / 391
login mot de passe

hachage

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  120 / 391
login mot de passe

décryptage
1 #define XOPEN SOURCE /∗ See feature test macros(7)
∗/
2 #include <unistd.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <stdlib.h>
6 int main (int argc, char∗ argv[] )
7 {
8 char ∗res ;
9 res = crypt( argv[1], argv[2]) ;
10 if ( strcmp( argv[2], res ))
11 return 1;
12
13 return 0;
14 }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  121 / 391
login mot de passe

décryptage

: : g c c −Wall pwd . c
/tmp/ c c g s f Z q g . o : I n f u n c t i o n ‘ main ’ :
pwd . c : ( . t e x t +0x21 ) : u n d e f i n e d r e f e r e n c e t o ‘ c r y p t ’
c o l l e c t 2 : l d a r e t o u r n e 1 code d ’ e t a t d ’ e x e c u t i o n
: : g c c −Wall pwd . c − l c r y p t
: : . / a . o u t t o t o ’ $6$6gznwvTA$6cM . B8GJvlBYN0QRDnYRU
6Px/ QQCFoybKhbl3Vr4q7XmycL . LYzldXu9eBtaBNTiOGzkBmw
DXkwfAj9K4jaTT0 ’

: : echo $ ?
0

strcmp renvoie 0 en cas d’égalité


commande unix : 0 = succès ( true )
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  122 / 391
login mot de passe

cassage, charte

Une fois connu le mot de passe crypté, il reste possible de casser les
mots de passe faibles par la force brute . . .
/etc/shadow est un anti-cracker !
[John the Ripper]

déontologie : Un utilisateur unix signe une charte qui stipule qu’un


mot de passe est strictement personnel.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  123 / 391
bash

5 - bash
ligne de commande
analyse
quote
expansion
fonction et tableau
commandes
pipeline
commandes séquentielles
alternative
test
itérations
choix multiple
menus
options
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  124 / 391
bash ligne de commande

Edition
Bash utilise la bibliothèque readline qui inclut la complétion
automatique des noms de commandes et de fichiers (tabulation) ainsi
que la navigation dans l’historique des commandes.
set pemet de sélectionner un éditeur : vi, emacs (défaut ).
8 Command Line Editing
readline emacs vi
beginning-of-line ctrl-a 0
end-of-line ctrl-e $
clear-screen ctrl-l
reverse-search-history ctrl-r
forward-search-history ctrl-s
kill-line ctrl-k d$
backward-kill-line ctrl-x Rubout d0
unix-line-discard ctrl-u dd
unix-word-rubout ctrl-w dw
yank ctrl-y p
display-shell-version ctrl-x C-v

set -o vi
set -o emacs
bind, .inputrc
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  125 / 391
bash ligne de commande

readline
1 static char ∗ligne = (char ∗) NULL;
2 char ∗nligne (void) {
3 if (ligne ) {
4 free (ligne );
5 ligne = (char ∗) NULL;
6 }
7 ligne = readline (”prompt:”);
8 if (ligne && ∗ligne)
9 add history (ligne );
10 return (ligne );
11 }
12 int main(void) {
13 while ( strcmp(nligne () , ”quit ”));
14 return 0;
15 }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  126 / 391
bash analyse

traitement des commandes

Le prompt du shell matérialise une ligne de commande invitant


l’utilisateur à soumettre une instruction : une chaine de caractères
analysée par le shell pour lancer des commandes.
interne : traitée dans le processus.
externe : clone + execve.
complexe : clone
1 1 : 4 7 p l @ m i c / s c r i p t > echo $PS1
\A pl@$MACHINE/\W>

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  127 / 391
bash analyse

boucle du shell

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  128 / 391
bash analyse

Interprétation des lignes

bash segmente la ligne en mots (tokens), le premier mot est


généralement une commande :
1 alias
.bashrc
alias
2 commande interne
enable
3 binaire
variable PATH
which
les autres arguments sont des options ou paramètres de la commande.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  129 / 391
bash analyse

what’s for ?
Un exemple proposé par Chet Ramey :
1 for for in for; do for=for; done; echo $for

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  130 / 391
bash analyse

what’s for ?
Un exemple proposé par Chet Ramey :
1 for for in for; do for=for; done; echo $for

Nous ne tenterons pas de percer les mystères de la grammaire du


shell bash, tout au plus quelques points extraits du manuel :
wget h t t p : / /www. gnu . o r g / s o f t w a r e / bas h / manual /
b a s h . html
man b a s h
Ne sont pas vraiment abordés ici :
les fonctions,
les tableaux,
les tableaux associatifs.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  130 / 391
bash analyse

jeux de caractères
Méta-caractères (séparateurs) :
| & ; ( ) < >
Opérateurs de contrôle :
| |& || && ; &
Opérateurs de redirection :
< << > >> >& <<<
Paramètres spéciaux :
∗ @ # ? $ ! 0 ˜
Mots réservés :
1 ! case do done elif else esac fi for function if
2 in select then until while { } time [[ ]]
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  131 / 391
bash quote

apostrophe

Les protections permettent de forcer l’interpréteur à ignorer la


signification spéciale de certains caractères ou mots. Les protections
peuvent être utilisées pour empêcher le traitement des caractères
spéciaux, éviter la reconnaissance des mots-réservés ou empêcher le
développement des paramètres. Il y a trois mécanismes de
protection :
le caractère d’échappement (antislash)
les apostrophes (quote)
les guillemets (double-quote)

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  132 / 391
bash quote

quoting

\ protége le caractère qu’il précède.


les apostrophes protégent une chaı̂ne de caractères.
entre deux guillemets :
$ est toujours actif.
\ affecte
$ \ ” <n l >

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  133 / 391
bash quote

cow quotes

cowsay −TU ’ how t o q u o t e ? ’

< how t o q u o t e ? >


−−−−−−−−−−−−−−−−
\ ˆ ˆ
\ ( oo ) \
( )\ ) \/\
U ||−−−−w |
|| ||

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  134 / 391
bash quote

cow explains how to quote

1 #!/bin/bash −v
2 x=quote; cowsay −T\\/ ”how to ’$x’ ?”

#!/ b i n / b a s h −v
x=q u o t e ; cowsay −T\\/ ”how t o ’ $x ’ ?”

< how t o ’ quote ’ ? >


−−−−−−−−−−−−−−−−−−
\ ˆ ˆ
\ ( oo ) \
( )\ ) \/\
\/ ||−−−−w |
|| ||

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  135 / 391
bash quote

quotes

cowsay −f s m a l l ’ ” $$ ” ’ ” $HISTSIZE ” ”\ $$ ”

< ” $$ ” 512 $$ >


−−−−−−−−−−−−−
\ , ,
\ ( oo )
( ) )\
|| − −|| ∗

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  136 / 391
bash quote

digression
1 #!/bin/bash −v
2 z=hello
3 printf −v z ”%s $USER” $z
4 echo $z
5 hello pl
6 man ascii | grep −o ’[0−9][0−9 ]∗A$’
7 101 65 41 A
8 x=A
9 printf ”%3o %2x %3d %s” \’$x \”$x ”’$x” $x
10 101 41 65 A z=65
11 printf −vx ”0%3o” $z
12 echo −e ”\\$x”
13 A
14 printf \\$(printf ”%03o” $z)
15 printf ”%03o” $z) Unix et Programmation Shell
Philippe Langevin (IMATH, USTV) Automne  137 / 391
bash quote

Analyse des commandes

1 Lecture : fichier, chaine, terminal


2 Analyse lexicale : application des quotes, suite de tokens
(opérateur, mot ) séparés par des métacaractères.
3 Traitement des alias.
4 Analyse syntaxique des commandes.
5 Expansion des tokens : noms de fichiers, commandes et
arguments.
6 Traitement des redirections
7 Exécution des commandes.
8 Terminaison des fils, status.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  138 / 391
bash expansion

expansion des tokens

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  139 / 391
bash expansion

{a,b,c,...} : accolade (brace)

1 #!/bin/bash
2 for x in {alice , eve, bob}.{X,Y}
3 do
4 touch /tmp/$[Link]
5 done
6 ls /tmp/[a−z]∗.[XYZ]∗.txt

/tmp/ a l i c e . X . t x t
/tmp/ a l i c e . Y . t x t
/tmp/ bob . X . t x t
/tmp/ bob . Y . t x t
/tmp/ e v e . X . t x t
/tmp/ e v e . Y . t x t

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  140 / 391
bash expansion

{1..n} : enumération

1 #!/bin/bash
2 if [ ! −f /tmp/[Link] ] ; then
3 for x in {1..254} ; do
4 host 193.49.96. $x
5 done | grep −v nat > /tmp/[Link]
6 fi
7 cut −d ’ ’ −f 1,5 < /tmp/[Link] | head −5

1 . 9 6 . 4 9 . 1 9 3 . i n −a d d r . a r p a r h o d e s . u n i v −t l n . f r .
2 . 9 6 . 4 9 . 1 9 3 . i n −a d d r . a r p a m a i l . u n i v −t l n . f r .
3 . 9 6 . 4 9 . 1 9 3 . i n −a d d r . a r p a l o r c a n e . u n i v −t l n . f r .
4 . 9 6 . 4 9 . 1 9 3 . i n −a d d r . a r p a dpt−i n f o . u n i v −t l n . f r .
5 . 9 6 . 4 9 . 1 9 3 . i n −a d d r . a r p a s e r e c o m . u n i v −t l n . f r .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  141 / 391
bash expansion

tilde

1 #!/bin/bash −v
2
3 echo −n ˜{alice,pl , bob,guest}
4 ˜alice /home/pl ˜bob /home/guest
5 for gus in {alice , pl , bob,guest}
6 do
7 echo ˜$gus
8 done
9 ˜alice
10 ˜pl
11 ˜bob
12 ˜guest

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  142 / 391
bash expansion

argument et paramètre de position

1 #!/bin/bash −v
2 echo $0 : $∗
3 set a b c
4 echo $∗
5 while [ $# −gt 0 ]; do
6 echo $1 : $∗
7 shift
8 done

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  143 / 391
bash expansion

décalage des paramètres de position


1 #!/bin/bash −v
2 echo $0 : $∗
3 ./ shift . sho :
4 set a b c
5 echo $∗
6 a bc
7 while [ $# −gt 0 ]; do
8 echo $1 : $∗
9 shift
10 done
11 a : a bc
12 b: bc
13 c : c

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  144 / 391
bash expansion

tri des arguments

1 #!/bin/bash
2 if [ $# = 0 ] ; then
3 set 2 1 4 3 6 5 8 7
4 fi
5 echo $∗ | tr ’ ’ ’ \n’ \
6 | sort −n | tr ’ \n’ ’ ’

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  145 / 391
bash expansion

paramètres spéciaux

1 #!/bin/bash −v
2 echo opt=$− pid=$$
3 opt=hvB pid=2615
4 bash −c ’echo child =$$’ &
5 echo hello > /tmp/spec
6 echo $?
7 0
8 echo hello > /root/tmp
9 ./ spec. sho: line 6: /root/tmp: Permission non accordee
10 echo $? $!
11 1 2617
12 child =2617

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  146 / 391
bash expansion

séparateur interne de champs


1 #!/bin/bash −v
2 set gnu is not unix
3
4 echo ”$∗”
5 gnu is not unix
6 echo ”$@”
7 gnu is not unix
8
9 IFS=:
10
11 echo ”$∗”
12 gnu:is : not: unix
13 echo ”$@”
14 gnu is not unix
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  147 / 391
bash expansion

danger !
39 echo h e l l o
40 touch t h i s
Le caractère ! est utilisé : 41 echo coucou
opérateur logique : != 42 cat f i l e
43 history
pid dernier job $ !
!39
indirection ${ !. . . } echo h e l l o
historique ! !−5
touch t h i s
! ec
echo h e l l o
!? f i l e
cat f i l e
ˆ f i l e ˆ foo ˆ
Philippe Langevin (IMATH, USTV) c a t Shell
Unix et Programmation foo Automne  148 / 391
bash expansion

nom de fichier

Une expression contenant un des

[ * ] ?

donne la liste des noms de fichiers du répertoire courant qui sont en


correspondance avec l’expression :
* : chaine arbitraire
[] : ensemble
? : caractère
Absence de correspondance : attention !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  149 / 391
bash expansion

filename

1 #!/bin/bash −v
2 if [ ! −d tmp ] ; then mkdir tmp ;fi
3 cd tmp
4 touch abc
5 touch cba
6 echo a[abc]b
7 a[ abc]b
8 echo a[abc]c
9 abc
10 shopt −s failglob
11 echo a[abc]b
12 ./ filename . sho: line 9: Pas de correspondance : a[ abc]b

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  150 / 391
bash expansion

$( commande )

1 #!/bin/bash −v
2
3 man −s 1 −f bc
4
5 res =$( bc <<< ”2ˆ(2ˆ5) + 1” )
6
7 factor $res

Il existe une syntaxe synomyme à base d’anticotes.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  151 / 391
bash expansion

$(( arithmétique ))

1 #!/bin/bash −v 1 #!/bin/bash −v
2 x=010 2
3 y=2 3 echo $(( 2#1000000 ))
4 echo $(( x ∗ y )) 4 64
5 16 5 echo $(( 16#abcdef ))
6 6 11259375
7 let y++ 7
8 echo $y 8x=$(( 16#abcdef ))
9 3 9echo $( bc <<< ”obase=16; $x”
10 )
11 let z=x∗y 10 bc <<< ”obase=16; $x” )
12 echo $z 11 bc <<< ”obase=16; $x”
13 24 12 ABCDEF

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  152 / 391
bash expansion

${parameter : [-+= ?] }
1 #!/bin/bash −v
2 echo ${foo:−hello world}
3 hello world
4 echo ${bar:=hello world}
5 hello world
6 echo foo=$foo bar=$bar
7 foo= bar=hello world
8 echo ${bar:+salut tout le monde}
9 salut tout le monde
10 echo ${bar:?}
11 hello world
12 echo ${foo:?}
13 ./ para1. sho: line 7: foo : parametre vide ou non defini

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  153 / 391
bash expansion

chaine,sous-chaine,prefixe,suffixe
1 #!/bin/bash −v
2 str =’Hello everybody out there using minix’
3 echo ${str:6}
4 everybody out there using minix
5 echo ${str:6:10}
6 everybody
7 # sharp prints suffixe
8 echo ${str#∗y}
9 body out there using minix
10 echo ${str##∗y}
11 out there using minix
12 # percent prints prefixe
13 echo ${str%%o∗} ${str%o∗}
14 Hell Hello everybody
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  154 / 391
bash expansion

${parameter/motif/remplace}
1 #!/bin/bash −v
2 claim=’I do not believe everybody should learn to code’
3 echo ${claim/d∗t /really \ }
4 I really believe everybody should learn to code
5 echo ${claim//d∗t/sometime d}
6 I sometime do code
7 echo \$\{str{ˆ,ˆˆ,\,,\,\,} pat\}
8 ${str ˆpat} ${str ˆˆpat} ${str , pat} ${str ,, pat}
9 claim=${claimˆˆ∗}
10 echo ${claim/#D∗T/}
11 I DO NOT BELIEVE EVERYBODY SHOULD LEARN TO
CODE
12 echo ${claim/#I∗Y/YOU} BASH!
13 YOU SHOULD LEARN TO CODE BASH!
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  155 / 391
bash expansion

${!variable} ${!prefixe} : déréférencement !


f o o=h e l l o ; p t r=f o o ; echo $ { ! p t r }
hello
echo $ { !H∗}
HISTCMD HISTCONTROL HISTFILE HISTFILESIZE
HISTSIZE HOME HOSTNAME HOSTTYPE
env | g r e p HIST
HISTSIZE=512
HISTFILESIZE =2048
HISTCONTROL=i g n o r e d u p s
HISTFILE=/home/ p l / . c o m p i l h i s t o r y
Bash :

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  156 / 391
bash expansion

${!variable} ${!prefixe} : déréférencement !


f o o=h e l l o ; p t r=f o o ; echo $ { ! p t r }
hello
echo $ { !H∗}
HISTCMD HISTCONTROL HISTFILE HISTFILESIZE
HISTSIZE HOME HOSTNAME HOSTTYPE
env | g r e p HIST
HISTSIZE=512
HISTFILESIZE =2048
HISTCONTROL=i g n o r e d u p s
HISTFILE=/home/ p l / . c o m p i l h i s t o r y
Bash :
f o r x i n $ { ! HIST ∗ } ; do echo $x=$ { ! x } ; done
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  156 / 391
bash fonction et tableau

fonction
1 #!/bin/bash
2 function chr {
3 printf \\$( printf ’ %03o’ $1 )
4 }
5 function ord {
6 printf ’ %d’ ”’$1”
7 }
8
9 for x in $∗ ; do
10 echo −ne \\t$x: ; ord $x
11 done

. / f o n c t i o n . sho {A . . E}
A: 6 5 B: 6 6 C:67 D: 6 8 E:69
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  157 / 391
bash fonction et tableau

globale par défaut


1 #!/bin/bash −v
2 foo=globale
3
4 function myproc {
5 local foo=locale
6 echo $foo
7 echo $bar
8 }
9
10 bar=$foo
11
12 myproc
13 locale
14 globale
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  158 / 391
bash fonction et tableau

tableau
1 #!/bin/bash −v
2 week=(lundi mardi mercredi jeudi vendredi samedi dimanche)
3 echo x=$week bad=$week[1] good=${week[1]}
4 x=lundi bad=lundi[1] good=mardi
5 echo dim:{#week[∗]} val:${week[∗]}
6 dim:{#week[∗]} val:lundi mardi mercredi jeudi vendredi
samedi dimanche
7 echo ind:${!week[∗]}
8 ind:0 1 2 3 4 5 6
9 for i in ${!week[∗]} ; do
10 day=${week[i]}
11 echo −n ${day:0:1}
12 done
13 lmmjvsd
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  159 / 391
bash fonction et tableau

tableau associatif

1 #!/bin/bash
2 declare −A count
3 for w in $( cat $0 | sed ’ s/[ˆa−z]/\n/g’ ) ; do
4 let count[$w]++
5 done
6
7 for w in ${!count[@]} ; do
8 echo −n ’ ’$w:${count[$w]}
9 done | fold −sw40

do : 2 l e t : 1 d e c l a r e : 1 ba sh : 1 done : 2
b i n : 1 f o l d : 1 c o u n t : 4 echo : 1 c a t : 1 s e d : 1
a : 1 i n : 2 g : 1 n : 2 s : 1 f o r : 2 w: 5 z : 1 sw : 1

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  160 / 391
bash commandes

types de commandes

Une commande composée d’arguments i.e. echo a b c est une


commande simple à partir desquelles on peut construire des
commandes complexes :
pipelines (tube)
listes (batch)
composée (contrôle)
Coprocesses Two-way communication between commands.
GNU Parallel Running commands in parallel.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  161 / 391
bash commandes

commande simple

En général, la commande est spécifiée par le premier mot, les


autres sont les arguments de la commande.
Un signal affecte la valeur de retour :

128 + signal

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  162 / 391
bash pipeline

[time [-p]] [ !] cmd1 [ [ | ou |& ] cmd2 ...]


Un pipeline est une suite de commandes simples separées par un
opérateur de contrôle :
‘ | ’ ou ‘ |& ’.
La sortie de cmd1 est connectée par un tube vers l’entrée de
cmd2 .
Autrement dit, cmd2 lit dans la sortie de cmd1 .
La connexion est réalisée avant l’évaluation des redirections.
Avec ‘ |& ’, le canal d’erreur de cmd1 est dirigé vers l’entrée de
cmd2 .
Il s’agit d’un raccourci pour :
cmd1 2>&1 | cmd2
Cette redirection implicite est réalisée aprés l’évaluation des
redirections.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  163 / 391
bash pipeline

exemple de pipeline

man b a s h | s e d ’ s / [ ˆ A−Z ] / \ n/g ’ | \


g r e p −E ’ [ A−Z ] { 3 } ’ | s o r t | u n i q −c | s o r t −n r
54 BASH
42 SHELL
29 BUILTIN
27 COMMANDS
21 PATH
21 IFS
18 COMP
16 POSIX
13 EXPANSION
13 ENV
11 NAME

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  164 / 391
bash commandes séquentielles

Liste de commandes
Une liste de commandes est un enchainement de pipelines séparés par
un des opérateurs :
‘ ;’ ‘&’ ‘&&’ ‘ || ’
qui se termine éventuellement par ‘ ;’ ou ‘&’, ou ’ nl ’.
Les opérateurs ‘&&’ et ‘ || ’ ont la même précédence, et sont
prioritaires aux deux autres ‘ ;’ et ‘&’.
Une commande qui se termine par ‘&’ est exécutée en arrière
plan (exécution asynchrone) dans un sous-shell. Le shell n’attend
pas la terminaison de la commande, le code est 0 (true).
L’entrée standard est par défaut /dev/null.
Les commandes séparés par des ‘ ;’ sont exécutées
séquentiellement. Le shell attend la terminaison de chacune des
commandes à tour de rôle.
La valeur de retour correspond au status de la dernière
Philippe commande.
Langevin (IMATH, USTV) Unix et Programmation Shell Automne  165 / 391
bash commandes séquentielles

liste conditionnelle

Il s’agit des séquences séparées par des ‘&&’ ou bien des ‘ || ’.


Dans une conjonction :

cmd1 && cmd2

cmd2 est exécutée si et seulement si le retour de cmd1 est OK.


Dans une disjonction :

cmd1 —— cmd2

cmd2 est exécutée si et seulement si le retour de cmd1 est KO.


Dans les deux cas, la valeur de retour sera bien celle de la dernière
commande exécutée.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  166 / 391
bash commandes séquentielles

exemple
1 #!/bin/bash −v
2 help time | sed −nE ’/[pP]osix/s/[[: space:]]+/ /p’
3 −p print the timing summary in the portable Posix format
4 time −p (sleep 1 && sleep 2 && sleep 3)
5 real 6.00
6 user 0.00
7 sys 0.00
8 time −p (sleep 1 || sleep 2 || sleep 3)
9 real 1.00
10 user 0.00
11 sys 0.00
12 time −p (sleep 1 & sleep 2 & sleep 3)
13 real 3.00
14 user 0.00
15 sys 0.00
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  167 / 391
bash commandes séquentielles

(liste)
exécutée dans un sous-shell sans effet sur l’environnement.
1 #!/bin/bash −v
2 x=HELLO
3 echo x=$x s=$BASH SUBSHELL
4 x=HELLO s=0
5 ( x=${x,,∗}; echo x=$x s=$BASH SUBSHELL; )
6 x=hello s=1
7 echo x=$x s=$BASH SUBSHELL
8 x=HELLO s=0

( cd /tmp ; pwd ) ; pwd


/tmp
/home/ p l

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  168 / 391
bash commandes séquentielles

{liste ;}

exécutée avec l’environnement du shell en cours !


1 #!/bin/bash −v
2 x=hello
3 echo x=$x s=$BASH SUBSHELL
4 x=hello s=0
5 { x=${xˆˆ∗}; echo x=$x s=$BASH SUBSHELL; }
6 x=HELLO s=0
7 echo x=$x s=$BASH SUBSHELL
8 x=HELLO s=0

1 :: { echo hello; echo world } >> message

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  169 / 391
bash alternative

if test-cmd ; then cmd0 ;[else cmd1 ;]fi


Si le code de retour de test-cmd est nul alors cmd0 est exécutée
sinon c’est cmd1 .
1 if [ −n HOST ] ; then
2 if ping −c1 $[Link] ; then
3 ssh pl@$[Link] who
4 else
5 echo $HOST is down
6 fi
7 fi

Les commandes [. . .] et [[. . .]] sont utilisées pour construire des tests.
[ ] test simple, détaillé ici.
[[ ]] voir le manuel.
elif construction est possible.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  170 / 391
bash test

help test

-d file répertoire
-f file fichier régulier
-p file pipe, fifo
-x file exécutable
-N file modifié depuis dernier accès
-o optname option du shell activée
-v varname variable assignée
-z string chaine vide
-n string chaine non vide

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  171 / 391
bash test

test unaire
1 #!/bin/bash −v
2 # 0 : SUCCES
3 # 1 : FAILURE
4 unset s
5 [ −z ”$s” ]; echo $?
6 0
7 [ −n ”$s” ]; echo $?
8 1
9 s=initialisation
10 [ ! −z ”$s” ] && echo non vide
11 non vide
12 [ −n ”$s” ] && echo init
13 init

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  172 / 391
bash test

test binaire
file1 -nt file2 file1 est plus récent que file2
file1 -ot file2 file1 est plus ancien que file2
str1 = str2 égalité des chaines
str1 != str2 chaines différentes.
str1 < str2 comparaison lexicographique
str =∼ pat correspondance
arg1 ♣ arg2 comparaison arithmétique
♣ : ‘-eq’, ‘-ne’, ‘-lt’, ‘-le’, ‘-gt’, or ‘-ge’.

$ [ ” x ” = ” x ” ] ; echo $ ? −−> 0
$ [ ” x ” < ” y ” ] ; echo $ ? −−> 1
ba s h : y : Aucun f i c h i e r ou d o s s i e r de c e t y p e
$ [ [ ” x ” < ” y ” ] ] ; echo $ ? −−> 0
$ [ [ a z e r t y =˜ a . ∗ y ] ] ; echo $ ? −−> 0
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  173 / 391
bash test

test binaire
1 #!/bin/bash −v
2 x=’1234’
3 y=’ 1234’
4 if [ ”$x” = ”$y” ] ; then
5 echo egalite
6 else
7 echo difference
8 fi
9 difference
10 if [ $x = $y ] ; then
11 echo egalite
12 else
13 echo difference
14 fi
15 egalite
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  174 / 391
bash test

expression logique

! expr négation de expr


( expr )
expr1 -a expr2 et logigue
expr1 -o expr2 ou logique

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  175 / 391
bash test

expression logique
1 #!/bin/bash −v
2 function transfert {
3 ls −lt $2 $1/$2
4 if [ −d $1 −a −f $2 −a ”$2” −nt ”$1/$2” ] ; then
5 cp −f $2 $1/$2
6 fi
7 }
8 echo hello > /tmp/h
9 sleep 60
10 echo Hello > h
11 transfert /tmp h
12 −rw−rw−r−− 1 pl pl 6 20 juin 08:24 h
13 −rw−rw−r−− 1 pl pl 6 20 juin 08:23 /tmp/h
14 transfert /tmp h
15 −rw−rw−r−− 1 pl plUnix
Philippe Langevin (IMATH, USTV)
6 et20Programmation
juin 08:24 Shell
/tmp/h Automne  176 / 391
bash itérations

while test-cmds ; do seq-cmds ; done

Exécute la suite de commandes tant que le code de retour de


test-commands vaut zéro. Le code de retour est celui de la dernière
commande exécutée.
1 while ping −c1 −W1 [Link]; do
2 echo alive
3 sleep 60
4 done

les ” ;” optionnel deviennent obligatoires sur une ligne !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  177 / 391
bash itérations

L’inévitable factorielle !
1 declare −i n=1
2 r =1 ; z=1
3 # comparaison des chaines
4 while [ $r == $z ]
5 do
6 # n est entier
7 n=n+1
8 # r non entier
9 let r =r∗n
10 z=$( bc <<< ”$z∗$n” )
11 done
12 echo n=$n $r $z

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  178 / 391
bash itérations

L’inévitable factorielle !
1 declare −i n=1
2 r =1 ; z=1
3 # comparaison des chaines
4 while [ $r == $z ]
5 do
6 # n est entier
7 n=n+1
8 # r non entier
9 let r =r∗n
10 z=$( bc <<< ”$z∗$n” )
11 done
12 echo n=$n $r $z

1 n=21 −4249290049419214848 51090942171709440000


Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  178 / 391
bash itérations

L’inévitable factorielle !

1 #!/bin/bash
2 z=$( \
3 bc << −EOJ
4 r =1
5 for( n=1 ; n < 50; n++ )
6 r =r∗n
7 print r
8 −EOJ
9 )
10 echo $z

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  179 / 391
bash itérations

while et read
La commande read utilise le premier caractère de la variable IFS
pour découper les lignes d’un fichier :
1 #!/bin/bash
2 IFS=:
3 while read user x uid z
4 do
5 if [ $uid −ge 1000 ]
6 then
7 echo $user
8 fi
9 done < /etc/passwd
mais une commande sait faire cela, laquelle ?

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  180 / 391
bash itérations

while et read
La commande read utilise le premier caractère de la variable IFS
pour découper les lignes d’un fichier :
1 #!/bin/bash
2 IFS=:
3 while read user x uid z
4 do
5 if [ $uid −ge 1000 ]
6 then
7 echo $user
8 fi
9 done < /etc/passwd
mais une commande sait faire cela, laquelle ?
[]$ gawk −F : ’ { i f ( $3 >=1000) p r i n t $1 } ’ / e t c /
passwd
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  180 / 391
bash itérations

for name [ [in [words...] ] ; ] do cmds ; done


expansion de words
exécution des commandes
1 #!/bin/bash
2 set a b c
3 for x ; do echo −n $x; done
4 for x in ∗ ; do echo −n $x; done
5 for x in $( cat $0 ); do echo −n $x; done
6 for x in alpha beta gamma ;
7 do
8 echo −n $x;
9 done

pas de in words est spécial.


Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  181 / 391
bash itérations

for (( expr1 ; expr2 ; expr3 )) ; do cmds ; done


Avec un comportement similaire à la bouble for du langage C :
l’expression arithmétique expr1 est évaluée, puis celle de expr3 tant
que expr2 n’est pas nulle.
1 deb=$1
2 lim=$2
3 pas=1
4 if [ $# = 3 ] then
5 pas=$3
6 fi
7
8 for (( x=deb; x<lim ; x+=pas ));
9 do
10 echo $x;
11 done
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  182 / 391
bash itérations

Chronométrage
1 deb=$1 ; lim=$2 ; pas=$3 ; cmd=$4
2 if [ $# != 4 ] ; then
3 echo usage $0 : deb lim pas cmd
4 exit 1
5 fi
6 if [ −f time. log ] ; then
7 echo effacer time. log
8 exit 2
9 fi
10 for (( x=deb; x<lim ; x+=pas )) ; do
11 echo −n .$x
12 /usr/bin/time −a −o [Link] −−format=”$x %e” $cmd $x
13 done
gnuplot...
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  183 / 391
bash choix multiple

case wd in [ [(] x [ | x]...) cmd-list ; ;]...esac


case exécute la liste de commandes correspondant au premier motif
correspondant.
| sépare les motifs
) termine les motifs
Chaque clause se termine par :
‘ ; ;’ ‘ ;&’ ‘ ; ;&’.
1 echo −n ”Enter the name of an animal: ”
2 read ANIMAL
3 echo −n ”The $ANIMAL has ”
4 case $ANIMAL in
5 horse | dog | cat) echo −n ”four”;;
6 man | kangaroo ) echo −n ”two”;;
7 ∗) echo −n ”an unknown number of”;;
8 esac
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  184 / 391
bash menus

select name [in words...] ; do cmds ; done


Une liste d’items est contruite à partir de la suite words. Elle est
placée sur la sortie standard. L’usager est PS3-invité à faire un choix
passé dans la variale REPLY.
1 mkdir /tmp/dir
2 rm −rf /tmp/dir/∗
3 touch /tmp/dir/{a..h}
4 select fname in /tmp/dir/∗;
5 do
6 index=$REPLY
7 break;
8 done
9 echo −e ”\nselection: $fname ($index)”
10 echo −−−

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  185 / 391
bash menus

1 ) /tmp/ d i r / a 3 ) /tmp/ d i r / c
5 ) /tmp/ d i r / e 7 ) /tmp/ d i r /g
2 ) /tmp/ d i r /b 4 ) /tmp/ d i r /d
6 ) /tmp/ d i r / f 8 ) /tmp/ d i r /h
#?
s e l e c t i o n : /tmp/ d i r /g ( 7 )
−−−
s e l e c t . o u t : s e l e c t . sh
echo 7 | . / s e l e c t . sh \
|& f o l d −s −w30 > s e l e c t . o u t

s e d −n ’ / s e l e c t . o u t / , / c l e a n /p ’ \
m a k e f i l e >> s e l e c t . o u t
clean :

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  186 / 391
bash options

getopts optstring name [args]

La commande getopts permet de gérer des options passées par la


ligne de commande :
optstring les options à reconnaitre, avec argument ou pas.
name option courante.
OPTIND indice de l’argument suivant.
OPTARG argument de l’option.
Traitement des erreurs
le drapeau OPTERR contrôle les messages d’erreurs.
idem ’ :’ préfixe optstring.
name vaut ’ ?’ pour une option inconnue.
name vaut ’ :’ pour un argument attendu.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  187 / 391
bash options

utilisation de getopt
1 #!/bin/bash
2 while getopts ”:hp:r: ” opt; do
3 case $opt in
4 p) parm=$OPTARG;;
5 \?) echo ”option invalide $OPTARG”;exit 1 ;;
6 :) echo ”argument requis $OPTARG”;exit 2 ;;
7 h) echo ”usage $0 [ −p nombre ] [ fichier ] ”
8 exit 3 ;;
9 esac
10 done
11 echo $∗
12 shift $((OPTIND−1))
13 [[ $parm =˜ $reg ]] && echo matching

−p 1245 [0 −5]{3}
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  188 / 391
fichier

6 - fichier

structure
I-noeud
commande fichier
répertoire
tube nommé
netcat
commande réseau

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  189 / 391
fichier structure

structure générale
L’ensemble des systèmes de fichiers d’un système unix est un arbre
enraciné dans répertoire / .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  190 / 391
fichier structure

Systèmes de fichiers
mount greffe des systèmes de fichiers, ces noeuds sont des
points de montage.
FILESYSTEMS ( 5 ) L i n u x Programmer ’ s Manual
NAME
f i l e s y s t e m s − L i n u x f i l e −s y s t e m t y p e s : m i n i x ,
e x t , e x t 2 , e x t 3 , e x t 4 , R e i s e r f s , XFS , JFS , x i a ,
msdos , umsdos , v f a t , n t f s , pr o c , n f s , i s o 9 6 6 0 ,
h p f s , s y s v , smb , n c p f s
DESCRIPTION
I n o r d e r t o u s e a f i l e system , you h av e t o mount
it ;
proc pseudo f i l e system
iso9660 CD−ROM f i l e s y s t e m
nfs network f i l e system
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  191 / 391
fichier structure

Quelques points
mount
/ dev / s d a 1 on /
t y p e e x t 4 ( rw , e r r o r s=remount−r o )
proc on / p r o c
t y p e p r o c ( rw , noexec , n o s u i d , nodev )
tmpfs on / media
t y p e t m p f s ( rw , n o s u i d , nodev , noexec , r e l a t i m e ,
s e c l a b e l , mode=755)
s i n f o 1 : / home/ p e r s o on /home/ p e r s o
t y p e n f s ( rw , s o f t , i n t r , s l o p p y , a d d r
=[Link])
c u r l f t p f s#f t p : / / f r e e b o x :−−−−@mafreebox . f r e e b o x .
f r / D i s q u e %20d u r /
on / media / f r e e b o x
t y p e f u s e ( rw , nUnix
Philippe Langevin (IMATH, USTV)
o setuProgrammation
i d , nodev Shell
, noexec , Automne
r e l a 
t i m e 192
, / 391
fichier structure

Organisation
bin exécutables fondamentaux [binaries]
boot noyau vmlinuz et fichiers de démarrage
dev périphériques [device]
etc fichiers de configuration des services
home données personnelles des utilisateurs
lib bibliothèques [libraries]
mnt point de montage temporaire
media point de montage automatique
proc pseudo-fichiers des processus en cours
root répertoire du super-utilisateur
sbin [(system|superuser) binaries]
tmp fichiers temporaires
usr accessibles à tous les utilisateurs
var fichiers variables, souvent modifiés
FHS système de fichiers
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  193 / 391
fichier I-noeud

structure d’un système de fichier


Un système de fichiers comprend trois zone :
superbloc
table de noeuds
fichiers et répertoire
df −i
Sys . f i c h . I n o d e s I U t i l . I L i b r e I U t i% Monte
sur
rootfs 1122304 160548 961756 15% /
tmpfs 63474 1 63473 1% / media
/ dev / s d a 1 128016 349 127667 1% / b o o t
super-bloc Il contient des informations globales sur le système de
fichier : taille, nom, type, nom de volume, verrous, tables de
gestions...
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  194 / 391
fichier I-noeud

I-noeud

Les noeuds du système de fichiers sont indexés par des entiers qui les
caractérisent : I-noeud (inode) :
l s − l / e t c / passwd
−rw−r−−r −−.
1 r o o t r o o t 1797 1 s e p t . 1 7 : 1 3 / e t c / passwd

l s − i l /home/ t o t o / . b a s h r c
2883586 −rw−r−−r −−.
1 t o t o n o v i c e 124 24 nov . 2011 /home/ t o t o / .
bashrc

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  195 / 391
fichier I-noeud

attribut
La commande stat détaille les attributs des fichiers
stat /home/ t o t o / . b a s h r c
File : /home/ t o t o / . b a s h r c
Size : 124 B l o c k s : 8 IO B l o c k : 4096 f i c h i e r
Device : f d 0 2 h /64770 d I n o d e : 2883586 Links : 1
Access : (0644/ − rw−r−−r −−)
Uid : (1002/ t o t o ) Gid : (1002/
novice )
Context : u n c o n f i n e d u : o b j e c t r : user home t : s0
A c c e s s : 2012−09−01 1 7 : 3 5 : 0 7 . 7 1 8 6 1 0 6 6 5 +0200
M o d i f y : 2011−11−24 2 3 : 0 0 : 3 4 . 0 0 0 0 0 0 0 0 0 +0100
Change : 2012−09−01 1 7 : 0 5 : 2 0 . 8 3 8 4 7 4 8 6 4 +0200
Birth : −

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  196 / 391
fichier I-noeud

taille, bloc

Dans un terminal, lancer les commandes :


t o u c h /tmp/ x
watch s t a t /tmp/ x
Dans un autre terminal
echo h e l l o > /tmp/ x
Observer le premier terminal. Continuer avec :
f o r ( ( i =0; i <12; i ++)) ; do
c a t /tmp/ x /tmp/ x > /tmp/ y ;
mv /tmp/ y /tmp/ x ; s l e e p 3 ;
done

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  197 / 391
fichier I-noeud

gestion des blocs (ext)

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  198 / 391
fichier I-noeud

Limite
nombre de fichiers = nombre d’inoeuds.
b=256
l e t t=10+b+b∗b+b∗b∗b
echo $ t
16843018
echo ” l ( $ t ) ” | bc − l
16.63944676687317765852
$ bc − l << THIS
> b=256
> t=10+b+bˆ2+b ˆ3
> l ( t )/ l (2)
> THIS
24.00564733370382901169
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  199 / 391
fichier I-noeud

Les types de noeud

type english création destruction


fichier file rm
répertoire directory mkdir rm -r
lien symbolique link ln -s rm
prise socket socket close IPC
tube nommé pipe mkfifo rm IPC
périphérique caractére
périphérique bloc

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  200 / 391
fichier I-noeud

Quelques noeuds
f i n d / dev −t y p e b −name ’ s ∗ ’
/ dev / s d a 3
tty
/ dev / p t s /1
l s −l $( tty )
crw−−w−−−−. 1 d r m i c h k o t t y . . . / dev / p t s /1
l s − l / b i n /awk
l r w x r w x r w x . 1 r o o t r o o t 4 . . . / b i n /awk −> gawk
l s −l d /∗
drwxr −xr −x . 19 r o o t r o o t 3480 . . . / dev
drwxr −xr −x . 6 r o o t r o o t 4096 . . . /home
dr−xr −xr −x . 19 r o o t r o o t 12288 . . . / l i b
drwxr −xr −x . 2 r o o t r o o t 4096 . . . /mnt
dr−xr −xr −x . 146 r o o t r o o t 0 . . . / proc
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  201 / 391
fichier commande fichier

commande fichier
ls, find, locate
mkdir, cd, popd, pushd, dir
basename, dirname, pwd, which
touch, cp, mv
tar : archivage
rsync, unison : sauvegarde, git
des statistiques :
df,du : stat. systèmes de fichiers, disque.
lsof : liste des fichiers ouverts
fuser : usage des fichiers
administratives :
ln : lien
mount : montage
fdisk, parted : manipuler les partitions
fsck : contrôler, réparer
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  202 / 391
fichier commande fichier

commande fichier
file, type
cmp, comm, diff
cat, tac, tee
more, less
tail, head
nl, wc,
grep, strings
od, hexdump
sort, uniq
split, csplit
join, paste, fold
col, tr, iconv, cut, awk, sed
gedit, vi, emacs , aspell
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  203 / 391
fichier commande fichier

compilation

indent :
make : maintenance
gcc : compilateur gnu
grof : profileur
gcov : couverture
gdb : debugguer
valgrind : fuite mémoire
flex : analyseur lexical
bison : compilateur de compilateur
[abc du c]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  204 / 391
fichier répertoire

Les répertoires
Les noms de fichiers sont stockés dans les répertoires :
inode taille nom
3804070 12 .
3538945 12 ..
3804071 20 [Link]
3804072 4052 [Link]
m k d i r tmp
echo ’ h e l l o w o r l d ’ > tmp/ h e l l o . t x t
echo ’ h e l l o w o r l d ’ > tmp/ H e l l o . t x t
] echo −e ’ l s / d r m i c h k o /tmp\ n q u i t ’
| d e b u g f s / dev / mapper / VolGroup−l v h o m e
debugfs : l s / d r m i c h k o /tmp
3804070 ( 1 2 ) . 3538945 ( 1 2 ) . . 3804071
(20) h e l l o . txt
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  205 / 391
fichier répertoire

ajout, suppression des entrées


On ajoute un fichier :
echo ’ h e l l o w o r l d ’ > tmp/ nouveau . t x t

] echo −e ’ l s / d r m i c h k o /tmp\ n q u i t ’
| d e b u g f s / dev / mapper / VolGroup−l v h o m e
debugfs : l s / d r m i c h k o /tmp
3804070 ( 1 2 ) . 3538945 ( 1 2 ) . . 3804071
(20) h e l l o . txt
3804072 ( 2 0 ) H e l l o . t x t 3804067 ( 4 0 3 2 )
nouveau . t x t
On efface un autre :
rm tmp/ h e l l o . t x t

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  206 / 391
fichier répertoire

src/dir.c
1 #include <string.h>
2 int main()
3 { int count;
4 struct dirent ∗fic ;
5 DIR ∗dir ;
6 char ∗path, ∗tok;
7 path=getenv( ”PATH” );
8 tok = strtok(path, ”: ”);
9 do {
10 dir = opendir( tok );
11 count=0;
12 while (( fic = readdir(dir)) )
13 if ( DT REG == fic−>d type) count++;
14 printf (”%s −> %d files\n”, tok, count);
15 closedir (dir ); Unix et Programmation Shell
Philippe Langevin (IMATH, USTV) Automne  207 / 391
fichier répertoire

src/dir.c

/ u s r / k e r b e r o s / s b i n −> 5 f i l e s
/ u s r / k e r b e r o s / b i n −> 14 f i l e s
/ u s r / l o c a l / b i n −> 4 f i l e s
/ u s r / b i n −> 2273 f i l e s
/ b i n −> 115 f i l e s
/ u s r / l o c a l / s b i n −> 0 f i l e s
/ u s r / s b i n −> 362 f i l e s
/ s b i n −> 207 f i l e s
/home/ p l / b i n −> 53 f i l e s
/home/ p l / s c r i p t −> 36 f i l e s

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  208 / 391
fichier répertoire

[Link]

1 #!/bin/bash
2 echo $PATH | tr ’:’ ’ \n’ | while read path
3 do
4 count=$( ls −l $path | grep −cE ’ˆ−’ )
5 echo $path ’−>’ $count files
6 done

man 3 readdir
man tr, grep
help echo, help while
2 solutions parmi d’autres !
[comparaisons] : python, perl, bash, C.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  209 / 391
fichier tube nommé

Les tubes nommés

whoami
michko
m k f i f o /tmp/ c a n a l
l s − l /tmp/ c a n a l
prw−rw−r −−. 1 michko michko 0 3 sept . 18:55 /
tmp/ c a n a l
c a t > /tmp/ c a n a l
michko écrit dans le tube...
whoami
toto
c a t < /tmp/ c a n a l
toto lit dans le tube.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  210 / 391
fichier netcat

netcat

La commande nc, le couteau suisse du net, permet d’écouter sur une


prise réseau :
nc − l 31415
ou bien d’envoyer des données vers une socket distante :
nc t u r i n g . e u p h o r i a . f r 31415

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  211 / 391
fichier netcat

dig, nc
nc −l u 31415 | hexdump −C
d i g −p 31415 www. e u p h o r i a . f r @ l o c a l h o s t

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  212 / 391
fichier netcat

dig, nc
nc −l u 31415 | hexdump −C
d i g −p 31415 www. e u p h o r i a . f r @ l o c a l h o s t
00000000 6 a 48 01 00 00 01 00 00
00 00 00 00 03 77 77 77
| jH . . . . . . . . . . . www|
00000010 08 65 75 70 68 6 f 72 69
61 02 66 72 00 00 01 00
| . euphoria . f r . . . . |
; <<>> DiG 9.7.3 − P1−RedHat −9.7.3 −2. P1 . f c 1 3
<<>> −p31415 www. e u p h o r i a . f r @ l o c a l h o s t
; ; g l o b a l o p t i o n s : +cmd
; ; c o n n e c t i o n t i m e d o u t ; no s e r v e r s c o u l d be
reached
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  212 / 391
fichier netcat

client/serveur

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  213 / 391
fichier netcat

gnuchess
gnuchess
GNU C h e s s 5 . 0 8
A d j u s t i n g H a s h S i z e t o 1024 s l o t s
T r a n s p o s i t i o n t a b l e : E n t r i e s =1K S i z e =40K
Pawn h a s h t a b l e : E n t r i e s =0K S i z e =28K
White ( 1 ) : e 2 e 4
1 . e2e4

b l a c k KQkq e3
r n b q k b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . P . . .
. . . . . . . .
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  214 / 391
fichier netcat

gnu chess service

Installation du serveur :
m k f i f o /tmp/ f i f o
nc − l 31415 < /tmp/ f i f o
| g n u c h e s s > /tmp/ f i f o
connexion d’un client :
nc 31415

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  215 / 391
fichier netcat

gnu chess service

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  216 / 391
fichier netcat

client
nc t u r i n g . e u p h o r i a . f r 31415
GNU C h e s s 5 . 0 8
A d j u s t i n g H a s h S i z e t o 1024 s l o t s
T r a n s p o s i t i o n t a b l e : E n t r i e s =1K S i z e =40K
Pawn h a s h t a b l e : E n t r i e s =0K S i z e =28K
White ( 1 ) : e 2 e 4
1 . e2e4

b l a c k KQkq e3
r n b q k b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . P . . .
. . . . . . . .
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  217 / 391
fichier commande réseau

commande réseau

ftp, sftp, scp


ssh
telnet
wget, curl
lynx, links
diagnostic :
ping, host, dig
route, ifconfig,ip
traceroute, tracepath
netstat

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  218 / 391
permission

7 - permission

droit fichier
changement
droit répertoire
droits spéciaux
setuid bit
faille

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  219 / 391
permission

permission

Un i-noeud est la propriété d’un utilisateur et d’un groupe :


chown t o t o : n o v i c e /tmp/ c a n a l
l s − l /tmp/ c a n a l
prw−rw−r −−. 1 t o t o n o v i c e 0 . . . /tmp/ c a n a l
s t a t /tmp/ c a n a l
F i l e : /tmp/ c a n a l
S i z e : 0 B l o c k s : 0 IO B l o c k : 4096 FIFO
D e v i c e : f d 0 1 h /64769 d I n o d e : 787380 L i n k s : 1
A c c e s s : (0 66 4/ prw−rw−r −−)
Uid : ( 1002/ t o t o ) Gid : ( 1002/ n o v i c e )

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  220 / 391
permission droit fichier

drapeaux

Les permissions sont décrites par un nombre de 4 chiffres en base


octale et forment 12 drapeaux de droit.
s S t u u u g g g o o o
0 0 0 1 1 1 1 0 1 1 0 0
r w x r - x r - -
Table – droit 0754

Le chiffre dominant concerne les droits spéciaux, les suivant les droits
utilisateur, groupe et autre.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  221 / 391
permission droit fichier

affichage
s S t u u u g g g o o o
1 r w s r w x r w x
1 r w x r w s r w x
1 r w x r w x r w t
Table – affichage des droits spéciaux

l s − l / b i n / passwd
−r w s r −xr −x . 1 r o o t r o o t 2715 22 j u i 0 2 : 5 1 / b i n /
passwd
l s −l / usr / bin / wall
−r−xr −s r −x . 1 r o o t t t y 10588 18 f e v 2013 / u s r /
bin / wall
l s −l d /tmp
d r w x r w x r w t 14 r o o t r o o t 480 18 s e p t . 1 8 : 2 2 /tmp
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  222 / 391
permission droit fichier

droit fichier

Les drapeaux rwx sont définis par le propriétaire du fichier pour lui, le
groupe et le reste du monde. Le propriétaire peut changer les
permissions.
r : fichier ouvert en lecture, copiable
w : fichier ouvert en écriture, vidable
x : exécutable
Les droits suid et sgid affectent ces droits.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  223 / 391
permission changement

manipulation

La commande chmod permet d’ajuster les droits :


chmod u+x go−x /tmp/ c a n a l
de les sceller numériquement.
chmod 700 /tmp/ c a n a l
mode récursif :
chmod −R a−w /home/ t o t o / pub

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  224 / 391
permission changement

priorité ugo
# u s e r a d d −g b a r f o o ; u s e r a d d drm ; u s e r a d d ken
# l s − l /home
drwx−−−−−− 4 drm drm 4096 . . . drm
drwx−−−−−− 4 foo bar 4096 . . . f o o
drwx−−−−−− 4 ken ken 4096 . . . ken
# usermod −a −G b a r drm ; g r o u p s drm
drm : drm b a r
# echo w o r l d > /tmp/ h e l l o
# chown f o o : b a r /tmp/ h e l l o ; l s − l /tmp/ h e l l o
−rw−r−−r−− 1 f o o b a r 6 . . . /tmp/ h e l l o
# chmod ou−r /tmp/ h e l l o
# s u d o −u ken c a t /tmp/ h e l l o
c a t : /tmp/ h e l l o : P e r m i s s i o n non a c c o r d e e
# s u d o −u f o o c a t /tmp/ h e l l o
c a t : /tmp/ h e l l o : P e r m i s s i o n non a c c o r d e e
# s u d o −u drm c a t /tmp/ h e l l o
world
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  225 / 391
permission droit répertoire

droit répertoire

r : lecture du contenu du répertoire.


w : permet la création, la suppression et le changement de noms
x : autorise l’accès (ou ouverture) au répertoire.
Le sticky bit et le sgid affectent ces droits.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  226 / 391
permission droit répertoire

x/dir

1 #!/bin/bash −v
2 mkdir −p /tmp/x/y
3 echo hello > /tmp/x/y/[Link]
4 cat /tmp/x/y/[Link]
5 hello
6 chmod u−x /tmp/x
7 cat /tmp/x/y/[Link]
8 cat: /tmp/x/y/[Link]: Permission non accordee
9 chmod u+x /tmp/x

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  227 / 391
permission droit répertoire

w/dir
su p a t ; l s −l d /tmp/ x / y
drwxrwxr −x 2 p l p l 4096 31 j u i l . 0 9 : 5 0 /tmp/ x / y
y e s | rm /tmp/ x / y / z . t x t
rm : i m p o s s i b l e de s u p p r i m e r /tmp/ x / y / z . t x t

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  228 / 391
permission droit répertoire

w/dir
su p a t ; l s −l d /tmp/ x / y
drwxrwxr −x 2 p l p l 4096 31 j u i l . 0 9 : 5 0 /tmp/ x / y
y e s | rm /tmp/ x / y / z . t x t
rm : i m p o s s i b l e de s u p p r i m e r /tmp/ x / y / z . t x t
chmod o+w /tmp/ x / y
l s − a l /tmp/ x / y
drwxrwxrwx 2 p l p l 4096 31 j u i l . 0 9 : 5 8 .
drwxrwxr −x 3 p l p l 4096 31 j u i l . 0 9 : 4 0 . .
−rw−rw−r−− 1 p l p l 6 31 j u i l . 0 9 : 5 8 z . t x t

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  228 / 391
permission droit répertoire

w/dir
su p a t ; l s −l d /tmp/ x / y
drwxrwxr −x 2 p l p l 4096 31 j u i l . 0 9 : 5 0 /tmp/ x / y
y e s | rm /tmp/ x / y / z . t x t
rm : i m p o s s i b l e de s u p p r i m e r /tmp/ x / y / z . t x t
chmod o+w /tmp/ x / y
l s − a l /tmp/ x / y
drwxrwxrwx 2 p l p l 4096 31 j u i l . 0 9 : 5 8 .
drwxrwxr −x 3 p l p l 4096 31 j u i l . 0 9 : 4 0 . .
−rw−rw−r−− 1 p l p l 6 31 j u i l . 0 9 : 5 8 z . t x t
$ echo boom > /tmp/ x / y / z . t x t
ba s h : /tmp/ x / y / z . t x t : P e r m i s s i o n non a c c o r d e e
$ rm −f /tmp/ x / y / z . t x t
$ l s −a /tmp/ x / y (OK)
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  228 / 391
permission droit répertoire

masque de création

Un masque est appliqué par défaut lors de la création des fichiers. Il


indique les droits à retirer ( masque ) ou à conserver (logique) :
umask ; umask −S
0002
u=rwx , g=rwx , o=r x
echo t e s t > /tmp/ t e s t
l s −l t e s t
−rw−rw−r −−. 1 p l p l 5 3 s e p t . 1 9 : 4 5 /tmp/ t e s t
echo $ ( ( 666 − 666 & 002 ) )
664
s t a t −−f o r m a t=”%a %A” /tmp/ t e s t
664 −rw−rw−r−−

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  229 / 391
permission droit répertoire

masque de création

1 #!/bin/bash −v
2 echo ’int main(void) {return 0;}’ > vrai. c
3 umask −S
4 u=rwx,g=rwx,o=rx
5 gcc vrai . c
6 ls −l a. out
7 −rwxrwxr−x 1 pl pl 4542 31 juil . 08:25 a. out
8 umask 077
9 gcc vrai . c
10 ls −l a. out
11 −rwx−−−−−− 1 pl pl 4542 31 juil. 08:25 [Link]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  230 / 391
permission droits spéciaux

bit collant
A l’origine, le sticky bit indique au système de conserver en mémoire
le code. Cette terminologie historique est réutilisée pour qualifier les
doits sur un répertoire :
l s −l d /tmp
drwxrwxrw . t 13 r o o t r o o t 4096 5 sept . 12:36 /
tmp/

s t a t −−f o r m a t=”%F %a %A” /tmp


r e p e r t o i r e 1777 d r w x r w x r w t

sticky bit du répertoire allumé


Un utilisateur peut manipuler une arborescence dans ce répertoire :
créer et effacer les fichiers qui lui appartiennent.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  231 / 391
permission droits spéciaux

sticky bit

l s −l d /{tmp ,TMP}
d r w x r w x r w t . 103 r o o t r o o t 12288 . . . /tmp
drwxrwxrwx 2 r o o t r o o t 4096 . . . /TMP
echo h e l l o > /tmp/msg . t x t
echo h e l l o > /TMP/msg . t x t
l s − l /{tmp ,TMP}/msg . t x t
−rw−rw−r−− 1 p l p l 6 . . . /tmp/msg . t x t
−rw−rw−r−− 1 p l p l 6 . . . /TMP/msg . t x t
su p a t
$ rm /TMP/msg . t x t
$ rm /tmp/msg . t x t
rm : o p e r a t i o n non p e r m i s e

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  232 / 391
permission droits spéciaux

droit suid
Dans certaines circonstances, un utilisateur doit pouvoir exécuter des
binaires avec des privilèges root. Typiquement, toto peut changer
son mot de passe avec passwd et donc ecrire dans /etc/shadow ! ?
l s − l / e t c / shadow
−−−−−−−−−−. 1 r o o t r o o t 1164 . . . / e t c / shadow
l s − l / u s r / b i n / passwd
−r w s r −xr −x . 1 r o o t r o o t 25992 . . . / u s r / b i n /
passwd
s t a t −−f o r m a t=”%F %a %A” / u s r / b i n / passwd
f i c h i e r 4755 −r w s r −xr −x
passwd est un binaire suid
ouvert en exécution
fournit la capacité root (euid).
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  233 / 391
permission droits spéciaux

binaires suid

find / usr / bin −perm +4000


/ usr / bin / chsh
/ u s r / b i n / chage
/ u s r / b i n / passwd
/ u s r / b i n / mount
/ usr / bin / crontab
/ u s r / b i n / sudo
/ u s r / b i n / umount
/ usr / bin / at
/ u s r / b i n / su

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  234 / 391
permission droits spéciaux

droit sgid répertoire

Le bit sgid sur un fichier exécutable s’applique au groupe : s masque


les droits x du groupe, S sinon.
Dans la cas d’un partage de dossier, tous les membres d’un
groupe souhaitent modifier ou supprimer les contributions des
membres du groupe.
Tout fichier et répertoire créé dans un répertoire sgid appartient
au groupe de celui-ci et non au groupe de l’utilisateur qui crée
l’élément.
Les sous-répertoires héritent du bit sgid, sans rétroaction !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  235 / 391
permission droits spéciaux

] g r o u p a d d t e s t ; m k d i r /home/ p a r t a g e
] chown r o o t : t e s t /home/ p a r t a g e
] usermod −a −G t e s t t o t o
groups
novice test
echo h e l l o > /home/ p a r t a g e / t o t o
l s − a l /home/ p a r t a g e ∗o∗
−rw−r−−r −−. 1 t o t o n o v i c e 18 1 6 : 5 2 t o t o
] chmod g+s /home/ p a r t a g e
s t a t −−f o r m a t=”%F %a %A” /home/ p a r t a g e
r e p e r t o i r e 2775 d r w x r w s r −x
echo h e l l o > /home/ p a r t a g e / w o r l d
l s − a l /home/ p a r t a g e ∗o∗
−rw−r−−r −−. 1 t o t o n o v i c e 18 1 6 : 5 2 t o t o
−rw−r−−r −−. 1 t o t o t e s t 6 16:53 world

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  236 / 391
permission setuid bit

uid, euid

Un processus possède un uid réel et un uid effectif sur lequel sont


basé les privilèges du processus. En général

UID = EUID

l’uid réel est celui du processus qui lance la commande.


l’uid effectif est (sous condition) celui du propriétaire de la
commande.

Les permissions sont basées sur l’euid.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  237 / 391
permission setuid bit

system vs execve
1 int main()
2 {
3 char ∗argv[2];
4 argv[0] = ”id”;
5 argv[1] = 0;
6
7 system(”id”);
8
9 execve(”/usr/bin/id”, argv, 0);
10
11 return 0;
12 }
system exécution par le shell.
execve appel système.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  238 / 391
permission setuid bit

system vs execve
sudo g c c −W a l l s e t u i d e x e c . c −o s e t u i d e x e c . e x e
. / s e t u i d e x e c . e x e | c u t −d ’ , ’ −f1 , 2
u i d =501( p l ) g i d =501( p l ) g r o u p e s =501( p l ) , 1 0 ( w h e e l
)
u i d =501( p l ) g i d =501( p l ) g r o u p s =501( p l ) , 1 0 ( w h e e l )
sudo chmod u+s s e t u i d e x e c . e x e
. / s e t u i d e x e c . e x e | c u t −d ’ , ’ −f1 , 2
u i d =501( p l ) g i d =501( p l ) g r o u p e s =501( p l ) , 1 0 ( w h e e l
)
u i d =501( p l ) g i d =501( p l ) e u i d =0( r o o t ) g r o u p s =0(
root ) ,10( wheel )
system euid uid ( bash n’est pas suid ).
execve euid = root. (appel système)
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  239 / 391
permission setuid bit

euid.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 int main( void ) {
4 FILE ∗src = NULL;
5 system(”ls −alt euid. exe”);
6 printf (”\nuid=%d euid=%d\n”,getuid (),geteuid ());
7 system(”whoami”);
8 system(”wc −L /etc/shadow”);
9 // −L : plus longue ligne ?
10 src = fopen(”/etc/shadow”, ”r”);
11 printf (”%p”, src );
12 fclose ( src );
13 return 0;
14 }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  240 / 391
permission setuid bit

system, execve

sudo g c c −W a l l e u i d . c −o e u i d . e x e
sudo chmod u+s e u i d . e x e
./ euid . exe
−r w s r −xr −x 1 r o o t r o o t 5326 2 1 : 3 7 e u i d . e x e

u i d =501 e u i d =0
pl
wc : / e t c / shadow : P e r m i s s i o n non a c c o r d e e
0 x859a008
bash : perte de euid.
fopen : exécuté avec euid root.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  241 / 391
permission setuid bit

uid, euid
1 #include <sys/types.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 int main( void )
6 {
7 FILE ∗src;
8 printf (”\nuid=%d euid=%d\n”,getuid (),geteuid ());
9 src = fopen( ”uid. txt ”, ”r” );
10 if ( ! src )
11 perror ( ”interdit ” );
12 fclose (src );
13 return 0;
14 }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  242 / 391
permission setuid bit

uid, euid
g c c −Wall u i d . c −o u i d . e x e
sudo chown nobody : nobody u i d . e x e
sudo cp −p u i d . e x e u i d . s s s
sudo chmod u+s u i d . s s s
touch uid . t x t ; l s −l uid . [ e s t ]∗
−rwxrwxr −x 1 nobody nobody 5237 . . . uid . exe
−r w s r w x r −x . 1 nobody nobody 5237 . . . u i d . s s s
−rw−−w−−−−. 1 p l pl 0 ... uid . txt
id
u i d =501( p l ) g i d =501( p l ) g r o u p e s =501( p l ) , 1 0 ( w h e e l )
./ uid . exe
u i d =501 e u i d =501
./ uid . sss
u i d =501 e u i d =99
i n t e r d i t : Permission denied
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  243 / 391
permission setuid bit

setuid.c
1 #include <sys/types.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 int main( void ) {
6 system(”ls −alt setuid . exe”);
7 printf (”\nuid=%d euid=%d\n”,getuid (),geteuid ());
8 system(”whoami”);
9 system(”ls /root”);
10 setuid(0);
11 printf (”\nuid=%d euid=%d\n”,getuid (),geteuid ());
12 system(”whoami”);
13 system(”ls /root”);
14 return 0;
15 }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  244 / 391
permission setuid bit

[Link]
sudo g c c −W a l l s e t u i d . c −o s e t u i d . e x e
sudo chmod u+s s e t u i d . e x e
./ s e t u i d . exe
−r w s r −xr −x 1 r o o t r o o t 5187 . . . s e t u i d . exe
u i d =501 e u i d =0
pl
ls : impossible d ’ ouvrir le repertoire
r o o t : P e r m i s s i o n non a c c o r d e e
u i d =0 e u i d =0
root
anaconda−k s . c f g Desktop i n s t a l l . l o g

setuid : le processus utilise son euid pour changer uid !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  245 / 391
permission faille

faille
1 #include <sys/types.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5
6 int main( int argc, char ∗argv[] )
7 {
8 char cmd[64];
9
10 sprintf ( cmd, ”wc −l %s”, argv[1] );
11 setuid(0);
12 system( cmd );
13 return 0;
14 }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  246 / 391
permission faille

exploit
. / boom . e x e / e t c / passwd
35 / e t c / passwd

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  247 / 391
permission faille

exploit
. / boom . e x e / e t c / passwd
35 / e t c / passwd

. / boom . e x e / e t c / shadow
35 / e t c / shadow

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  247 / 391
permission faille

exploit
. / boom . e x e / e t c / passwd
35 / e t c / passwd

. / boom . e x e / e t c / shadow
35 / e t c / shadow

. / boom . e x e ”/ e t c / passwd ; g r e p p l / e t c / shadow ”


35 / e t c / passwd
p l : $6$uHL8DbWBehKEl0Rb$dZZ/3 O2uhDlMkkrnjIG / q8Lo .
J8
CZKPqZAc7j7EFFBo6o4QTw/UlWK . YWhjvgKRqquMo .
aKJEtlG3
YEYPyg5T . : 1 5 4 3 9 : 0 : 9 9 9 9 9 : 7 : : :
passwd
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  247 / 391
permission faille

Injection de code

faille L’absence de contrôle sur les données passées au exécutable


pose toujours des soucis, dans le cas des suid c’est un sérieux
problème de sécurité !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  248 / 391
permission faille

Injection de code

faille L’absence de contrôle sur les données passées au exécutable


pose toujours des soucis, dans le cas des suid c’est un sérieux
problème de sécurité !
. / boom . e x e ’ boom . c ; / b i n / sh ’

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  248 / 391
permission faille

Injection de code

faille L’absence de contrôle sur les données passées au exécutable


pose toujours des soucis, dans le cas des suid c’est un sérieux
problème de sécurité !
. / boom . e x e ’ boom . c ; / b i n / sh ’

15 boom . c
sh −4.2#

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  248 / 391
permission faille

Injection de code

faille L’absence de contrôle sur les données passées au exécutable


pose toujours des soucis, dans le cas des suid c’est un sérieux
problème de sécurité !
. / boom . e x e ’ boom . c ; / b i n / sh ’

15 boom . c
sh −4.2#

sh −4.2# whoami
root
shell root !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  248 / 391
permission faille

attaque sushi

#!/ b i n / b a s h
echo $UID $EUID
sudo chown r o o t : r o o t s u i d . sh
sudo chmod u+s s u i d . sh
l s − l s u i d . sh
−r w s r w x r −x 1 r o o t r o o t 28 19 s e p t . 0 6 : 1 0 s u i d . sh
. / s u i d . sh
501 501
Les possibilités de failles dans un script suid seraient encore plus
nombreuses : attaques sushi. Pour des raisons de sécurité :
dans un script shell : euid := uid
modification de fichier =⇒ perte du suid-bit

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  249 / 391
permission faille

shellshock
1 #include <sys/types.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 // shellshockable : facile
6 int main( void )
7 {
8 char tmp[128], cmd[128];
9 sprintf (tmp, ”sed −n ’/:%d:/s/:.∗//p’ /etc/passwd”, getuid
() );
10 sprintf (cmd, ”grep $( %s ) /etc/shadow”, tmp);
11 puts(”cryptogramme:”);
12 setuid(0);
13 system( cmd );
14 return 0;
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  250 / 391
permission faille

shellshock
SYSTEM( 3 ) Manuel du programmeur L i n u x
NOM
s y s t e m − E x e c u t e r une commande s h e l l
SYNOPSIS
#i n c l u d e < s t d l i b . h>
i n t s y s t e m ( c o n s t c h a r ∗command ) ;
DESCRIPTION
La f o n c t i o n s y s t e m ( ) e x e c u t e l a commande i n d i q u e e
d a n s command en a p p e l a n t / b i n / s h −c command , e t
r e v i e n t a p r e s l ’ e x e c u t i o n c o m p l e t e de l a commande .
NOTES
N’ u t i l i s e z j a m a i s s y s t e m ( ) d a n s un programme
avec l e s p r i v i l e g e s Set−UID ou Set−GID . Des
v a r i a b l e s d ’ env . a v e c d e s v a l e u r s e t r a n g e s p e u v e n t
e t r e u t i l i s e e s pour corrompre l e systeme .
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  251 / 391
processus

8 - processus

exécutable vs processus
environnement
variable du shell
contexte d’exécution
commande processus
gentillesse
ressource
sous-processus
job
processus léger

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  252 / 391
processus exécutable vs processus

processus ?

Il s’agit d’un fichier binaire en cours d’exécution ! Il y a un processus


actif par processeur, le noyau partage et ordonne leur exécution.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  253 / 391
processus exécutable vs processus

processus ?

Il s’agit d’un fichier binaire en cours d’exécution ! Il y a un processus


actif par processeur, le noyau partage et ordonne leur exécution.
bg, jobs, time, kill
ps, pstree, /usr/bin/time, top

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  253 / 391
processus exécutable vs processus

ps
La commande ps renseigne sur les attributs

PID, PPID, TID (SPID), UID, EUID . . .

et l’état d’un processus


état
D Uninterruptible sleep (usually IO)
R Running or runnable (on run queue)
S Interruptible sleep
T Stopped, traced
X dead (should never be seen)
Z Defunct (”zombie”) process
format BSD : < haute priorité, N basse, L pages vérouillées, s session
leader, l multithreadé, + en avant plan.
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  254 / 391
processus exécutable vs processus

exemple

p s −e −o s t a t e , p i d , cmd | g r e p −v S
R 12447 p s −e −o s t a t e , p i d , cmd

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  255 / 391
processus exécutable vs processus

exemple

p s −e −o s t a t e , p i d , cmd | g r e p −v S
R 12447 p s −e −o s t a t e , p i d , cmd

p s −−p p i d 1 −o p p i d , p i d , u s e r , cmd
1 338 r o o t / u s r / l i b / udev / udevd
1 339 r o o t / u s r / l i b / s y s t e m d / s y s t e m d−j o u r n a l d
1 531 r o o t / u s r / l i b / s y s t e m d / s y s t e m d−l o g i n d
1 538 r o o t / u s r / s b i n / a t d −f
1 540 r o o t / u s r / s b i n / lxdm−b i n a r y −nodaemon
1 577 r o o t / u s r / s b i n / c r o n d −n
1 867 r o o t / s b i n / d h c l i e n t −H d e l l p l −1 . . .
1 934 r o o t / u s r / s b i n / s s h d −D
1 1187 p l xterm
1 1256 r o o t s e n d m a i l : a c c e p t i n g c o n n e c t i o n s
1 1272 smmsp s e n d m a i l : Queue r u n n e r @ 0 1 : 0 0 : 0 0 . . .
1 1439 p l s s h −Nf p l @ n i l . f r −L2222 : 1 0 . 2 . 7 3 . 8 6 : 2 2

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  255 / 391
processus environnement

Environnement

Un processus hérite des variables d’environnement. Elles sont passées


par la pile, tout comme le résultat de la commande.
1 ...
2 int main( int argc, char ∗argv[], char∗ env[] )
3 {
4 ...
5 return SUCCES;
6 }

code de retour = 0 : SUCCES

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  256 / 391
processus environnement

capture de l’environnement

1 #include <stdio.h>
2 int main( int arg, char∗∗ argv , char∗∗ envr )
3 {
4 int res = 0;
5 while ( ∗argv )
6 printf (”\narg:%s”, ∗argv++);
7 while ( ∗envr ) {
8 printf (”\nenv:%s”, ∗envr++);
9 res ++;
10 }
11 return res ;
12 }

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  257 / 391
processus environnement

code de retour
1 :: gcc −Wall env.c
2 :: ./ a. out hello
3 arg:./ a. out
4 arg: hello
5 env:HOSTNAME=dellpl
6 env:TERM=xterm
7 env:SHELL=/bin/bash
8 env:HISTSIZE=1000
9 env:USER=pl
10 ...
11 :: echo $?
12 41
13 :: env −i ./ a. out hello
14 arg:./ a. out
15 arg: hello
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  258 / 391
processus variable du shell

variable usuelle
std : LOGNAME, HOME PATH, SHELL, TERM, USER, UID,
GID,...
bash : PS1, PS2, HISTFILE, SHELLOPT, BASH VERSION,...
paramètres de bash : $, 0–9, −, ], ∗, @, !, ?,
h e l p v a r i a b l e | g r e p −E ’ ( PS | SH) ’
BASH VERSION V e r s i o n i n f o r m a t i o n f o r t h i s
Bash .
PS1 The p r i m a r y prompt s t r i n g .
PS2 The s e c o n d a r y prompt s t r i n g .
SHELLOPTS A c o l o n −s e p a r a t e d l i s t o f e n a b l e d
s h e l l options .
env | g r e p −e ’ ˆP ’
PATH=/ u s r / k e r b e r o s / s b i n : / u s r / k e r b e r o s / b i n : / u s r /
l o c a l / bin :/ usr / bin :/ bin :/ usr / l o c a l / sbin :/ usr /
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  259 / 391
processus variable du shell

transmission

les variables du shell sont transmises aux sous-shell.


export permet la transmission aux processus fils.
1 XYZ=’hello world’
2 env | grep XYZ
3 export XYZ
4 env | grep XYZ
5 XYZ=hello world
6 export −p XYZ
7 export −n XYZ
8 env | grep XYZ

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  260 / 391
processus variable du shell

commandes

help variable : variables usuelles.


env : environnement d’exécution
export : transmission automatique
unset : démonte une variable du shell.
which
declare
g r e p PATH ˜ / . b a s h p r o f i l e
PATH=$PATH :$HOME/ b i n :$HOME/ s c r i p t
e x p o r t MANPATH=$MANPATH:$HOME/ t e x i n p u t
set : configuration de bash

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  261 / 391
processus variable du shell

declare
X=(1 2 3 )
d e c l a r e −p X
d e c l a r e −a X= ’([0]=”1” [ 1 ] = ” 2 ” [ 2 ] = ” 3 ” ) ’
d e c l a r e z=15
d e c l a r e −p z
d e c l a r e − i z =”15”
declare s t r=h e l l o
d e c l a r e −p s t r
d e c l a r e −− s t r =” h e l l o ”
d e c l a r e −A t
t [ ’ un ’ ] = 1 ; t [ ’ deux ’ ] = 2 ; t [ ’ t r o i s ’ ] = 3
d e c l a r e −p t
d e c l a r e −A t = ’ ( [ un ]=”1” [ deux ]=”2” [ t r o i s ]=”3”
)’
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  262 / 391
processus variable du shell

option du shell
1 #!/bin/bash
2 PS4=::
3 help set | grep −E ’ˆ[ ]∗−(e|x)’
4 set −x
5 echo foo > /etc/shadow
6 set −e
7 echo bar > /etc/shadow
8 echo hello world

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  263 / 391
processus variable du shell

option du shell
1 #!/bin/bash
2 PS4=::
3 help set | grep −E ’ˆ[ ]∗−(e|x)’
4 set −x
5 echo foo > /etc/shadow
6 set −e
7 echo bar > /etc/shadow
8 echo hello world

1 −e Exit immediately if a command exits with a non−


zero status.
2 −x Print commands and their arguments as they are
executed.
3 :: echo foo
4 ./ set. sho: line 5: /etc/shadow: Permission non accordee
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  263 / 391
processus contexte d’exécution

contexte d’exécution

Le contexte d’exécution,
registre
mémoire
descripteur
et l’ensemble des données concernant un processus sont disponibles
dans le répertoire /proc/self ou /proc/pid.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  264 / 391
processus contexte d’exécution

[Link]

1 #!/bin/bash −v
2 ls −d /proc/self/∗ | sed ’ s/\/[Link] \///g’\
3 | tr ’ \n’ ’ ’ | fold −w 54
4 #
5 cat /proc/self /environ \
6 | tr ’ \000’ ’ \n’ | grep −i name
7 cat /proc/self /status

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  265 / 391
processus contexte d’exécution

[Link]
1 #!/bin/bash −v
2 ls −d /proc/self/∗ | sed ’ s/\/[Link] \///g’\
3 | tr ’ \n’ ’ ’ | fold −w 54
4 attr auxv cgroup clear refs cmdline comm coredump filt
5 er cpuset cwd environ exe fd fdinfo io latency limits
6 loginuid maps mem mountinfo mounts mountstats net oom
7 adj oom score pagemap personality root sched schedstat
8 sessionid smaps stack stat statm status syscall task
9 wchan #
10 cat /proc/self /environ \
11 | tr ’ \000’ ’ \n’ | grep −i name
12 HOSTNAME=[Link]
13 USERNAME=pl
14 LOGNAME=pl
15 G BROKEN FILENAMES=1
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  266 / 391
processus contexte d’exécution

[Link]
1 #!/bin/bash −v
2 cat /proc/self /status
3 Name: cat
4 State: R (running)
5 Tgid: 2286
6 Pid: 2286
7 PPid: 2284
8 TracerPid: 0
9 Uid: 501 501 501 501
10 Gid: 501 501 501 501
11 Utrace: 0
12 FDSize: 256
13 Groups: 10 501
14 VmPeak: 4084 kB
15 VmSize: 4084 kBUnix et Programmation Shell
Philippe Langevin (IMATH, USTV) Automne  267 / 391
processus contexte d’exécution

/proc/pid
1 #include <sys/types.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5
6 int main( int argc, char ∗argv[] )
7 {
8 char cmd[64];
9 if ( argc > 1 )
10 sprintf (cmd, ”cat /proc/%d/%s”, getpid() , argv[1]) ;
11 else
12 sprintf (cmd, ”ls −al /proc/%d”, getpid() );
13 system( cmd );
14 putchar(’ \n’);
15 return 0;
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  268 / 391
processus contexte d’exécution

g c c −W a l l p r o c . c −o p r o c . e x e ; . / p r o c . e x e
dr−xr −xr −x . 2 pl pl0 3 sept . 12:19 a t t r
−rw−r−−r −−. 1 pl pl 0 3 sept . 12:19 autogroup
−r −−−−−−−−. 1 p l p l 0 3 s e p t . 1 2 : 1 9 auxv
−r−−r−−r −−. 1 p l p l 0 3 sept . 12:19 cgroup
−−w−−−−−−−. 1 pl pl 0 3 sept . 12:19
clear refs
−r−−r−−r −−. 1 pl pl 0 3 sept . 12:19 cmdline
−rw−r−−r −−. 1 p l p l 0 3 s e p t . 1 2 : 1 9 comm
−rw−r−−r −−. 1 pl pl 0 3 sept . 12:19
coredump filter
−r−−r−−r −−. 1 pl pl 0 3 sept . 12:19 cpuset
lrwxrwxrwx . 1 p l p l 0 3 s e p t . 1 2 : 1 9 cwd −> /
home/ p l /UPS/ doc
−r −−−−−−−−. 1 pl pl 0 3 sept . 12:19 environ
lrwxrwxrwx . 1 p l p l 0 3 s e p t . 1 2 : 1 9 e x e −> /
home/ p l /UPS/ doc / p r o c . e x e
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  269 / 391
processus contexte d’exécution

Carte mémoire
. / p r o c . e x e maps
08048000 −08049000 r−xp 00000000 f d : 0 1 793772 /
home/ p l /UPS/ doc / a . o u t
08049000 −0804 a000 rw−p 00000000 f d : 0 1 793772 /
home/ p l /UPS/ doc / a . o u t
42 c92000 −42cb1000 r−xp 00000000 f d : 0 1 163870 /
u s r / l i b / ld −2.15. so
42 cb1000 −42cb2000 r−−p 0001 e000 f d : 0 1 163870 /
u s r / l i b / ld −2.15. so
42 cb2000 −42cb3000 rw−p 0001 f 0 0 0 f d : 0 1 163870 /
u s r / l i b / ld −2.15. so
42 cb5000 −42e5d000 r−xp 00000000 f d : 0 1 163871 /
u s r / l i b / l i b c −2.15. so
42 e5d000 −42 e 5 f 0 0 0 r−−p 001 a8000 f d : 0 1 163871 /
u s r / l i b / l i b c − 2 . 1Unix
Philippe Langevin (IMATH, USTV)
5 .etsProgrammation
o Shell Automne  270 / 391
processus commande processus

commande processus

ps, pstree, top, uptime


time, time
nice, ulimit
gdb, ltrace, strace
kill, killall
wait
jobs, bg, fg
at, batch
nohup
disown

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  271 / 391
processus gentillesse

calcul

1 #include <stdio.h>
2 #include <stdlib.h>
3 int main( int argc, char∗argv[] )
4 {
5 int x = atoi( argv[1] );
6 int y = 1;
7 while ( −−x )
8 y = (x ∗ y) % 23;
9 return y;
10 }

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  272 / 391
processus gentillesse

[Link]

#!/ b i n / b a s h −v
g c c −W a l l −O2 c a l c . c −o c a l c . e x e
. / c a l c . e x e 100000000 &
sleep 1
ps −o cmd , pcpu
CMD %CPU
evince proc . pdf 2.7
ba s h 0.0
make −B pcpu . o u t 0.0
/ b i n / sh −c . / pcpu . sh >& pcp 0 . 0
/ b i n / b a s h −v . / pcpu . sh 0.0
. / c a l c . e x e 100000000 102
ps −o cmd , pcpu 0.0

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  273 / 391
processus gentillesse

charge/wait

1 #/bin/bash −v
2 cpt=$1
3 uptime | sed ’ s/load/\nload/’
4 while [ $cpt −gt 0 ]
5 do
6 /usr/bin/time −−format=”r=%U c=%c t=%E” \
7 ./ calc . exe 500000000 &
8 let cpt−−
9 done
10 wait
11 date

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  274 / 391
processus gentillesse

charge/wait
1 4 : 1 1 : 4 0 up 7 days , 2 1 : 2 3 , 5 u s e r s ,
l o ad average : 0 ,15 , 0 ,53 , 0 ,34
r =12.54 c =265 t = 0 : 1 2 . 8 0
r =12.52 c =162 t = 0 : 1 2 . 9 0
r =12.52 c =644 t = 0 : 1 3 . 0 8
r =12.47 c =797 t = 0 : 1 3 . 6 8
ven . s e p t . 20 1 4 : 1 1 : 5 4 CEST 2013
1 4 : 1 1 : 5 4 up 7 days , 2 1 : 2 3 , 5 u s e r s ,
l o ad average : 0 ,80 , 0 ,66 , 0 ,39
r =12.54 c =958 t = 0 : 1 9 . 1 0
r =12.53 c =928 t = 0 : 1 9 . 2 7
r =12.54 c =1080 t = 0 : 1 9 . 3 0
r =12.53 c =1061 t = 0 : 1 9 . 3 8
r =12.51 c =833 t = 0 : 1 9 . 5 5
r =12.48 c =866 t = 0 : 1Unix
Philippe Langevin (IMATH, USTV)
9 .et7Programmation
2 Shell Automne  275 / 391
processus gentillesse

gentillesse
1 #/bin/bash −v
2 cpt=$1
3 gtle =0
4 while [ $cpt −gt 0 ]
5 do
6 /usr/bin/time −−format=”nice=$gtle cpu=%P ctx=%c
total=%E” \
7 nice −n $gtle ./ calc . exe 500000000 &
8 let cpt−−
9 let gtle +=5
10 done
11 lscpu | grep ’ (s)’ | iconv −f UTF−8 −t ASCII −c
12 ps −opid,nice,psr , cmd −C [Link]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  276 / 391
processus gentillesse

gentillesse
Mode ( s ) o p r a t o i r e ( s ) d e s p r o c e s s e u r s : 32− b i t ,
64− b i t
Processeur ( s ) : 4
L i s t e de p r o c e s s e u r ( s ) en l i g n e : 0−3
Thread ( s ) p a r c u r : 2
Cur ( s ) p a r s o c k e t : 2
Socket ( s ) : 1
PID NI PSR CMD
20555 5 3 . / c a l c . e x e 500000000
20557 0 1 . / c a l c . e x e 500000000
20560 10 3 . / c a l c . e x e 500000000
20561 15 3 . / c a l c . e x e 500000000
20562 19 0 . / c a l c . e x e 500000000
n i c e =0 cpu=97% c t x =107 t o t a l = 0 : 1 2 . 7 1
n i c e =5 cpu=91% c t x =1039
Philippe Langevin (IMATH, USTV)
t o t a l = 0 : 1 3 . 6 3 Automne 
Unix et Programmation Shell 277 / 391
processus ressource

limites
. / p r o c . e x e l i m i t s | s e d −E ’ s / u n l i m i t e d /∗/ g ; s / [
\ t ]+/ /g ’
Limit S o f t Hard U n i t s
Max cpu t i m e ∗ ∗ seconds
Max f i l e s i z e ∗ ∗ bytes
Max d a t a s i z e ∗ ∗ bytes
Max s t a c k s i z e 10485760 ∗ bytes
Max c o r e f i l e s i z e 0 ∗ bytes
Max r e s i d e n t s e t ∗ ∗ bytes
Max p r o c e s s e s 1024 7911 p r o c e s s e s
Max open f i l e s 1024 1024 f i l e s
Max l o c k e d memory 65536 65536 b y t e s
Max a d d r e s s s p a c e ∗ ∗ bytes
Max f i l e l o c k s ∗ ∗ locks
Max p e n d i n g s i g n a l sUnix et7911
Philippe Langevin (IMATH, USTV)
7911 s i g n a l s Automne  278 / 391
Programmation Shell
processus ressource

limit.c
1 #include <sys/time.h>
2 #include <sys/resource.h>
3 #include <stdio.h>
4 int main( void )
5 {
6 struct rlimit z;
7 printf (”limites : souple maximum\n”);
8 getrlimit ( RLIMIT AS, &z );
9 printf (”mem :%10lu %10lu\n”, [Link] cur, z. rlim max);
10 getrlimit ( RLIMIT NOFILE, &z );
11 printf (”fic :%10lu %10lu\n”, [Link] cur , z. rlim max);
12 getrlimit ( RLIMIT NPROC, &z );
13 printf (”proc :%10lu %10lu\n”, [Link] cur , z. rlim max);
14 getrlimit ( RLIMIT STACK, &z );
15 printf (”pile
Philippe Langevin (IMATH, USTV)
:%10luUnix%10lu\n”, [Link] cur , z. rlim
et Programmation Shell
max);
Automne  279 / 391
processus ressource

./ l i m i t . exe
limites : souple maximum
mem : 4 2 9 4 9 6 7 2 9 5 4294967295
fic : 1024 1024
proc : 1024 7911
pile : 10485760 4294967295
cpu : 4 2 9 4 9 6 7 2 9 5 4294967295

Temps UCT l i m i t e e x p i r e

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  280 / 391
processus ressource

stack.c
1 #include <signal. h>
2 #include <stdio.h>
3 #include <stdlib . h>
4 int n = 0;
5 void go( void )
6 {
7 //printf(” %d\n”, n );
8 n++;
9 go( );
10 }
11
12 int main( int argc, char∗argv[] )
13 {
14 go( );
15 return 0;
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  281 / 391
processus ressource

[Link]
1 #!/bin/bash −v
2 ulimit −s
3 10240
4 echo −e ’display n\nrun\nquit’ > /tmp/[Link]
5 gdb −q −x /tmp/[Link] ../src/[Link]\
6 | grep SIG −A3
7 Program received signal SIGSEGV, Segmentation fault.
8 go () at stack. c:9
9 9 go( );
10 1: n = 786223
11 ulimit −s 0
12 gdb −q −x /tmp/[Link] ../src/[Link]\
13 | grep SIG −A3
14 Program received signal SIGSEGV, Segmentation fault.
15 go () at stack. c:9 Unix et Programmation Shell
Philippe Langevin (IMATH, USTV) Automne  282 / 391
processus sous-processus

sous-processus

Un processus peut lancer des sous-processus de plusieurs manières :


fork : le sous-processus hérite d’une copie contexte.
clone : partage de variables.
execve : exécute un binaire ou un script.
pthread : processus léger
Dans les cas lourds/léger, un processus parent attend (normalité) la
fin des sous-processus, et les sous-processus signalent leur
terminaison.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  283 / 391
processus job

job
Les sous-processus du shell (jobs ) peuvent être en :
avant plan
arrière plan
La commande interne jobs donne la liste des sous-processus du shell.
1 #!/bin/bash −v
2 sleep 10 &
3 sleep 5 &
4 jobs
5 [1]− Running sleep 10 &
6 [2]+ Running sleep 5 &
7 ps −p $!
8 PID TTY TIME CMD
9 2812 pts/1 [Link] sleep
10 jobs −l %1
11 [1]− 2811 Running Unix et Programmation Shellsleep 10
Philippe Langevin (IMATH, USTV)
& Automne  284 / 391
processus job

tâche en arrière plan


s l e e p 120 & s l e e p 60 & s l e e p 30 &
[ 1 ] 3649
[ 2 ] 3650
[ 3 ] 3651
k i l l −s SIGSTOP %2
jobs
[1] En c o u r s d ’ e x e c u t i o n s l e e p 120 &
[ 2 ] + S to p p e s l e e p 60
[3] − En c o u r s d ’ e x e c u t i o n s l e e p 30 &
k i l l −s SIGKILL %1
[1] Processus arrete s l e e p 120
jobs
[ 2 ] + S to p p e s l e e p 60
[3] − En c o u r s d ’ e x e c u t i o n s l e e p 30 &
[3] − F i n i
Philippe Langevin (IMATH, USTV)
s l e e p 30 Automne 
Unix et Programmation Shell 285 / 391
processus processus léger

thread POSIX
1 #include <unistd.h>
2 #include <sys/types.h>
3 #include <sys/wait.h>
4 #include <stdio.h>
5 #include <errno.h>
6 #include <stdlib.h>
7 #include <pthread.h>
8
9 void ∗ task (void ∗argv)
10 {
11 int x = ∗((int ∗) argv);
12 sleep (x);
13 pthread exit (0);
14 }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  286 / 391
processus processus léger

bibliotèque pthread
1 int main (int argc, char ∗argv[] )
2 {
3 pid t pid;
4 pthread t th;
5 int status , x = atoi (argv[1]) ;
6 if (( pid = fork ()) < 0)
7 perror (”fork ”), exit (1);
8
9 if ( pid )
10 wait (&status);
11 else {
12 if (pthread create (&th, NULL, task, &x) < 0)
13 perror (”thread”), exit (2);
14 pthread join (th, NULL);
15 }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  287 / 391
processus processus léger

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  288 / 391
processus processus léger

fork, pthread create


1 #!/bin/bash −v
2 ./ fils . exe 30 &
3 sleep 5
4 ps −T −o pid,ppid,spid,cmd
5 kill $!
6 ps −T −o pid,ppid,spid,cmd
[Link]
processus lourds et légers de make -B [Link] ?
1 fils . exe : fils . c
2 gcc −Wall fils . c −o fils . exe −lpthread
3
4 fils . out : fils . exe fils . sh
5 ./ fils . sh >& fils . out
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  289 / 391
processus processus léger

. / f i l s . e x e 30 &
sleep 5
ps −T −o p i d , p p i d , s p i d , u s e r , cmd
1462 1415 1462 pl / b i n / b ash
2119 1462 2119 pl make −B f i l s . o u t
2125 2119 2125 pl / b i n / sh −c . / f i l s . sh
>& f i l s . o u t
2126 2125 2126 pl / b i n / b ash −v . / f i l s .
sh
2127 2126 2127 pl ./ f i l s . e x e 30
2129 2127 2129 pl ./ f i l s . e x e 30
2129 2127 2130 pl ./ f i l s . e x e 30
2131 2126 2131 pl ps −T −o p i d , p p i d ,
s p i d , u s e r , cmd
kill $!
ps −T −o p i d , p p i d , s p i d , u s e r , cmd
1462 1415 1462 pl / b i n / b ash
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  290 / 391
redirection

9 - redirection

flux vs descripteur
redirection
tracer un processus
descripteur de fichier
diagnostic
substitution de processus

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  291 / 391
redirection flux vs descripteur

fichier C
La bibliothéque glibc propose aux C-programmeurs de puissantes
fonctions d’entrées/sorties pour opérer sur les flux.
1 #include <stdlib.h>
2 #include <stdio.h>
3 int main( int argc, char ∗argv[] )
4 {
5 char∗ msg = ”hello”;
6 FILE ∗dst;
7 dst = fopen( ”/tmp/[Link]”, ”w” );
8 if ( ! dst ) perror (”fopen”), exit (1);
9 fprintf (dst, ”%s”, msg );
10 fclose(dst);
11 return 0;
12 }
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  292 / 391
redirection flux vs descripteur

flux
Les flux sont gérer par une structure relativement complexe :
gdb −−q u i e t
−x f l u x . gdb f l u x .
exe
| g r e p −A14
fileno
> f l u x . out

1 set pagination off


2 break main
3 run
4 whatis FILE
5 ptype FILE
6 quit
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  293 / 391
redirection flux vs descripteur

flux
Les flux sont gérer par une structure relativement complexe :
gdb −−q u i e t
−x f l u x . gdb f l u x .
exe 1 type = struct IO FILE {

| g r e p −A14 2 int flags ;


3 char ∗ IO read ptr ;
fileno 4 char ∗ IO read end;
5 char ∗ IO read base;
> f l u x . out 6 char ∗ IO write base ;
7 char ∗ IO write ptr ;
8 char ∗ IO write end ;
1 set pagination off 9 char ∗ IO buf base;
10 char ∗ IO buf end;
2 break main 11 char ∗ IO save base;
3 run 12 char ∗ IO backup base;
13 char ∗ IO save end;
4 whatis FILE 14 struct IO marker ∗ markers;
15 struct IO FILE ∗ chain;
5 ptype FILE 16 int fileno ;
6 quit
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  293 / 391
redirection flux vs descripteur

descripteur
Un descripteur de fichier est une entrée dans une table des fichiers.
Les ES sont gérées par des appels de bas niveau : read, write.
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 int main( int argc, char ∗argv[] )
7 {
8 char∗ msg = ”hello”;
9 int fd;
10 fd = open( ”/tmp/[Link]”, O WRONLY );
11 if ( fd < 0 ) exit (1);
12 write( fd , msg, 6);
13 close( fd );
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  294 / 391
redirection redirection

cat
La commande cat copie sur la sortie standard :
cat
H e l l o World <− c l a v i e r
H e l l o World <− e c r a n
Les descripteurs standards peuvent êre redirigés vers des descripteurs
ou des fichiers
cat >f i c h i e r
H e l l o World <− c l a v i e r

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  295 / 391
redirection redirection

cat
La commande cat copie sur la sortie standard :
cat
H e l l o World <− c l a v i e r
H e l l o World <− e c r a n
Les descripteurs standards peuvent êre redirigés vers des descripteurs
ou des fichiers
cat >f i c h i e r
H e l l o World <− c l a v i e r
cat f i c h i e r
H e l l o World

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  295 / 391
redirection redirection

cat
La commande cat copie sur la sortie standard :
cat
H e l l o World <− c l a v i e r
H e l l o World <− e c r a n
Les descripteurs standards peuvent êre redirigés vers des descripteurs
ou des fichiers
cat >f i c h i e r
H e l l o World <− c l a v i e r
cat f i c h i e r
H e l l o World
cat <f i c h i e r
H e l l o World
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  295 / 391
redirection redirection

cat
La commande cat copie sur la sortie standard :
cat
H e l l o World <− c l a v i e r
H e l l o World <− e c r a n
Les descripteurs standards peuvent êre redirigés vers des descripteurs
ou des fichiers
cat >f i c h i e r
H e l l o World <− c l a v i e r
cat f i c h i e r
H e l l o World
cat <f i c h i e r
H e l l o World
c a t < f i c h i e r >o u tUnix
Philippe Langevin (IMATH, USTV) p uettProgrammation Shell Automne  295 / 391
redirection redirection

fichier standard

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  296 / 391
redirection redirection

redirection

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  297 / 391
redirection redirection

descripteurs et fichiers spéciaux

0 : entrée standard
1 : sortie standard
2 : sortie erreur standard
extern FILE *stdin;
extern FILE *stdout;
extern FILE *stderr;
/dev/null
/dev/random
/dev/zero
/dev/tcp/hote/port

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  298 / 391
redirection redirection

évaluation
debug Condidérons les fichiers :
1 cat <input >output
[Link]

1 cat <input >output 2>&1


[Link]

1 cat <input 2>&1 >output


[Link]

d’aprés le manuel, la troisième est incorrecte.

s t r a c e −o { f i c } − f f −e t r a c e ={ l s t } ba sh {
script}
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  299 / 391
redirection redirection

En effet
1 :: cat direct . sh erreur 2>&1 > /tmp/foo
2 cat: erreur : Aucun fichier ou dossier de ce type
3
4 :: cat direct . sh erreur > /tmp/bar 2>&1

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  300 / 391
redirection redirection

En effet
1 :: cat direct . sh erreur 2>&1 > /tmp/foo
2 cat: erreur : Aucun fichier ou dossier de ce type
3
4 :: cat direct . sh erreur > /tmp/bar 2>&1

1 :: echo $?
2 1

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  300 / 391
redirection redirection

En effet
1 :: cat direct . sh erreur 2>&1 > /tmp/foo
2 cat: erreur : Aucun fichier ou dossier de ce type
3
4 :: cat direct . sh erreur > /tmp/bar 2>&1

1 :: echo $?
2 1

1 :: cat /tmp/foo
2 cat <input >output
3
4 :: cat /tmp/bar
5 cat <input >output
6 cat: erreur : Aucun fichier ou dossier de ce type
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  300 / 391
redirection redirection

direction : gauche à droite !

1 ls >output 2>&1
2 ls 2>&1 >output

BASH( 1 )
I l y a deux f o r m e s p o u r e f f e c t u e r une d o u b l e
redirection :
&>mot et >&mot
On p r e f e r e g e n e r a l e m e n t l a p r e m i e r e , e q u i v a l e n t e
a:
>mot 2>&1
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  301 / 391
redirection redirection

aspect syntaxique
Avec bash, les entrées/sorties sont redirigeables à l’aide des <,> :
1 cat <input >output
2 >output cat <input
sont des abbréviations de
1 cat 0<input 1>output
2 1>output cat 0<input

1 3.6.1 Input : [ n] < word


2 3.6.2 Output : [ n] > word :simil : [ n] >> word
3 3.6.4 Standards : &> word :equiv: >word 2>&1
4 3.6.5 Appending : &>>word :equiv: >> word 2>&1
5 3.6.6 Here Documents
6 <<[−]word
7 here−document
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  302 / 391
redirection redirection

[Link]

1 #!/bin/bash
2 set −v
3 nc −l 31415 > /tmp/[Link] &
4 sleep 1
5 netstat −plent −−ip | sed −E ’s/[ \t]+/ /g’
6 set +v
7 cat > /dev/tcp/localhost/31415 <<− this
8 bash redirige pas mal de chose !
9 this
10 set −v
11 cat /tmp/[Link]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  303 / 391
redirection redirection

[Link]
1 nc −l 31415 > /tmp/[Link] &
2 sleep 1
3 netstat −plent −−ip | sed −E ’s/[ \t]+/ /g’
4 (Tous les processus ne peuvent etre identifies , les infos
sur les processus
5 non possedes ne seront pas affichees , vous devez etre root
pour les voir toutes .)
6 Connexions Internet actives (seulement serveurs )
7 Proto Recv−Q Send−Q Local Address Foreign Address State
Utilisatr Inode PID/Program name
8 tcp 0 0 [Link]:57250 [Link]:∗ LISTEN 29 8802 −
9 tcp 0 0 [Link]:111 [Link]:∗ LISTEN 0 8689 −
10 tcp 0 0 [Link]:22 [Link]:∗ LISTEN 0 9505 −
11 tcp 0 0 [Link]:31415 [Link]:∗ LISTEN 501 59251 2845/nc
12 tcp 0 0 [Link]:631Unix0.0.0.0:∗
Philippe Langevin (IMATH, USTV)
−  304 / 391
LISTEN 0 9059Automne
et Programmation Shell
redirection tracer un processus

Tracer un processus
Les outils de traçages :
ltrace : trace les appels aux bibliothèques.
strace : trace les signaux et les appels systèmes.
permettent d’analyser finement les processus.
1 hello . out : hello . exe
2 strace −o hello. sys \
3 −e read,write , open,execve, close , stat ./ hello . exe
4 ltrace −o hello. lib ./ hello . exe
5 ltrace −c −o [Link] ./ hello . exe
6 strace −c −o [Link] ./hello . exe
7 sed ’ s/[ ]\+/ /g’ hello . tmp > [Link]
8 awk ’/hello . out/,/@@@/’ makefile > hello. out
makefile
[ptrace]
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  305 / 391
redirection tracer un processus

src/hello.c

1 #include <stdlib.h>
2 #include <stdio.h>
3 int main( int argc, char∗argv[] )
4 {
5 int nb;
6 FILE ∗dst;
7 dst = fopen( ”hello . txt ”, ”w” );
8 if ( ! dst ) perror (”fopen”), exit (1);
9 nb = fprintf (dst, ”%s”, argv[0] );
10 fprintf ( stderr , ”%d” , nb );
11 return 0;
12 }

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  306 / 391
redirection tracer un processus

remarque

Le code LATEX du transparent suivant contient la ligne :

\lstinputlisting[style=make]{src/[Link]}

qui explique la dernière ligne des actions de la cible [Link].

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  307 / 391
redirection tracer un processus

[Link] : trace des appels bibliothèques

% time seconds usecs / c a l l calls function


−−−−−− −−−−−−−−−−− −−−−−−−−−−− −−−−−−−−− −−−−−−−−−−−−−−−−−−−−
53.89 0.000603 603 1 fopen
46.11 0.000516 258 2 fprintf
−−−−−− −−−−−−−−−−− −−−−−−−−−−− −−−−−−−−− −−−−−−−−−−−−−−−−−−−−
100.00 0.001119 3 total

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  308 / 391
redirection tracer un processus

[Link] : trace des appels systèmes

% time seconds usecs / c a l l calls errors syscall


−−−−−− −−−−−−−−−−− −−−−−−−−−−− −−−−−−−−− −−−−−−−−− −−−−−−−−−−−−−−−−
91.34 0 . 0 0 0 7 3 8 738 1 e x e c v e
8.66 0 . 0 0 0 0 7 0 8 9 mmap
0.00 0.000000 0 1 read
0.00 0.000000 0 2 w r i t e
0.00 0 . 0 0 0 0 0 0 0 3 open
0.00 0.000000 0 2 close
0.00 0.000000 0 3 fstat
0.00 0.000000 0 3 mprotect
0.00 0 . 0 0 0 0 0 0 0 1 munmap
0.00 0.000000 0 3 brk
0.00 0.000000 0 1 1 access
0.00 0.000000 0 1 arch prctl
−−−−−− −−−−−−−−−−− −−−−−−−−−−− −−−−−−−−− −−−−−−−−− −−−−−−−−−−−−−−−−
100.00 0 . 0 0 0 8 0 8 30 1 total

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  309 / 391
redirection tracer un processus

[Link] : trace des appels bibliothèques

l i b c s t a r t m a i n ( 0 x4005e4 , 1 , 0 x 7 f f f a e 1 c d 2 7 8 , 0
x400680 , 0 x400670 < u n f i n i s h e d . . . >
f o p e n ( ” h e l l o . t x t ” , ”w” )
= 0 xae7010
f p r i n t f ( 0 xae7010 , ”%s ” , ” . / h e l l o . e x e ” )
= 11
f p r i n t f ( 0 x 3 9 5 d f 7 6 8 6 0 , ”%d ” , 1 1 )
= 2
+++ e x i t e d ( s t a t u s 0 ) +++

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  310 / 391
redirection tracer un processus

[Link] : trace des appels systèmes

e x e c v e ( ” . / h e l l o . e x e ” , [ ” . / h e l l o . e x e ” ] , [ / ∗ 54 v a r s
∗/]) = 0
open ( ” / e t c / l d . s o . c a c h e ” , O RDONLY) = 3
close (3) = 0
open ( ” / l i b 6 4 / l i b c . s o . 6 ” , O RDONLY) = 3
r e a d ( 3 , ”\177 ELF
\2\1\1\3\0\0\0\0\0\0\0\0\3\0 >\0\1\0\0\0000\354\301
8 3 2 ) = 832
close (3) = 0
open ( ” h e l l o . t x t ” , O WRONLY | O CREAT | O TRUNC , 0 6 6 6 ) =
3
w r i t e (2 , ”11” , 2) = 2
w r i t e (3 , ”./ h e l l o . exe ” , 11) = 11

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  311 / 391
redirection descripteur de fichier

open etc. . .
OPEN( 2 ) L i n u x Programmer ’ s Manual
SYNOPSIS
i n t open ( c o n s t c h a r ∗ path , i n t f l a g s ) ;
i n t open ( c o n s t c h a r ∗ path , i n t f l a g s , mode t md)
;
i n t c r e a t ( c o n s t c h a r ∗ path , mode t mode ) ;
DESCRIPTION
G i v e n a pathname f o r a f i l e , open ( ) r e t u r n s a
f i l e de scri ptor , a small , nonnegative i n t e g e r f o r
use i n subsequent system calls .
The f i l e d e s c r i p t o r r e t u r n e d by a s u c c e s s f u l
c a l l w i l l be t h e l o w e s t −numbered f r e e f i l e
descriptor
SEE ALSO
chmod ( 2 ) , chown , c l o s e , dup , f c n t l , l i n k , l s e e k ,
mknod , mmap, mount , Unix
Philippe Langevin (IMATH, USTV)
openat , r e a d , s o c k e t ,Automne
et Programmation Shell
s t a
t , 312 / 391
redirection descripteur de fichier

table des descripteurs

Un processus possède une table de 255 descripteurs de fichiers, les


trois premiers sont initialisés :
0 : entrée standard
1 : sortie standard
2 : erreur standard
L’appel systeme open( fichier, mode ) configure un descripteur
de fichier pour des opérations de lecture read, d’écriture write avec
le fichier physique.
-1 : appel système a échoué !
L’appel système close ferme un descripteur. Les appels systeme dup
permettent de manipuler les descripteurs.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  313 / 391
redirection descripteur de fichier

dupliquer
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <stdio.h>
7 int main( int argc, char∗argv[] )
8 { int fd;
9 fd = open( argv[1],O RDWR |O CREAT|O TRUNC, 0644 );
10 if ( fd < 0 ) perror (”open”), exit (1);
11 close( 1 );
12 if ( dup( fd ) < 0 ) perror (”dup”), exit (1);
13 close(fd);
14 if ( execlp ( ”ls ”, ”ls ”, ”−alt”, NULL ) < 0 )
15 perror (”execlp ”), Unix
Philippe Langevin (IMATH, USTV)
exit (1);
et Programmation Shell Automne  314 / 391
redirection descripteur de fichier

dupliquer

g c c −W a l l dup . c −o dup . e x e
. / dup . e x e dup . t x t
head −5 dup . t x t
t o t a l 300
−rw−r−−r −−. 1 p l pl 0 14 s e p t . 1 4 : 0 7
dup . t x t
−rw−rw−r −−. 1 p l pl 1313 14 s e p t . 1 4 : 0 7
sdup . o u t
−rw−rw−r −−. 1 p l pl 2160 14 s e p t . 1 4 : 0 7
sdup . tmp
−rw−rw−r −−. 1 p l pl 2861 14 s e p t . 1 4 : 0 7
ldup . out

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  315 / 391
redirection descripteur de fichier

dup
DUP( 2 ) L i n u x Programmer ’ s Manual
NAME
dup , dup2 , dup3 − d u p l i c a t e a f i l e d e s c r i p t o r
SYNOPSIS
i n t dup ( i n t o l d f d ) ;
i n t dup2 ( i n t o l d f d , i n t newfd ) ;
DESCRIPTION
These s y s t e m c a l l s c r e a t e a copy o f o l d f d .

dup ( ) u s e s t h e l o w e s t −numbered u n u s e d d e s c r i p t o r
f o r t h e new d e s c r i p t o r .

dup2 ( ) makes newfd be t h e copy o f o l d f d ,


c l o s i n g newfd f i r s t i f n e c e s s a r y .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  316 / 391
redirection descripteur de fichier

[Link] : trace des appels bibliothèques


% time seconds usecs / c a l l calls function
−−−−−− −−−−−−−−−−− −−−−−−−−−−− −−−−−−−−− −−−−−−−−−−−−−−−−−−−−
29.91 0.178987 121 1474 s t r l e n
11.49 0.068741 121 564 ctype get mb cur max
7.76 0.046463 15487 3 dcgettext
6.22 0.037220 120 310 memcpy
5.61 0.033547 120 278 f p u t s u n l o c k e d
4.18 0.025027 120 208 l o c a l e c o n v
3.51 0.021030 404 52 i s w p r i n t
2.75 0.016455 5485 3 getpwuid
2.26 0.013501 192 70 s t r s t r
2.03 0.012120 130 93 m a l l o c
1.93 0.011560 167 69 a c l e x t e n d e d f i l e
1.83 0.010972 120 91 errno location
1.82 0.010910 158 69 l g e t f i l e c o n
1.70 0.010199 147 69 l o c a l t i m e
1.70 0.010196 147 69 lxstat64
1.52 0.009074 120 75 s t r c p y
1.43 0.008538 121 70 r e a d d i r 6 4
1.41 0.008452 122 69 sprintf chk
1.39 0.008315 120 69 f w r i t e u n l o c k e d
1.38 0.008280 120 69 s t p c p y
1.37 0.008205 118 69 mempcpy chk
1.31 0.007868 655 12 w c s w i d t h
1.12 0.006725 120 56 memset
0.85 0.005068 181 28 f r e e
0.77 0.004597 191 24 mbstowcs
0.41 0.002436 203 12 n l l a n g i n f o
0.38 0.002297 120 19 s t r c o l l
0.38 0.002285 190 12 mempcpy
0.33 0.001968 984 2 fflush
Philippe
0 . 1 9 Langevin
0 . 0 0(IMATH,
1141 USTV) 380 Unix et3 Programmation
getgrgid Shell Automne  317 / 391
redirection descripteur de fichier

[Link] : trace des appels systèmes


% time seconds usecs / c a l l calls errors syscall
−−−−−− −−−−−−−−−−− −−−−−−−−−−− −−−−−−−−− −−−−−−−−− −−−−−−−−−−−−−−−−
56.65 0 . 0 0 0 2 7 7 55 5 s o c k e t
31.08 0 . 0 0 0 1 5 2 4 37 close
7.98 0 . 0 0 0 0 3 9 1 47 mmap2
4.29 0 . 0 0 0 0 2 1 0 69 lstat64
0.00 0 . 0 0 0 0 0 0 0 23 r e a d
0.00 0.000000 0 1 w r i t e
0.00 0 . 0 0 0 0 0 0 0 38 10 open
0.00 0.000000 0 3 1 execve
0.00 0.000000 0 2 2 access
0.00 0 . 0 0 0 0 0 0 0 1 dup
0.00 0.000000 0 4 brk
0.00 0.000000 0 2 2 ioctl
0.00 0 . 0 0 0 0 0 0 0 13 munmap
0.00 0 . 0 0 0 0 0 0 0 1 uname
0.00 0 . 0 0 0 0 0 0 0 12 m p r o t e c t
0.00 0.000000 0 2 llseek
0.00 0.000000 0 2 rt sigaction
0.00 0.000000 0 1 r t s i g p r o c m a s k
0.00 0.000000 0 1 getrlimit
0.00 0 . 0 0 0 0 0 0 0 69 s t a t 6 4
0.00 0 . 0 0 0 0 0 0 0 28 fstat64
0.00 0.000000 0 2 getdents64
0.00 0 . 0 0 0 0 0 0 0 138 138 getxattr
0.00 0 . 0 0 0 0 0 0 0 69 lgetxattr
0.00 0.000000 0 2 f u t e x
0.00 0.000000 0 2 set thread area
0.00 0.000000 0 1 set tid address
0.00 0.000000 0 1 c l o c k g e t t i m e
0.00 0.000000 0 2 statfs64
Philippe
0 . 0 0 Langevin
0 . 0 0 0 0(IMATH,
0 0 0 USTV)
1 openat Unix et Programmation Shell Automne  318 / 391
redirection diagnostic

Diagnostic

Nous pouvons faire une analyse des appels système du bash de deux
manières. Dans les deux cas, il faut penser à tracer les
sous-processus :
1 On place les commandes à analyser dans un script : :
s t r a c e −o { f i c } − f f −e t r a c e ={ l s t } ba sh {
script}
2 On détermine le pid du shell à tracer, et on trace le les
commandes à analyser par une capture :
s t r a c e −o { f i c } − f f −e t r a c e ={ l s t } −p { p i d
}

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  319 / 391
redirection diagnostic

memo [Link]
c l o s e (255) = 0
open ( ” i n p u t ” , O RDONLY | O LARGEFILE ) = 3
dup2 ( 3 , 0 ) = 0
close (3) = 0
open ( ” o u t p u t ” , O WRONLY | O CREAT | O TRUNC | O LARGEFILE
, 0666) = 3
dup2 ( 3 , 1 ) = 1
close (3) = 0
e x e c v e ( ” / b i n / c a t ” , [ ” c a t ” ] , [ / ∗ 46 v a r s ∗ / ] ) = 0
open ( ” / e t c / l d . s o . c a c h e ” , O RDONLY | O CLOEXEC) = 3
close (3) = 0
open ( ” / l i b / l i b c . s o . 6 ” , O RDONLY | O CLOEXEC) = 3
r e a d ( 3 , ”\177 ELF
\1\1\1\3\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\220\347\31
B4 \ 0 \ 0 \ 0 ” . . . , 5 1 2 ) = 512
close (3)
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell
=Automne
0  320 / 391
redirection diagnostic

memo [Link]
c l o s e (255) = 0
open ( ” i n p u t ” , O RDONLY | O LARGEFILE ) = 3
dup2 ( 3 , 0 ) = 0
close (3) = 0
open ( ” o u t p u t ” , O WRONLY | O CREAT | O TRUNC | O LARGEFILE
, 0666) = 3
dup2 ( 3 , 1 ) = 1
close (3) = 0
dup2 ( 1 , 2 ) = 2
e x e c v e ( ” / b i n / c a t ” , [ ” c a t ” ] , [ / ∗ 46 v a r s ∗ / ] ) = 0
open ( ” / e t c / l d . s o . c a c h e ” , O RDONLY | O CLOEXEC) = 3
close (3) = 0
open ( ” / l i b / l i b c . s o . 6 ” , O RDONLY | O CLOEXEC) = 3
r e a d ( 3 , ”\177 ELF
\1\1\1\3\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\220\347\31
B4 \ 0 \ 0 \ 0 ” . . . , 5 1 2Unix
Philippe Langevin (IMATH, USTV)
) = 512
et Programmation Shell Automne  321 / 391
redirection diagnostic

memo [Link]
c l o s e (255) = 0
open ( ” i n p u t ” , O RDONLY | O LARGEFILE ) = 3
dup2 ( 3 , 0 ) = 0
close (3) = 0
dup2 ( 1 , 2 ) = 2
open ( ” o u t p u t ” , O WRONLY | O CREAT | O TRUNC | O LARGEFILE
, 0666) = 3
dup2 ( 3 , 1 ) = 1
close (3) = 0
e x e c v e ( ” / b i n / c a t ” , [ ” c a t ” ] , [ / ∗ 46 v a r s ∗ / ] ) = 0
open ( ” / e t c / l d . s o . c a c h e ” , O RDONLY | O CLOEXEC) = 3
close (3) = 0
open ( ” / l i b / l i b c . s o . 6 ” , O RDONLY | O CLOEXEC) = 3
r e a d ( 3 , ”\177 ELF
\1\1\1\3\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0\220\347\31
B4 \ 0 \ 0 \ 0 ” . . . , 5 1 2Unix
Philippe Langevin (IMATH, USTV)
) = 512
et Programmation Shell Automne  322 / 391
redirection substitution de processus

substitution de processus

La substitution de processus s’appuie sur le mécanisme des tubes


nommés (FIFOs) ou la méthode /dev/fd de noms de fichiers.

1
2 comm −3 <(sort x | uniq) <(sort y | uniq)

Il ne s’agit pas d’une redirection !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  323 / 391
redirection substitution de processus

man comm
COMM( 1 ) U s e r Commands
NAME comm − compare two s o r t e d f i l e s l i n e by l i n e
SYNOPSIS comm [ −123 ] FILE1 FILE2
Compare s o r t e d f i l e s FILE1 and FILE2 l i n e by l i n e
.
With no o p t i o n s , p r o d u c e t h r e e −column o u t p u t . Column
1 c o n t a i n s l i n e s u n i q u e t o FILE1 , column 2 c o n t a i n s
l i n e s u n i q u e t o FILE2 , and column t h r e e c o n t a i n s
l i n e s common t o b o t h f i l e s . −X s u p p r e s s column X .
EXAMPLES
comm −12 f i l e 1 f i l e 2
P r i n t o n l y l i n e s p r e s e n t i n b o t h f i l e 1 and
file2 .
comm −3 f i l e 1 f i l e 2
P r i n t l i n e s i n f i l e 1 n o t i n f i l e 2 , and v i c e
versa .
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  324 / 391
redirection substitution de processus

[Link]
1 #!/bin/bash −v
2 #from Linux Journal
3 echo −e ’a\nf\nc\ng\ne\nb’ > x
4 echo −e ’c\ne\na\nd\nb\nf’ > y
5 sort x | uniq > /tmp/X
6 sort y | uniq > /tmp/Y
7 comm −3 /tmp/X /tmp/Y
8 d
9 g
10
11 comm −3 <(sort x | uniq) <(sort y | uniq)
12 sort y | uniq
13 sort x | uniq
14 d
15 g
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  325 / 391
pipeline

10 - pipeline

tracer des commandes


pipeline
tracer un pipeline

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  326 / 391
pipeline

traitement des commandes

Le prompt du shell matérialise une ligne de commande invitant


l’utilisateur à soumettre une instruction : une chaine de caractères
analysée par le shell pour lancer des commandes.
interne : traitée dans le processus.
externe : clone + execve.
complexe : clone

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  327 / 391
pipeline tracer des commandes

trace des commandes externes


1 #!/bin/bash
2 /bin/echo hello
3 echo HELLO
4 /bin/echo allo
[Link]

e c h o s . o u t : e c h o s . sh
s t r a c e −f −e t r a c e=e x e c v e , c l o n e , w a i t p i d , w r i t e \
−o e c h o s . s t r −e s i g n a l=SIGCHLD . /
e c h o s . sh

s e d −n ’ / e c h o s . o u t / , /HERE/p ’ m a k e f i l e > e c h o s .
out
[Link]
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  328 / 391
pipeline tracer des commandes

[Link]
19330 e x e c v e ( ” . / e c h o s . s h ” , [ ” . / e c h o s . s h ” ] , [ / ∗ 54
vars ∗/]) = 0
19330 c l o n e ( c h i l d s t a c k =0, f l a g s=
CLONE CHILD CLEARTID | CLONE CHILD SETTID | SIGCHLD ,
c h i l d t i d p t r =0 x 7 f e f 1 8 3 3 7 9 d 0 ) = 19331
19331 e x e c v e ( ” / b i n / echo ” , [ ” / b i n / echo ” , ” h e l l o ” ] ,
[ / ∗ 53 v a r s ∗ / ] ) = 0
19331 w r i t e ( 1 , ” h e l l o \n ” , 6 ) = 6
19330 −−− SIGCHLD ( C h i l d e x i t e d ) @ 0 ( 0 ) −−−
19330 w r i t e ( 1 , ”HELLO\n ” , 6 ) = 6
19330 c l o n e ( c h i l d s t a c k =0, f l a g s=
CLONE CHILD CLEARTID | CLONE CHILD SETTID | SIGCHLD ,
c h i l d t i d p t r =0 x 7 f e f 1 8 3 3 7 9 d 0 ) = 19332
19332 e x e c v e ( ” / b i n / echo ” , [ ” / b i n / echo ” , ” a l l o ” ] ,
[ / ∗ 53 v a r s ∗ / ] ) = 0
19332 w r i t e ( 1 , ” a l l o Unix
Philippe Langevin (IMATH, USTV)
\n ”et Programmation
, 5) Shell
=Automne
5  329 / 391
pipeline pipeline

pipeline

Le pipeline permet de chaı̂ner des processus de sorte que la sortie d’un


processus (stdout) alimente directement l’entrée (stdin) du suivant.
1 :: ps −eoppid | sort | uniq −c | sort −gr
2 | head −3 | sed ’ s/[ ]\+/:/g’
3 | cut −d’:’ −f3 | xargs ps −p

La mise en oeuvre d’un pipeline s’appuie sur les appels système :


fork / clone
pipe, dup2
execve

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  330 / 391
pipeline pipeline

processus

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  331 / 391
pipeline tracer un pipeline

cat </tmp/src | wc -l > /tmp/dst

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  332 / 391
pipeline tracer un pipeline

bash pipeline

1 echo hello > /tmp/src


2 call =open,close,pipe, dup2,execve, clone , fork
3 strace −o [Link] −f −e trace=$call −p $$ &
4 sleep 1
5 cat </tmp/src | wc −l >/tmp/dst
[Link]

. / p i p e . sh > p i p e . o u t
P r o c e s s 2291 a t t a c h e d
P r o c e s s 2298 a t t a c h e d
P r o c e s s 2299 a t t a c h e d
. / p i p e f i l t e r . sh p i p e . o u t

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  333 / 391
pipeline tracer un pipeline

trace brute
5377 −−− SIGCHLD { s i s i g n o=SIGCHLD , s i c o d e=
CLD EXITED , s i p i d =5379 , s i u i d =1000 ,
s i s t a t u s =0, s i u t i m e =0, s i s t i m e =0} −−−
5377 p i p e ( [ 3 , 4 ] ) = 0
5377 c l o n e ( c h i l d s t a c k =0, f l a g s=
CLONE CHILD CLEARTID | CLONE CHILD SETTID |
SIGCHLD , c h i l d t i d p t r =0xb778a728 ) = 5384
5384 c l o s e ( 2 5 5 ) = 0
5377 c l o s e ( 4 ) = 0
5377 c l o s e ( 4 ) = −1
EBADF ( Bad f i l e d e s c r i p t o r )
5377 c l o n e ( < u n f i n i s h e d . . . >
5384 c l o s e ( 3 ) = 0
5384 dup2 ( 4 , 1 < u n f i n i s h e d . . . >
5377 < . . . c l o n e resumed>
Philippe Langevin (IMATH, USTV)
c h i l d s t a c k =0,
Unix et Programmation Shell
f l a g s=
Automne  334 / 391
pipeline tracer un pipeline

filtre

1 #!/bin/bash
2
3 grep −Ev ’(locale | cache|BAD|\−1|255|exited|libc)’ pipe.
out \
4 | sed −r ’s/(clone ).∗=(.∗)/\1 := \2/’ \
5 | uniq | tr −d ’[A−Z]’ | cut −c1−44 > [Link]
6
7 set $(grep −oE ’ˆ[0−9]+’ [Link] | sort | uniq )
8 sed −i −e ”s/$1/& (A)/g” \
9 −e ”s/$2/& (B)/g” \
10 −e ”s/$3/& (C)/g” [Link]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  335 / 391
pipeline tracer un pipeline

trace filtrée (1/3)

5377 (A) −−− { s i s i g n o =, s i c o d e= , s i p i d =537


5377 (A) p i p e (3 , 4) = 0
5377 (A) c l o n e := 5384 (B)
5377 (A) close (4) = 0
5377 (A) c l o n e ( <u n f i n i s h e d ... >
5384 (B) close (3) = 0
5384 (B) dup2 ( 4 , 1 < u n f i n i s h e d . . . >
5377 (A) < . . . c l o n e := 5385 (C)
5384 (B) < . . . dup2 resumed> ) = 1
5384 (B) close (4) = 0
5377 (A) close (3) = 0
5385 (C) dup2 ( 3 , 0 ) = 0

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  336 / 391
pipeline tracer un pipeline

trace filtrée (2/3)

5385 (C) close (3) = 0


5384 (B) open ( ” / tmp/ s r c ” , | ) = 3
5384 (B) dup2 ( 3 , 0 ) = 0
5384 (B) close (3) = 0
5384 (B) e x e c v e ( ” / u s r / b i n / c a t ” , ” c a t ” , /∗ 55 va
5385 (C) open ( ” / tmp/ d s t ” , | | | , 0 6 6 6 ) = 3
5385 (C) dup2 ( 3 , 1 ) = 1
5385 (C) close (3) = 0
5384 (B) < . . . e x e c v e resumed> ) = 0
5385 (C) e x e c v e ( ” / u s r / b i n /wc ” , ”wc ” , ”− l ” , /∗ 5
5385 (C) < . . . e x e c v e resumed> ) = 0
5384 (B) < . . . open resumed> ) = 3
5384 (B) close (3) = 0

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  337 / 391
pipeline tracer un pipeline

trace filtrée (2/3)


5385 (C) < . . . open resumed> ) = 3
5384 (B) < . . . open resumed> ) = 3
5385 (C) c l o s e ( 3 ) = 0
5384 (B) c l o s e ( 3 ) = 0
5385 (C) c l o s e ( 3 ) = 0
5384 (B) c l o s e ( 3 ) = 0
5385 (C) c l o s e ( 3 ) = 0
5384 (B) c l o s e ( 0 ) = 0
5384 (B) c l o s e ( 1 < u n f i n i s h e d . . . >
5385 (C) c l o s e ( 3 < u n f i n i s h e d . . . >
5384 (B) < . . . c l o s e resumed> ) = 0
5385 (C) < . . . c l o s e resumed> ) = 0
5384 (B) c l o s e ( 2 ) = 0
5385 (C) c l o s e ( 3 ) = 0
5385 (C) c l o s e ( 0 ) = 0
5385 (C) c l o s e ( 1 ) Unix et Programmation Shell
Philippe Langevin (IMATH, USTV)
= 0
Automne  338 / 391
pipeline tracer un pipeline

A : pipe(3,4)

A : clone,close(4), clone
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  339 / 391
pipeline tracer un pipeline

A : clone, close(4), clone

B : close(3), dup2(4,1), A : close(3)


Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  340 / 391
pipeline tracer un pipeline

B : close(3), dup2(4,1), A : close(3)

C : dup2(3,0), B : open(/tmp/src) = 3, B : dup2(3,0)


Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  341 / 391
pipeline tracer un pipeline

C : dup2(3,0), B : open(/tmp/src)=3, B :
dup2(3,0)

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  342 / 391
pipeline tracer un pipeline

B : close(3), C : open(/tmp/dst)=3, B :
execve(cat)

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  343 / 391
pipeline tracer un pipeline

C : dup2(3,1), close(3), execve( wc )

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  344 / 391
outils

11 - outils

regex
grep
find
sed
awk
vi

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  345 / 391
outils

outils

La liste des commandes utiles s’allonge d’années en années. Mais la


croissance n’est pas exponentielle, et il est encore possible de se
mettre à jour ! Dans vos TPs, vous travaillerez les incontournables :
make, gcc, gdb, gprof etc. . .
gnuplot, dot, tex, latex. . .
flex, bison
utiliserez régulièrement les
ps, sort, wc
cut, tr
ssh, scp, sftp

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  346 / 391
outils

quelques démos

Il s’agit de faire quelques démonstrations concernant la bibliothèque


regex et les commandes grep , sed , find , awk et vi

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  347 / 391
outils

quelques démos

Il s’agit de faire quelques démonstrations concernant la bibliothèque


regex et les commandes grep , sed , find , awk et vi

A très peu de choses prés, tout est prévu dans ces commandes pour
les manipulation des fichiers textes. Il s’agit plus de savoir comment
retrouver rapidement une option utile avec son mode d’emploi !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  347 / 391
outils

quelques démos

Il s’agit de faire quelques démonstrations concernant la bibliothèque


regex et les commandes grep , sed , find , awk et vi

A très peu de choses prés, tout est prévu dans ces commandes pour
les manipulation des fichiers textes. Il s’agit plus de savoir comment
retrouver rapidement une option utile avec son mode d’emploi !

La plupart du temps, les expressions régulières jouent un rôle clef


dans le traitement des fichiers.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  347 / 391
outils regex

rexexp
REGEX ( 7 ) L i n u x Programmer ’ s Manual
NAME
r e g e x − POSIX . 2 r e g u l a r e x p r e s s i o n s
DESCRIPTION
R e g u l a r e x p r e s s i o n s ( ”RE” s ) , a s d e f i n e d i n POSIX2 ,
come i n 2 f o r m s : modern REs ( r o u g h l y t h o s e o f e g r e p ;
POSIX . 2 c a l l s t h e s e ” e x t e n d e d ” REs ) and o b s o l e t e
REs ( r o u g h l y t h o s e o f ed ( 1 ) ; POSIX . 2 ” b a s i c ” REs ) .

O b s o l e t e REs m o s t l y e x i s t f o r backward c o m p a t i b l e .
i n some o l d p r o g r a m s ; t h e y w i l l be d i s c u s s e d a t
t h e end . POSIX . 2 l e a v e s some a s p e c t s o f RE s y n t a x
and s e m a n t i c s open ; ” ( ! ) ” marks d e c i s i o n s on t h e s e
a s p e c t s t h a t may n o t be f u l l y p o r t a b l e t o o t h e r
POSIX . 2 i m p l e m e n t a t i o n s .
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  348 / 391
outils regex

rexexp

1 regcomp (&r, argv[1], REG EXTENDED) != 0);


2 src = fopen (argv[2], ”r”);
3 while ( ! feof (src ) ) {
4 fgets (line , 1024, src );
5 s = 0;
6 while (0 == regexec (&r, &(line[s]), 1, &pos, 0))
7 {
8 // traitement
9 }
10 }
11 regfree (&r);

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  349 / 391
outils grep

grep

origine
mars 1973, par Ken Thompson.

La version GNU de grep utilise l’algorithme de recherche de motif de


Boyer-Moore (1977).

oxford dictionary
wiki grep
gnu grep
voir aussi : ngrep

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  350 / 391
outils grep

grep

NAME
grep − p r i n t l i n e s matching a p a t t e r n

SYNOPSIS
g r e p [ OPTIONS ] PATTERN [ FILE . . . ]
g r e p [ OPTIONS ] [− e PATTERN | −f FILE ] [ FILE . . . ]

DESCRIPTION
g r e p s e a r c h e s t h e named i n p u t F I L E s f o r l i n e s
c o n t a i n i n g a match t o t h e g i v e n PATTERN . By
d e f a u l t , grep p r i n t s the matching l i n e s .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  351 / 391
outils grep

grep -e vs -E

grep −r i o −−i n c l u d e =”∗. t e x ”


−e ’ \ ( emacs \ | vim \) ’ ˜/ doc

grep −r i o −−i n c l u d e =”∗. t e x ”


−E ’ ( emacs | vim ) ’ ˜/ doc

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  352 / 391
outils grep

grep -e vs -E

grep −r i o −−i n c l u d e =”∗. t e x ”


−e ’ \ ( emacs \ | vim \) ’ ˜/ doc

grep −r i o −−i n c l u d e =”∗. t e x ”


−E ’ ( emacs | vim ) ’ ˜/ doc
recherche les fichiers TEX, dans l’arborescence doc, qui
mentionnent un des éditeurs vi ou emacs

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  352 / 391
outils grep

grep -e vs -E

grep −r i o −−i n c l u d e =”∗. t e x ”


−e ’ \ ( emacs \ | vim \) ’ ˜/ doc

grep −r i o −−i n c l u d e =”∗. t e x ”


−E ’ ( emacs | vim ) ’ ˜/ doc
recherche les fichiers TEX, dans l’arborescence doc, qui
mentionnent un des éditeurs vi ou emacs
/home/ p l /UPS/ doc / t o o l s . t e x : emacs
/home/ p l /UPS/ doc / t o o l s . t e x : vim
/home/ p l /UPS/ doc / p r o l o g u e . t e x : emacs
/home/ p l /UPS/ doc / p r o l o g u e . t e x : emacs

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  352 / 391
outils grep

grep -iownE ’[-a-z]+regexp’ doc/*.tex


Matcher S e l e c t i o n
−E , −−e x t e n d e d −r e g e x p
Matching C o n t r o l
−e PATTERN, −−r e g e x p=PATTERN
−i , −−i g n o r e −c a s e
−v , −−i n v e r t −match
−w , −−word−r e g e x p
−x , −−l i n e −r e g e x p
G e n e r a l Output C o n t r o l
−c , −−c o u n t p r i n t a c o u n t o f m a t c h i n g
−L , −− f i l e s −w i t h o u t −match
−l , −− f i l e s −w i t h −matches
−m NUM, −−max−c o u n t=NUM
−o , −−o n l y −m a t c h i n g
−q , −−q u i e t , −− s i l e n t
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  353 / 391
outils grep

grep -Rli –include=*rc path /etc 2>/dev/null


Output L i n e P r e f i x C o n t r o l
−b , −−b y t e −o f f s e t
−H, −−with −f i l e n a m e
−h , −−no−f i l e n a m e
−n , −−l i n e −number
Context Line Control
−A NUM, −−a f t e r −c o n t e x t=NUM
−B NUM, −−b e f o r e −c o n t e x t=NUM
−C NUM, −NUM, −−c o n t e x t=NUM
F i l e and D i r e c t o r y S e l e c t i o n
−−e x c l u d e=GLOB
−−e x c l u d e −from=FILE
−−e x c l u d e −d i r=DIR
−−i n c l u d e=GLOB
−R , −r , −− r e c u r s i v e
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  354 / 391
outils grep

exemple

g r e p −iownE ’[ − a−z ]+ r e g e x p ’ doc / ∗ . t e x


doc / t o o l s . t e x :126: − − e x t e n d e d −r e g e x p
doc / t o o l s . t e x :128: − − r e g e x p
doc / t o o l s . t e x :131: − − word−r e g e x p
doc / t o o l s . t e x :132: − − l i n e −r e g e x p
doc / t o o l s . t e x :319: − − r e g e x p

g r e p −i wl E R ’[ − a−z ]+ r e g e x p ’ −−i n c l u d e =∗. t e x ˜


/home/ p l /web−d o c s / c o u r s /UPS/ doc / t o o l s . t e x

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  355 / 391
outils grep

retour de grep
0 au moins une occurrence
1 aucune occurrence
2 erreur d’accès, erreur de syntaxe
1 for file in ∗
2 do
3 if grep −qE ’[0−9]+’ $file
4 then
5 echo liste de $file :
6 grep −oE ’[0−9]+’ | sort | uniq −c
7 else
8 echo $file pas de nombre
9 fi
10 done

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  356 / 391
outils find

find

origine
Dick Haight ( ?)

find est une commande puissante pour trouver les fichiers en


fonction de critères variés.

sur -print
wiki find
gnu findutils
voir aussi : locate, xargs

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  357 / 391
outils find

find

La même chose que précédemment, avec find, sans le support


récursif de grep
f i n d ˜/ doc / t o o l s . t e x −name ” ∗ . t e x ”
−e x e c g r e p −Hio −E ’ ( emacs | vim ) ’ { } \ ;
ou encore
f i n d ˜/ doc / t o o l s . t e x −name ” ∗ . t e x ” |
x a r g s g r e p −Hio −E ’ ( emacs | vim ) ’

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  358 / 391
outils find

man find | wc -l ... 1615 !

NAME
find − search for f i l e s in a directory hierarchy
SYNOPSIS
f i n d [−H][ − L ][ −P][ −Dx][ −Ox ] [ p a t h . . . ] [ e x p r e s s i o n ]

DESCRIPTION
GNU f i n d s e a r c h e s t h e d i r e c t o r y t r e e r o o t e d a t
e a c h g i v e n f i l e name by e v a l u a t i n g t h e g i v e n
e x p r e s s i o n from l e f t t o r i g h t , a c c o r d i n g t o t h e
r u l e s o f p r e c e d e n c e ( s e e s e c t i o n OPERATORS) ,
until t h e outcome i s known . . .

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  359 / 391
outils find

option
−maxdepth −mindept h −mount −r e g e x t y p e

$ f i n d / −maxdepth 2 −name ” $$ ” 2>/dev /


null
/ p r o c /2105
$ f i n d / −mount −maxdepth 2 −name ” $$ ” 2>/dev /
null
$ f i n d / −maxdepth 2 −r e g e x ” . ∗ / [ 0 − 2 ] { 1 } ” 2>/dev
/null
$ f i n d / −r e g e x t y p e p o s i x −e x t e n d e d −maxdepth 2 \
−r e g e x ” . ∗ / [ 0 − 2 ] { 1 } ” 2>/dev / n u l l
/ p r o c /1
/ p r o c /2
$ f i n d ˜ −m in d e pth 6 −name ’ \ . ∗ ’ −p r u n e \
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  360 / 391
outils find

test
-name, -iname nom de base
-wholename nom complet
-regex, -iregex nom de base
-type type f, d, p, c, l, b
-user propriété
-group groupe
-perm permission
-links nombre de liens
-size taille char, word, bloc, k, M, G
-atime,-amin date d’accès
-mtime,-mmin modification
-ctime,-cmin création
-newer comparaison des dates

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  361 / 391
outils find

inoeud faible

$ f i n d / −inum −3 − p r i n t f ”% i %u %p\n”
2 root /
1 p l /home/ p l / . g v f s
1 root / sys
2 root / sys / fs
1 root / proc
1 root / proc / sys / f s / binfmt misc
2 root / proc / sys / f s / binfmt misc / s t a t u s
2 r o o t / boot
1 r o o t / dev / p t s
2 r o o t / dev / p t s / ptmx

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  362 / 391
outils find

A propos de find et de -print

. . . You know, like why is the -i option for grep mean ignore case,
and the -f option for sort mean ignore case, and so on. . . Well, the
instructor of the course decided to chime in and said something like
this :

“Here’s another good example of this problem with UNIX. Take the
find command for example. WHAT idiot would program a command
so that you have to say -print to print the output to the screen.
What IDIOT would make a command like this and not have the
output go to the screen by default”

And the instructor went on and on, and vented his spleen...

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  363 / 391
outils find

A propos de find et de -print

The next morning, one of the ladies in the class raised here hand, the
instructor called on her, and she proceeded to say something like this :

“The reason my father programmed the find command that way, was
because he was told to do so in his specifications.”

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  364 / 391
outils find

A propos de find et de -print

The next morning, one of the ladies in the class raised here hand, the
instructor called on her, and she proceeded to say something like this :

“The reason my father programmed the find command that way, was
because he was told to do so in his specifications.”

D’après ce courrier, Dick Haight est à l’origine de find.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  364 / 391
outils find

action
f i n d ˜ − s i z e +1M −c t i m e −10 −perm 0664
−name ” ∗ . JPG” −u s e r p l −ok delete
\;
< d e l e t e . . . /home/ p l / p i c s /IMGP0968 . JPG > ? n
< d e l e t e . . . /home/ p l / p i c s /IMGP0514 . JPG > ? n
< d e l e t e . . . /home/ p l / p i c s /IMGP0965 . JPG > ? n
−d e l e t e
−e x e c command ;
− e x e c d i r command ;
−l s
−ok command ;
−o k d i r command ;
−p r i n t
−p r i n t 0
− printf
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  365 / 391
outils sed

Editeur de flux : sed


NAME
s e d − s t r e a m e d i t o r f o r f i l t e r −t r a n s f o r m i n g t e x t
SYNOPSIS
s e d [ OPTION ] . . . { s c r i p t } [ i n p u t − f i l e ] . . .
DESCRIPTION
sed i s a stream e d i t o r . A stream e d i t o r i s
u s e d t o p e r f o r m b a s i c t e x t t r a n s f o r m a t i o n s on an
input stream
OPTION
−n , −−q u i e t , −− s i l e n t
−e s c r i p t , −−e x p r e s s i o n=s c r i p t
−r , −−r e g e x p −e x t e n d e d
−f s c r i p t − f i l e , −− f i l e =s c r i p t − f i l e
− i [ SUFFIX ] , −−i n −p l a c e [=SUFFIX ]
− l N, −−l i n e −l e n g t h=N
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  366 / 391
outils sed

sed

origine
1973-74, par Lee McMahon, Bell labs.

wiki sed
gnu sed

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  367 / 391
outils sed

principe
sed charge les lignes d’un fichier correspondant à une adresse dans
un espace de travail pour lui appliquer des commandes d’édition.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  368 / 391
outils sed

adresse : motif, ligne

1 #!/bin/bash −v
2 sed ’ /nologin /d’ /etc/passwd
3 root: x:0:0: root:/ root:/ bin/bash
4 sync: x:5:0: sync:/ sbin :/ bin/sync
5 shutdown:x:6:0: shutdown:/sbin:/sbin /shutdown
6 halt : x:7:0: halt :/ sbin :/ sbin /halt
7 pl : x:501:501::/ home/pl:/bin/bash
8 guest: x:502:502::/ home/guest:/bin/bash

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  369 / 391
outils sed

adresse : intervalle
1 #!/bin/bash −v
2 sed −rn ’/dae.∗n/,7{=;p}’ /etc/passwd
3 3
4 daemon:x:2:2:daemon:/sbin:/sbin/nologin
5 4
6 adm:x:3:4: adm:/var/adm:/sbin/nologin
7 5
8 lp : x:4:7: lp :/ var /spool/lpd:/ sbin /nologin
9 6
10 sync: x:5:0: sync:/ sbin :/ bin/sync
11 7
12 shutdown:x:6:0: shutdown:/sbin:/sbin /shutdown
13 24
14 avahi: x:70:70: Avahi mDNS/DNS−SD Stack:/var/run/avahi−
daemon:/sbin/nologin
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  370 / 391
outils sed

commande
q quitter
d,D effacer l’espace des motifs
s substitution
y remplacement
p, P affiche l’espace des motifs
n, N chargement d’une ligne
h, H mémoriser
g,G charger la mémoire
x échange les contenus mémoires
{} groupement des commandes
= numéro de ligne
: étiquette
b saut

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  371 / 391
outils sed

1 #!/bin/bash −v
2 echo {1..6} | sed ’ y/ /\n/’ > /tmp/foo
3 sed ’ N;s/\n/−/’ /tmp/foo
4 1−2
5 3−4
6 5−6
7 sed −n ’h;n;G;s/\n/−/p’ /tmp/foo
8 2−1
9 4−3
10 6−5
11 sed −r ’/[3]/{ h; n; G;s/(ˆ|\n)/−/g}’ /tmp/foo
12 1
13 2
14 3
15 −4−3
16 5
17 6
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  372 / 391
outils sed

exemples
1 #!/bin/bash −v
2
3 sed −rne ’/root/s/[ ]∗(:|ˆ) [ ]∗./\ U&/gp’ /etc/passwd
4 Root:X:0:0: Root:/root:/bin/bash
5 Operator:X:11:0: Operator:/root:/ sbin /nologin
6 echo abcdefgh | sed ’ s/../\ u&−/g’
7 Ab−Cd−Ef−Gh−
8
9 echo abcde | sed ’ s/./&\n/g;’ > /tmp/abcd
10 sed = /tmp/abcd | sed −n ’1˜2N;s/\s/−/p’
11 1−a
12 2−b
13 3−c
14 4−d
15 5−e
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  373 / 391
outils sed

exemples
1 #!/bin/bash −v
2 echo −e ’1\n2\n3\n4\n5\n6\n7’ > /tmp/nbr
3 sed −ne ’N;N;s/\n/:/gp’ /tmp/nbr
4 [Link]
5 [Link]
6 sed −e ’x; n; ’ /tmp/nbr | tr ’ \n’ ’ /’ ; echo
7 /2/1/4/3/6/5/
8 sed −e ’3,5d’ /tmp/nbr | tr ’ \n’ ’ /’ ; echo
9 1/2/6/7/
10 sed −ne ’3,5p’ /tmp/nbr | tr ’ \n’ ’ /’ ; echo
11 3/4/5/
12 sed −ne ’3,5!p’ /tmp/nbr | tr ’ \n’ ’ /’ ; echo
13 1/2/6/7/

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  374 / 391
outils sed

s/regexp/replacement/flags
1 #!/bin/bash −v
2
3 sed −ne ’/sh$/s/:.∗:/ −−> /p’ /etc/passwd
4 root −−> /bin/bash
5 pat −−> /bin/bash
6 pl −−> /bin/bash
7 juju −−> /bin/bash
8 sed −ne ’/sh$/s/\([ˆ:]∗\) :.∗:\([ˆ:]∗\) /\2 <−− \1/p’ /etc/
passwd
9 /bin/bash <−− root
10 /bin/bash <−− pat
11 /bin/bash <−− pl
12 /bin/bash <−− juju

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  375 / 391
outils awk

awk

Un mini langage pour manipuler les colonnes d’un fichier. awk a été
créé aux Bell Labs dans les années 70s par :
Alfred Aho
Peter Weinberger
Brian Kernighan.
c a t / e t c / passwd | awk −F : ’ { p r i n t $1 } ’
C’est un des langages qui a inspiré perl.
wiki awk
gawk
voir aussi : locate, xargs

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  376 / 391
outils awk

awk
awk ’ / ˆ p . ∗ l / { p r i n t $1 } ’ / e t c / passwd
pulse : x :998:996: PulseAudio
p l : x : 1 0 0 0 : 1 0 0 0 : p l : / home/ p l : / b i n / bash
awk −F : ’ / ˆ p . ∗ l / { p r i n t $2+$3+$4 } ’ / e t c / passwd
1994
2000
awk −−p o s i x −F ’ : ’ ’ $4 ˜ /5[0 −9]{2}/ { p r i n t
$1 , $4 } ’ / e t c / passwd
p l 500
p a t 501
P e r l c o m b i n e s ( i n t h e a u t h o r ’ s o p i n i o n , anyway )
some o f t h e b e s t f e a t u r e s o f C , sed , awk , and sh ,
so people f a m i l i a r with those languages should
ha ve l i t t l e d i f f i c u l t y w i t h i t . L a r r y Wa ll
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  377 / 391
outils awk

Un exemple tiré de linux magazine


#!/ b i n / b a s h
# Grab a l i s t o f u s e r s from t h e / e t c / passwd f i l e
c a t / e t c / passwd | g r e p sh | g r e p home | awk −F : ’ {
p r i n t $1 } ’

pipeline overdose
En général, un abus de pipelines traduit des maladresses !

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  378 / 391
outils awk

Un exemple tiré de linux magazine


#!/ b i n / b a s h
# Grab a l i s t o f u s e r s from t h e / e t c / passwd f i l e
c a t / e t c / passwd | g r e p sh | g r e p home | awk −F : ’ {
p r i n t $1 } ’

pipeline overdose
En général, un abus de pipelines traduit des maladresses !

g r e p −E ’ ( sh | home ) ’ | awk −F : ’ { p r i n t $1 } ’

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  378 / 391
outils awk

Un exemple tiré de linux magazine


#!/ b i n / b a s h
# Grab a l i s t o f u s e r s from t h e / e t c / passwd f i l e
c a t / e t c / passwd | g r e p sh | g r e p home | awk −F : ’ {
p r i n t $1 } ’

pipeline overdose
En général, un abus de pipelines traduit des maladresses !

g r e p −E ’ ( sh | home ) ’ | awk −F : ’ { p r i n t $1 } ’

awk −F : ’ / home/ && / sh / { p r i n t $1 } ’ / e t c / passwd

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  378 / 391
outils awk

Un exemple tiré de linux magazine


#!/ b i n / b a s h
# Grab a l i s t o f u s e r s from t h e / e t c / passwd f i l e
c a t / e t c / passwd | g r e p sh | g r e p home | awk −F : ’ {
p r i n t $1 } ’

pipeline overdose
En général, un abus de pipelines traduit des maladresses !

g r e p −E ’ ( sh | home ) ’ | awk −F : ’ { p r i n t $1 } ’

awk −F : ’ / home/ && / sh / { p r i n t $1 } ’ / e t c / passwd

awk −F : ’ $6 ˜ /home/ && $7 ˜ / sh / { p r i n t $1 } ’ /


e t c / passwd
Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  378 / 391
outils awk

awkword
1 lynx −−dump $1 | awk ’
2 BEGIN { FS=”[ˆa−zA−Z]+” }
3
4 {
5 for (i =1; i <=NF; i++) {
6 word = tolower($i)
7 words[word]++
8 }
9 }
10
11 END {
12 for (w in words)
13 printf (”%3d %s\n”, words[w], w)
14 }
15 ’ | grep −E ’[a−z]{3}’
Philippe Langevin (IMATH, USTV)
| sort −rn | head −12
Unix et Programmation Shell Automne  379 / 391
outils vi

vi

L’éditeur visuel vi (William Joy, BSD ) est un bon laboratoire pour


pratiquer les expressions régulières utiles pour l’éditeur non visuel sed.
vi test . txt
Vous comprendrez que vi démarre en mode commande et qu’il
fonctionne principalement en trois modes :
insertion
commande
visuel
ctrl-c bascule en mode commande. ctrl-v bascule en mode visuel

vimbook

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  380 / 391
outils vi

commande

commande action exemple


:help aide :help yank
:w sauvegarde :w [Link]
:q quitte
:q ! quitte sans sauver
:wq modifie et quitte
:sh lancer un shell :sh ... exit
:make lancer make
:ab abréviation :ab anti
anticonstitutionnellement
:split nouveau cadre :split common.c

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  381 / 391
outils vi

bouger

commande commentaire portée


w suivant mot
b précédent mot
ˆ début ligne
0 début ligne
$ fin ligne
:0 début fichier
:5 ligne fichier
:$ fin fichier
ctrl-W changer de cadre

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  382 / 391
outils vi

rechercher

commande commentaire
:/motif rechercher le motif
n suivant
N précédent

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  383 / 391
outils vi

insérer

commande action commentaire


i insérer avant le curseur
a aprés le curseur
A fin de ligne
I début de ligne
o ligne suivante
O ligne précédente
:r file un fichier :r [Link]
:r !commande une sortie :r ! wc [Link]

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  384 / 391
outils vi

diverse
commande action commentaire
u annuler undo
U annuler undo line
. répéter
m marquer bloc a, b
ctrl-V marquer visuel
J concaténer des lignes
∼ casser lettre
g∼w casser mot
gU$ majusculer curseur-EOL
guw minusculer mot
ctrl-A incrémenter nombre
ctrl-X décrémenter nombre

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  385 / 391
outils vi

couper

commande portée
x caractère
5x 5 caractères
dw mot
5dw 5 mots
dd ligne
5dd 5 lignes
D curseur-EOL
d´a marque a
:5,7d lignes 5,6,7

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  386 / 391
outils vi

copier

commande commentaire
yw copier un mot
y3w 3 mots
yy une ligne
y7 7 lignes
y’z la marque z
:10,20y les lignes 10-20.
:’<,’>y le bloc visuel.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  387 / 391
outils vi

coller

commande action commentaire


p coller sous le curseur
P coller au dessus
:10,20t 100 copier lignes 10-20 vers 100
:10,20m 100 deplacer lignes 10-20
:100,$m 50 deplacer 100-EOF vers 50.

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  388 / 391
outils vi

remplacer

commande action portée


r remplacer caractère
cw changer mot
cc changer ligne
C changer curseur-EOL

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  389 / 391
outils vi

substituer

commande action portée


:%s/motif/nouveau/g substituer fichier
:%s/motif/nouveau une fois par ligne
:%s/motif/nouveau/gc cofirmation fichier
:10,20s/motif/nouveau/g 10 a 20.
:s/.*/U&/ masjusculer ligne courante.
:s/motif/nouveau&/g fichier
:/motif/-2,+4d efface contexte
:s/[ABC]/[abc]/g A devient a B devient

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  390 / 391
outils vi

action contextuelle

commande action
:g/chaine/commande
:g/target/s/0/ZERO/g remplace 0 par ZERO dans les targets
:g/ˆ[ ]*$/d supprime toutes les lignes vides
:g/target/t7 les lignes cibles en 7
:g/target/cd 80 centre les lignes ciblées
:g !/target/d efface les lignes
:v/target/d idem
:g/re/p as grep !
oxford dictionary

Philippe Langevin (IMATH, USTV) Unix et Programmation Shell Automne  391 / 391

Vous aimerez peut-être aussi