GNU et commandes Unix (LPIC101)

Un livre de Wikibooks.

Wikiversity-logo.svg
Contenu transféré sur Wikiversité

Le contenu que vous recherchez a été déplacé vers la Wikiversité. Il devrait être disponible sous le nom Certification Linux LPI/Administrateur système débutant/Examen 101/GNU et commandes Unix.

Split-arrows.svg
Livre à fractionner

Il a été suggéré de fractionner ce livre en plusieurs sous-pages afin d'améliorer sa lisibilité.

Logo LPI

Sections

[modifier] Table des matières de la section

[modifier] Unix et Linux

[modifier] Objectifs

Unix est l'OS original d'Internet. NFS, TCP/IP, RPC, ... ont été développés sur et pour Unix. Unix est en fait une spécification de ce que doit être ce genre d'OS. Il en existe plusieurs implémentations. Citons pour l'emple AIX d'IBM, HP-UX d'HP, Solaris de Sun, ou les *BSD. Linux est une implémentation Unix entièrement réécrit par Linus Torvalds et son équipe de développeurs volontaires répartis sur l'ensemble de la planète et mis en contact grâce à Internet. Unix comme Linux sont : Portable, multi-utilisateurs, multi-tâches, rendu indépendants des périphériques d'entrées et de sorties, capables de gérer les ressources matérielles, d'une grande performance, sécurisés, équipé d'une ligne de commande puissante et d'une interface graphique.

Linux est compatible avec la norme POSIX et supporte d'autres API standard comme BSD ou SVR4 Linux possède toutes les fonctionalités que l'on peut attendre d'un Unix moderne, dont le multi-tâche, multi-utilisateurs, mémoire virtuelle, librairies partagées, chargement à la demande, shared copy-on-write executables, gestion propre de la mémoire et utilisation de TCP/IP pour le réseau.

De plus en plus d'entreprises sélectionnent Linux pour ses performances, son cout faible et l'absence de royalties.

[modifier] Unix et Linux

Unix est l'OS d'origine d'Internet. Il a été développé en 1970 aux laboratoires A&T Bell Labs. Il a ensuite été distribué gratuitement notament aux gouvernements et aux universités. Divers organismes en supporte différentes distributions :

  • System V
  • BSD
  • SCO

La plupart des Unix sont soumis à des licences de copyright.

Linux a été diffusé pour la première fois par Linux Torvalds en 1991. Son modèle de développement est libréré du droit d'auteur. Il adopte la licence GPL créée par Richard Stallman quelques années auparavant. Richard Stallman est également à l'origine du projet GNU, sans lequel Linux ne servirait pas à grand chose. Certaines personnes préfèrent ainsi parler de système GNU/Linux. Linux implémente la plupart des commandes system V, BSD et Unix.

[modifier] Se logger et se délogger

Entrer dans une session est le premier pas pour accéder à un système Linux. Vous avez besoin d'un identifiant (ID) et d'un mot de passe pour pouvoir commencer à utiliser le système. L'identifiant "root" est l'identifiant du super-utilisateur qui a tous les privillèges et n'est normalement assigné qu'à l'administrateur du système. Lorsque l'on a réussi à entrer dans le système, quelques variables d'environement vont être initialisées et le shell assigné au compte correspondant à l'identifiant sera lancé.

Exemples de variables initialisées au loggin: $HOME, $SHELL, $PATH, et d'autres. En modifiant le fichier /etc/login.defs, l'administrateur peut régler quelques paramètres du logging et les variables pour tous les utilisateurs. Comme par exemple:

UID_MIN 500
UID_MAX 60000
UMASK 022
ENV_PATH /usr/local/bin:/usr/bin:/bin

Pour sortir, utilisez les commandes exit ou logout.

[modifier] Mot de passe

Personne ne peut voir votre mot de passe, même l'administrateur. Pour changer votre mot de passe d'utilisateur ou de groupe, utilisez passwd.

passwd [options]

Options courantes: -l, -u : bloque et débloque un compte. -g [| r]: Utilisé pour les groupes. -g défini un mot de passe pour le groupe, et -r le remplace. -x|n : Nombre de jours maximum et minimum pendant lequel un mot de passe reste valide.

En règle générale, un mot de passe doit:

  • avoir une longueur minimale.
  • ne contenir aucun mot du langage courant.
  • Contenir des caratères alphanumériques
  • Contenir un mélange de lettres majuscules et minuscules.

[modifier] Information sur les utilisateurs

Une ligne est définie dans le fichier /etc/passwd pour chaque compte utilisateur. Le mot de passe crypté est stocké dans le fichier /etc/shadow. Le format de /etc/passwd est:

Root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/bin/bash
daemon:x:2:2:Daemon:/sbin:/bin/bash
yann:x:500:100:Yann Forget:/home/yann:/bin/bash

Le champs x est l'ancienne localisation pour le mot de passe.

Le format de /etc/shadow est:

root:IMXweyiV816gg:11996:0:10000::::
bin:!*:8902:0:10000::::
daemon:*:8902:0:10000::::
yann:GoIM8j1S.IuTY:11996:0:99999:7:::

L'* pour le mot de passe crypté veux dire qu'aucun mot de passe n'a encore été défini. Le ! devant le mot de passe crypté veux dire que le compte est bloqué.

[modifier] Information sur les groupes

Il y a une ligne dans le fichier /etc/group pour chaque groupe d'utilisateurs. Le mot de passe crypté est stocké dans /etc/gshadow. Le format de /etc/group est:

root:x:0:root
bin:x:1:root,bin,daemon
daemon:x:2:
video:x:33:yann

Le format de /etc/gshadow est:

root:*:root:root
bin:*:root:root
daemon:*:root:root
video:*:root:root,yann

Les mots de passe pour les groupes ne sont pas souvent implémentés car il faut passer un membre du groupe pour en changer ...

[modifier] Commandes variées

Pour obtenir des informations sur une session, jouez la commande id.

id [options] [username]

Options courantes: -g : N'imprime que l'identifiant du groupe. -u : N'imprime que l'identifiant de l'utilisateur.

Exemple:

$ id
uid=0(root) gid=0(root) groupes=0(root), 1(bin), 14(uucp), 15(shadow),16(dialout)

Pour lancer un shell avec un nouvel utilisateur et/ou groupe, jouez la commande su.

su [options] [username]

Options courantes: -s : Selectionne un autre shell.

Exemple:

$ su toto
passwd:

[modifier] Shell

Un shell est un interpréteur de lignes de commandes qui :

  • attends les commandes (en affichant ce qu'on appelle l'invite)
  • Les interprète (ceci inclus les redirections d'entrée-sortie, les tuyaux, la génération de nom de fichiers, etc...)
  • les exécute
  • exécute des langages de script

IL y a plusieurs shells populaires :

  • sh: Bourn shell, le shell de scripts standart.
  • csh: Berkley shell, permet le contrôle de tâches, l'historique des commandes, les alias ...
  • ksh: Korn shell, Les syntaxes du Bourn avec les fonctionalités du Berkley.
  • Bash: Bourne Again shell, libre, shell clone du Korn. Shell traditionel de Linux.
  • Tcsh: Libre, clone du Berkley avec beaucoups d'extensions.

La plupart des shell vous permettent de personaliser son invite et son environement.

Pour le bash, la variable du prompt est PS1

Pour le bash, les fichiers utilisés pour la personnalisation de l'environnement sont:

.bashrc exécuté à chaque nouvelle session bash.

.bash_profile exécuté à la connextion au shell.

.bash_logout exécuté à la sortie du shell.

[modifier] Exercices

[modifier] Travailler en ligne de commande

[modifier] Objectifs

Description: Les candidats devront pouvoir intéragir avec les shells et les commandes en utilisant la ligne de commandes. Cet objectif inclus l'introduction de commandes et de séquences de commandes valides, la définition, la référence et l'exportation de variables d'environement, l'utilisation de l'historique et des facilités d'édition, l'invoquation de programmes dans et en dehors du chemin, l'utilisation des commandes de substitution, l'application récursive des commandes dans l'arbre des répertoires, et l'utilisation de la commande man pour trouver des informations sur les commandes.

fichiers clés, termes et utilitaires :

. / source
bash
echo
env
exec
export
man
pwd
set
unset
~/.bash_history
~/.profile

[modifier] Ligne de commande

Les lignes de commandes sont de la forme :

commande  [options]  [arguments]

Exemples:

pwd
ls -ld ou ls -l -d ou ls -d -l
rm -r /tmp/toto
cat  ../readme helpme > save
more /etc/passwd /etc/hosts /etc/group
find . -name *.[ch] -print
date "+day is %a"

On peut mettre des lignes de commandes dans un fichier, de manière à obtenir un script.

Pour afficher une chaine de caractères sur la sortie standard, utiliser la commande echo.

echo [-n][string|command|$variable]
echo my home directory is: $HOME
echo I use the $SHELL shell

[modifier] Shells et Bash

L'ordre de précédence des différentes sources lorsque vous entrez une commande dans le shell sont :

  • Les alias.
  • Les mots clés comme if, for et more.
  • Les Fonctions.
  • Les "Built-ins" comme cd, type, et kill.
  • Les scripts et les programmes exécutables présents dans les chemins listés dans la variable d'environement PATH.

Pour connaitre la source exacte d'une commande, utiliser :

$ type kill
kill is a shell builtin

Ce qui est différent de :

/bin/kill

Pour lister l'ensemble des commandes "built-in", utilisez l'aide.

/bin/bash peut-être invoqué à l'ouverture d'une session ou explicitement par un utilisateur. A l'ouverture, les fichiers scripts suivants sont utilisés :

  • /etc/profile fichier du système par défaut.
  • $HOME/.profile s'il existe.
  • $HOME/.bash_profile s'il existe
  • /etc/bash.bashrc s'il existe
  • $HOME/.bashrc s'il existe

Lorsqu'un utilisateur invoque explicitement le shell bash, les fichiers suivants sont exécutés : /etc/bash.bashrc s'il existe. $HOME/.bashrc s'il existe;

L'historique de tout ce qui est tapé se trouve dans le fichier .bash_history.

Un script est une liste de commandes et d'opérations exécutées dans le contexte du shell. Vous pouvez vous servir de scripts bash pour mettre en place votre environement, vos variables, et plus.

[modifier] Découvrir /bin/bash

Chaque fois que vous exécutez un nouveau programme, une nouvelle tâche est créée. Quand le programme se termine, la tâche se termine aussi et vous retrouvez le prompt en retour. Vous pouvez faire tourner le programme en arrière plan en ajoutant le caractère "&" apres la commande :

monscript &

Dans certaines situations, il est également possible d'utiliser le contexte de la tâche bash en utilisant la commande exec [program]

C'est utile quand vous ne voulez pas que le programme rende le prompt à sa terminaison. Le programme login, par exemple, est un bon exemple de réutilisation de la tâche Bash dans laquelle il est démarré.

exec login

[modifier] Variables du Shell

Toutes les variables locales de la session bash peuvent être vues par la commande set. La variable ne sera vue que par le shell où elle a été déclarée.

Pour déclarer une variable locale, utiliser simplement :

$ MAVARIABLE=SAVALEUR

Pour effacer une variable, utiliser :

$ unset MAVARIABLE

Toutes les variables d'environement peuvent-être vues par la commande env. Pour déclarer une variable qui sera vue par les autres shells, utilisez export.

$ export MAVARIABLE=SAVALEUR 

ou,

$ MAVARIABLE=SAVALEUR  
$ export MAVARIABLE

Quelques varaibles importantes :

HOME : répertoire utilisateur de celui qui s'est connecté.
PATH : chemin de recherche des commandes.

[modifier] Man pages

Les manuels en ligne décrivent la majorité des commandes disponibles sur votre système.

$ man mkdir
$ man cal

Si vous cherchez un mot clé dans toutes les man pages, utiliser l'option -k, ou la commande apropos.

$ man -k compress
$ apropos compress

La variable MANPATH contient les répertoires où les man pages sont stockées.

$ echo $MANPATH
/usr/local/man:/usr/share/man:/usr/X11R6/man:/opt/gnome/man

[modifier] Exercices

  1. Obtenez des informations sur les commandes useradd et userdel.
  2. Créer deux nouveaux comptes user1 et user2 et donner leur un mot de passe par la commande passwd. En tant que root, bloquez ces comptes et voyez si vous pouvez encore ouvrir une session pour ces comptes.
  3. Quelle est la commande qui concatène des fichiers?
  4. Declarez et Initializez les variables d'environement NAME et LASTNAME. Utiliser echo pour les imprimer.
  5. Lancez un nouveau bash et vérifiez que vous pouvez encore voir ces deux nouvelles variables.
  6. Utilisez exec pour démarer un nouveau bash. Voyez-vous toujours ces nouvelles variables ?
  7. Utilisez la commande date pour afficher le mois.
  8. Ajoutez un utilisateur notroot et attribuez lui les mêmes privilèges qu'à root. Bloquez le compte root.

[modifier] Exécution de flux de textes en utilisant des filtres

[modifier] Objectifs

Description: Les Candidats devraient etre en mesure d'appliquer des filtres sur les flux texte(text streams). Ces taches incluent l'envoi de fichiers texte et de flux externes(output streams) à travers les filtres utilitaire texte (text utility filters) pour modifier ceux-ci, et utiliser les commandes standards UNIX issues des packages textutil GNU.

Fichiers, termes et commandes principaux inclus :

cat
cut
expand
fmt
head
join
nl
od
paste
pr
sed
sort
split
tac
tail
tr
unexpand
uniq
wc

[modifier] Correspondance de chaîne et jokers

Le joker est un mécanisme de correspondance de chaîne pour la génération de noms de fichiers. L'objectif du joker est d'accroître la productivité : Localiser les fichiers dont vous ne vous souvenez pas. Localiser les fichiers qui ont quelque chose en commun. Travailler avec un groupe de fichiers plutôt qu'individuellement.

Le shell interprête ces caractères spéciaux :

! @ # $ % ^ & * ( ) { } [ ] | \ ; ~ ' " ` ?

Les caractères utilisés pour les jokers sont :

?  *  [  ]  ~

Si vous utilisez un caractère joker, le shell va essayer de générer un fichier. Essayez la commande suivante :

echo all files *

[modifier] Caractères joker speciaux

? correspond à n'importe quel caractère (une et une seule fois).
* n'importe quel caractère (zéro ou plusieurs fois)
[abcfghz] un caractère parmi le jeu indiqué 
[a-z] Un caractère dans une série
[!x-z] Pas dans cette série
~ Répertoire personnel
~utilisateur Répertoire personnel de "utilisateur"

Exemples:

? Seulement un caractère
[aA]??? Quatre caractères, en commençant par a ou A.
~toto chemin du répertoire personnel de toto
[!0-9]* Toute chaîne qui ne commence pas par un chiffre.

Que font ces commandes?

ls [a-z][A-Z]??.[uk]
ls big*
ls a???a
ls ??*

[modifier] Shell et jokers

Une commande shell peut être une commande simple ou complexe.

ls -l [fF]*
ls *.c | more
ls -l [a-s]* | mail `users`

La première activité du shell est d'interprêter les jokers. Seulement le shell interprête les jokers sans guillemets.

[modifier] Guillemets et commentaires

[modifier] Guillemets

Utiliser des guillemets pour que le shell n'interprête pas les caractères spéciaux et ne transforme plusieurs mots en commandes shell.

  • 'chaîne' Presque tout dans les guillements est litéral :
echo 'Il le fait, "Pourquoi ?"'
echo 'Parce que "#@&^:-)"'
echo '$VAR='Moi

"chaîne" Comme 'chaîne' mais interprête $, \, !

echo "Que s'est-il passé ?"
echo "Je ne sais pas mais lisez cette $REPONSE"

L'antislash \ traîte le caractère suivant comme litéral :

echo \$VAR=Moi
echo Que s\'est-il passé \?

Comment afficher l'antislash ?

echo \\

[modifier] Commentaires

Vous pouvez ajouter des commentaires sur une ligne de commande ou dans un script. Utiliser le caractère #. Un espace doit immédiatement précéder #.


Exemples:

echo $HOME # Print my Home directory
echo "### PASSED ###" # Only this part is a comment
Echo The key h#, not g was pressed.

Commandes

  • cat, tac: Concatene des fichiers et affiche le résultat sur la sortie standard.
  • head, tail: Renvoie sur la sortie standard la première (respectivement) la dernière partie des fichiers passés en argument.
  • nl: Renvoie le nombre de lignes des fichiers passés en argument.
  • wc: Print the number of bytes, words, and lines in files.
  • cut: Remove sections from each line of files.
  • tr: Translate or delete character.
  • expand, unexpand: Convertis espaces en tabulations et tabulations en espaces.
  • Paste: Merge lines of files.
  • join: Join lines of two files on a common field.
  • uniq: Remove duplicate lines from a sorted file.
  • split: Split a file into pieces.
  • fmt: Simple optimal text formatter.
  • pr: Convert text files for printing.
  • sort: Sort lines of text files.
  • od: Dump files in octal and other formats.

Concatenate files

To concatenate files, use cat.

cat [options] [files...]
tac [options] [files...]

The results are displayed to the standard output.

Common options: -s: never more than one single blank line. -n: number all output line.

Examples:

cat file  # Display file to the stdout.
cat chapter* # Display all chapters to stdout.
cat -n -s file # Display file with line number with single blank line.

To concatenate files in reverse order, use tac. View the begining and the end of a file

To view only few lines at the beginning or at the end of a file, use head or tail.

head [options] [files...]
tail [options] [files...]

The results are displayed to the standard output.

Common options: -n: number of lines to be displayed. (head and tail) -c: number of bytes to be diplayed (head and tail) -f: append output. (tail) -s #: iteration for new data every # sec. (tail)

Examples:

head file # Display the first 10 lines of file.
head -n 2 file # Display the first 2 lines of file.
tail -c 10 file # Display the last 10 bytes of file.
tail -f -s 1 /var/log/messages 

Display the last 10 lines of messages, block and check for new data every second.

Numbering file lines To add the line number to a file, use nl.

nl [options] [files...]

The results are displayed to the standard output.

Common options: -i #: incremente line number by #. -b: numbering style: a: number all lines, t: non empy line, n: number no line. -n: numbering format: rz:right justified, ln: left justified.

Examples:

nl file # Add the line number in each line in the file.
nl -b t -n rz file # Add the line number to each non-empty line with zero-completed format.

Counting items in a file

To print the number of lines, words and characters of a file, use wc.

wc [options] [files...]

The results are displayed to the standard output.

Common options: -c: the byte size. -m: the number of character. -w: the number of word. -l: the number of line. -L: length of the longest line.

Examples:

wc *.[ch] # Diplay the number of lines, words, and characters for all files .c or .h.
wc -L file # Display the size of the longest line.
wc -w file # Display the number of words.

Cutting fields in files

To remove sections from each line of files, use cut.

cut [options] [files...]

The results are displayed to the standard output.

Common options: -b #: Extract the byte at position #. -f #: Extract the field number #.

Examples:

cut -b 4 file # Extract and display the 4th byte of each line of file. 
cut -b 4,7 file # Extract and display the 4th and 7th byte of each line.
cut -b -2,4-6, 20- file
# Extract character 1 and 2, 4 to 6 and 20 to the end of the line for each line of file.
cut -f 1,3 -d: /etc/passwd # Extract the username and ID of each line in /etc/passwd.

The default delimiter is TAB but can be specified with -d.

[modifier] Characters conversion

To translate the stdin to stdout, use tr.

tr [options] SET1 SET2

Common options: -d: delete character in SET1. -s: replace sequence of character in SET1 by one.

Examples:

tr ‘a‘ 'A'  # Translate lower a with A
tr ‘[A-Z]’ ‘[a-z]’ # Translate uppercase to lowercase
tr -d ‘ ‘ # Delete all spaces from file

To convert tabs to spaces, use expand and to convert spaces to tabs, use unexpand.

expand  file
unexpand file

[modifier] Lines manipulation

To paste multiple lines of files, use paste.

paste [options] [files...]

Common options: -d #: delimiter: Use # for the delimiter. -s: serial: paste one file at the time.

Examples:

paste f1 f2 # Display line of f1 follow by f2.
paste -d: file1 file2 # Use ':' for the delimiter.

To join multiple lines of files, use join.

join file1 file2 

To remove duplicated line, use uniq.

uniq [options] [files...]

Common options: -d: only print duplicated lines. -u: only print unique lines.

Examples:

uniq -cd file # Display the number of duplicated line.

Splitting files

To split big files, use split.

split [options] file

Common options: -l #: split every # lines. -b #: split file in bytes or b for 512 bytes, k for 1Kbytes, m for 1 Mbytes.

Examples:

split -l 25 file  # Split file into 25-line files.
split -b 512 file # Split file into 512-byte files.
split -b 2b file  # Split file into 2*512-byte files.

[modifier] Formating for printing

To format a file, use fmt.

fmt [options] [files...]

Common options: -w #: maximum line width.

Examples:

$ fmt -w 35 file # Display 35-character lines width.

To format a file for a printer, use pr.

pr [options] [files...]

Common options: -d: double space.

Examples:

$ pr -d file # Format file with double-space.

Sort lines of text files To sort the lines of the names files, use sort.

sort [options] file

The results are displayed to the standard output. Common options: -r: Reverse -f: Ignore case -n: Numeric -o: file: Redirect output to file -u: No duplicate records -t;: Use ';' as delimiter, rather than tab or space.

Examples:

sort file -r
sort file -ro result

Binary file dump

To dump a binary file, use od.

od [options] file

The results are displayed to the standard output and start with an offset address in octal.

Common options: -c: each byte as character -x: 2-byte in hex -d: 2-byte in decimal -X: 4-byte in hex. -D: 4-byte in decimal.

Examples:

$ od -cx /bin/ls
0000000 177   E   L   F 001 001 001  \0  \0  \0  \0  \0  \0  \0  \0  \0
       457f 464c 0101 0001 0000 0000 0000 0000
0000020 002  \0 003  \0 001  \0  \0  \0     224 004  \b   4  \0  \0  \0
       0002 0003 0001 0000 9420 0804 0034 0000
0000040   °   ²  \0  \0  \0  \0  \0  \0   4  \0      \0 006  \0   (  \0
       b2b0 0000 0000 0000 0034 0020 0006 0028
0000060 032  \0 031  \0 006  \0  \0  \0   4  \0  \0  \0   4 200 004  \b
       001a 0019 0006 0000 0034 0000 8034 0804

[modifier] Exercices

  1. Use wildcard characters and list all filenames that contain 'x' follow by 'in' in the /etc directory.
  2. Use wildcard characters and list all filenames that start with any character between 'a' and 'e' that have at least two more characters and do not end with a number.
  3. Use wildcard characters and list all filenames of exactly 4 characters and all filenames starting with an uppercase letter. Do not descend into any directory found.
  4. Use wildcard characters and list all files that contains 'sh' in /bin.
  5. Affichez votre variable d'environement HOME precédée de la chaine de caractere "La valeure de $HOME est:"
  6. Display the contents of $SHELL with two asterisk characters before and after it.
  7. How would you display the following string of characters as is with echo using double quote and \.
    • @ # $ % ^ & * ( ) ' " \
  8. Compose echo commands to display the following two strings:
    • That's what he said!
    • 'Never Again!' he replied.
  9. Affichez le nombre de mots dans tous les fichiers commencants par la lettre h dans le répertoire /etc.
  10. How would you send a 2M file with two 1.44M floppy. How would you put back together the splitted file?
  11. What is the command to translate the : delimiter in /etc/password by #?

[modifier] Gestion de base des fichiers

[modifier] Objectifs

Description: Les candidats devraient etre en mesure d'utiliser les commandes de base UNIX pou copier, déplacer, et retirer des fichiers et des directory. Ces taches regroupent les opérations avancées de gestion de fichier tel que la copie recursive de fichiers multiples, retirer des directory recursivement, et deplacer des fichiers qui rencontre " a wildcard pattern". Cela inclus d'utiliser les spécifications simples et avancés de "wildcard" pour se referer aux fichiers, aussi bien que d'utiliser find pour localiser et agir sur les fichiers en se basant sur le type, la taille, et le temps(time).

Key files terms and utilities include:
cp
find
mkdir
mv
ls
rm
rmdir
touch

file globbing

cp: Copy files and directories. ls: List directory contents.

[modifier] Créer et supprimer des répertoires

Pour créer un répertoire, utilisez mkdir.

mkdir [options] dir

Options courantes:

-m mode: set permission mode. Default use umask.
-p parent: cré les répertoires parents si innexistants

Examples:

mkdir -m 0700 bin
mkdir -p bin/system/x86

Pour supprimmer un répertoire vide, utilisez rmdir.

rmdir [options] dir

Common options:

-p parent: supprime les sous-répertoires vides.

Examples:

rmdir  tmp
rmdir -p bin/system/x86

[modifier] Copier des fichiers et des répertoires

Pour copier une fichier en un autre, ou vers un répertoire, utiliser la commande cp.

cp [options] source target

Source et target peuvent être un fichier ou un répertoire.

Common options:

-i interactive: prompt to overwrite
-r recursive: copy the subdirectories and contents. Use -R for special files.
-f force: force the overwriting

The default is to silently clobber the target file. Does not alter the source.

Examples:

cp *.[a-z] /tmp
cp readme readme.orig
cp  ls /bin
cp -ri bin/* /bin

[modifier] Déplacer et renommer des fichiers

Pour renommer un fichier, un répertoire ou pour déplacer un fichier ou un répertoire vers un autre endroit, utilisez mv.

mv [options] source target

Source et target peuvent être un fichier ou un répertoire.

Common options: -i interactive: prompt to overwrite -f force: force the overwriting -v verbose The default is to silently clobber the target file. Does not alter the srcfile. Examples: mv *.[a-z] /tmp mv readme readme.orig mv ls /bin mv -fi bin/* /bin

[modifier] Afficher une liste de fichiers et des informations

La commande pour lister le répertoire courrant est ls.

ls [options] [filenames]

Common options are:

-l for a long format
-F Append a file type character
-a All files, including hidden
-R Recursive listing of subtree
-d Do not descend into directory

La commande ls est l'équivallent de la commande dir sous DOS.

Examples of ls output:

ls -l /bin/ls
-rwxr-xr-x    1   root  root  46784 mar 23  2002 /bin/ls
ls -ld /bin
drwxr-xr-x    2 root   root   2144 nov  5 11:55 /bin
ls -a .
.bash_history .bash_profile .bashrc ...
ls -dF /etc .bashrc /bin/ls
.bashrc  /bin/ls*  /etc/

[modifier] Types de fichiers

The long format means:

ls -l /etc/hosts    #List a long format of the file hosts
-rw-r—r-- 1 root root 677 Jul 5 22:18 /etc/hosts

[modifier] Contenu des fichiers et emplacement

Linux/Unix does not distinguish file by filename extension, like Windows. To determine the file content use file.

file /etc .bashrc /bin/ls /dev/cdrom
/etc:       directory
.bashrc:    ASCII English text
/bin/ls:    ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses  shared libs), stripped
/dev/cdrom: symbolic link to /dev/hdc

To determine if a command is a built-in shell command or a program, use type, and use which to find its location.

type cp cd ls which type
cp is /bin/cp
cd is a shell builtin
ls is aliased to `ls $LS_OPTIONS'
which is aliased to `type -p'
type is a shell builtin
which cut
/usr/bin/cut

[modifier] Créer et utiliser des fichiers

Les noms de fichiers peuvent être créé avec les redirections I/O :

cat chapter1 chapter2 > book

Un éditeur comme vi :

vi mynewfile

Plein d'utilitaires UNIX :

cp file newfile

Une application

netscape

La commande touch, qui créée des fichiers vides

touch memo

Un nom de fichier valide :

a maximum 255 caractères
doit respecter la casse (majuscules, minuscules,...)
peut comporter tous les caractères sauf l'anti-slash '\'

Recommended alphanumeric characters as well as plus, minus, and underscore characters.

Characters to avoid

Hypen character.
touch my-file -lt
White space.
touch more drink
touch "more drink"
Most other special characters !@#$%^&*():;"'}{|\<,>.?~`
touch memo*

[modifier] Supprimer des fichiers et des répertoires

To remove files or subtree directories, use rm.

rm [options] files

Files can be a file or a directory.

Common options:

-i interactive: prompt to for each removal
-f force: force the overwriting
-r recursive: remove subtree directories and contents

There is no unremove or undelete command.

Examples:

rm *.[a-z]
rm readme readme.orig
rm  ls /bin
rm -rfi /bin
cd; rm -rf *  .*

[modifier] Trouver des fichiers dans le sous-répertoire d'une arborescence

To search for a file in a subtree directory, use find.

find [subtrees] [conditions] [actions]

The command can take multiple conditions and will search recursively in the subtree.

Some possible conditions are:

-name [FNG] # Search fo the FNG name
-type c # Type of file [bcdfl]
-size [+-]# # Has a +- size in blocks (c:bytes,k:kilo)
-user [name] # Own by user
-atime [+-]# # Accessed days ago +n means not been accessed for the last n days -n means been accessed the last ndays.
-mtime [+-]# # Modified days ago
-perm nnn # Has permision flags nnn

Some possible actions are:

-print # Print the pathname
-exec cmd {} \; # Execute cmd on the file
-ok cmd {} \; # Same as -exec but ask first

Examples

find . -name '*.[ch]' -print
find /var /tmp . -size +20 -print
find ~ -type c -name '*sys*' -print
find / -type f -size +2c -exec rm -i {} \;
find / -atime -3 -print
find ~jo ~toto -user chloe -exec mv {} /tmp \;

[modifier] whereis and which

To locate a binary, source file, or man pages, use whereis.

whereis [options]

Common options:

-b: Search only for binaries.
-m: Search only for manual sections.
-s: Search only for sources.

Examples:

whereis host
host: /usr/bin/host /etc/host.conf /usr/share/man/man1/host.1.gz
whereis -m host
host: /usr/share/man/man1/host.1.gz

To locate a file located somewhere defined by the PATH variable, use which.

which -a ls
/bin/ls

The -a will look for all possible matches in PATH, not just for the first one.

[modifier] Exercices

  1. Compose an interactive command to remove all .tmp file in your home directory. Respond y to every prompt.
  2. List all the files in users home directories ending with .pdf that are bigger than 50 blocks and have not been accessed for a month.
  3. Create a file file.h that will contain all the filenames ending with .h found in the /usr directory.
  4. Do a touch on all the c files found in /usr/src/packages directory.
  5. What are the default permissions when you create a new file and a new directory?
  6. How would you create a new file or directory that contains a space in the filename? (Example: 'new dir')
  7. What is the command to remove all the files of type char and block in your home directory?
  8. How to find the location of the programm find ?
  9. Delete all files in /tmp which are not owned by root and have not been accessed for a week.

[modifier] Utiliser les streams, pipes, et redirections

[modifier] Objectifs

Description: Les candidats devraient etre en mesure de rediriger les flux(streams) et de les connecter de façon à effectuer avec efficience des données texte (process textual data). Ces taches inclues les redirection standard, les erreurs standard, faire un pipe sur sur le resultat d'une commande vers l'entrée d'une autre commande(piping), utiliser la sortie d'une commande (output) comme argument d'une autre commande et d'envoyer la sortie à la fois vers la sortie standard(stdout) et un fichier.

Key files terms and utilities include:
tee
xargs
<
<<
>
>>
|
` `

[modifier] Entrée et sortie standard

For each command executed in a terminal, there are: a standard input value 0. (default keyboard) a standard output value 1.(default terminal) and a standard output for the errors value 2. (default terminal).

Each channel can also be identified by an address: &0 for input, &1 for output, And &2 for errors.

Each channel [n] can be redirected. [n]< file: Default value of n is 0 and it reads standard input from file. [n]> file: Default value is 1 and it sends standard output to file. (clobber) [n]>>file: Default value is 1 and it appends standard output to file. <<word: Read standard input until word is reached. `command`: Substitute the command name by the result.

Examples:

$ pwd > file  # out=file in=none error=terminal.
cat chap* >book # out=book in=none error=terminal.
mv /etc/* . 2>error # out=terminal in=none error=error.
echo end of file >> book # out=book in=none error=terminal.
set -o noclobber # Shell does not clobber existing files.
ls > list 2>&1 # ls and errors are redirected to list.
ls 2>&1 > list # Errors are redirected to standard output and ls output is redirected to list.
cat `ls /etc/*.conf` > conffile 2>>/tmp/errors

Concatenate all the configuration files from /etc dir in conffile and append errors in file /tmp/errors.

Redirecting with pipes

Pipes are an efficient way to apply multiple commandes concurrently.

command1 | command2

The standard output of command1 will be piped to the standard input of command2. The standard error is not piped.

Examples:

ls -l /dev | more
ls -l /etc/*.conf | grep user | grep 500
ls -l /bin | mail `users`

To redirect the standard output to a file and to the terminal at the same time, use tee.

ls -l /dev | tee file
ls -l /etc | tee -a file # Append to the file

Building arguments

The xargs utility constructs an argument list for a command using standard input.

xargs [options] [command]

The xargs command creates an argument list for command from standard input. It is typically used with a pipe.

Common options: -p: prompt the user before executing each command.

Examples:

ls f* | xargs cat # Print to standard output the content of all files starting with f.
find ~ -name 'proj1*' print | xargs cat

Search in the Home directory for files starting with proj1 and send it to the standard input of cat.

Use the /dev/null device file to discard output or error messages.

Try the following:

grep try /etc/*
grep try /etc/* 2> /dev/null
grep try /etc/* > /dev/null 2> /dev/null

[modifier] Exercices

  1. Create a file list.bin that will contain all the filenames from /bin directory.
  2. Write a command that will append the list of files from /usr/local/bin to the file named list.bin and discard any error output.
  3. Split list.bin file into files that are 50 lines long and remove list.bin.
  4. From the splitted files create back list.bin. but with inversed order.
  5. Simplify the following commands:
ls *.c | xargs rm
ls [aA]* | xargs cat
cat `ls *.v` 2>/dev/null
  1. Use find to do the following command:
more `ls *.c`
  1. Write a command that will create a file list.sbin with the contents of /sbin and at the same time display it to standard output.
  2. Create a file that within the filename you include the creation time.
  3. Create a file that will contain all the filename in reverse order with extension .conf from the /etc directory.

[modifier] Créer, surveiller et terminer des processus

[modifier] Objectifs

Description: Les candidats devraient pouvoir gerer les processus. Cela comprend la compréhension de la façon d'executer un job en tache de fond ou non(foreground and background), de modifier leur statut(background vers foreground et vice versa), demarrer un processus qui s'executera sans connection à un terminal et signaler au programme de continuer aprés le logout. Les taches comprennent aussi la gestion des processus actifs, en selectionnant et triant les processus pour visualisation, en envoyant des signaux au processus, en tuant des processus et identifiant et tuant des aplications X qui ne se sont pas arretés alors que la session X est close.

Key files terms and utilities include:
&
bg
fg
jobs
kill
nohup
ps
top

[modifier] Créer des processus

A running application is a process. Every processes have: A process ID. A parent process ID. A current directory PWD. A file descriptor table. A program which it is executing. Environment variables, inherited from its parent process. Stdin, stdou, and stderr Other

Bash is a program that when it is executed becomes a process. Each time you execute a command in a shell a new process is created. Except for the buil-in shell command. They run in the shell context. Use type to check if a command is a built-in shell command.

Example type cp ls which type Monitor processes Once the system is up and running from a terminal it is possible to see which processes are running with the ps program. To display a long format of all the processes in the system, do:

ps -Al
F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
004 S     0     1     0  0  80   0 -   112 do_sel ?        00:00:04 init
004 S     0   381     1  0  80   0 -   332 do_sel ?        00:00:00 dhcpcd
006 S     0  1000     1  0  80   0 -   339 do_sel ?        00:00:00 inetd
044 R     0  1524  1222  0  79   0 -   761 -      pts/3    00:00:00 ps

The ps program will display all the processes running and their PID numbers and other information. To see a long format of the processes in your login session, do a:

ps -l
F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY          TIME CMD
000 S   500  1154  1139  0  80   0 -   724 wait4  pts/1    00:00:00 bash
002 S   500  1285  1283  0  77   0 - 24432 wait_f pts/1    00:00:00 soffice.bin
040 R   500  1442  1435  0  79   0 -   768 -      pts/4    00:00:00 ps
F: Process Flags 002: being created, 040: forked but didn't exec, 400: killed by a signal.
S: Process States: R: runnable, S: sleeping, Z: zompbie
UID: User ID, PID: Process ID, PPID: Parent Process ID, C: Scheduler, PRI: priority
NI: Nice value, SZ: size of routine, WCHAN: name of routine

[modifier] Surveiller des processus

To monitor the processes in real-time, use top. top

 9:20am  up  2:48,  4 users,  load average: 0.15, 0.13, 0.09

78 processes: 75 sleeping, 3 running, 0 zombie, 0 stopped CPU states: 15.3% user, 0.3% system, 0.0% nice, 84.2% idle Mem: 254896K av, 251204K used, 3692K free, 0K shrd, 27384K buff Swap: 514072K av, 0K used, 514072K free 120488K cached

 PID USER     PRI  NI  SIZE  RSS SHARE STAT %CPU %MEM   TIME COMMAND
1517 rarrigon   0   0 40816  39M 17372 R    15.0 16.0   2:59 mozilla-bin
1727 rarrigon  19   0   988  988   768 R     0.3  0.3   0:00 top
   1 root      20   0   220  220   188 S     0.0  0.0   0:04 init
   2 root      20   0     0    0     0 SW    0.0  0.0   0:00 keventd

RSS: The total amount of physical memory used by the task. SHARE: The amount of shared memory used by the task. %CPU: The task's share of the CPU time. %MEM: The task's share of the physical memory. Once top is running it is also possible to execute interactive commands: Type N to sort tasks by pid. Type A to sort tasks by age (newest first). Type P to sort tasks by CPU usage. Type M to sort tasks by memory usage. Type k to kill a process (prompted for pid).

[modifier] Terminer des processus

The ps program will display all the processes running and their PID numbers. Once the PID is known, it is possible to send signals to the process. SIGSTOP to stop a process. SIGCONT to continue a stopped process. SIGKILL to kill a process.

The program to send a signal to a process is called kill.

kill -SIGKILL [pid]
kill -63 [pid]
kill -l

By default a process is started in foreground and it is the only one to receive keyboard input. Use CTRL+Z to suspend it.

To start a process in backgroud use the &.

bash &
xeyes &

Job control

In a bash process it is possible to start multiple jobs. The command to manipulate jobs are:

jobs   # List all the active jobs
bg %job  # Resume job in background
fg %job  # Resume job in foreground
kill %job # Kill background job

When bash is terminated all processes that have been started from the session will receive the SIGHUP signal. This will by default terminate the process.

To prevent the termination of a process, the program can be started with the nohup command.

nohup mydaemon

[modifier] Exercices

[modifier] Modifier les priorités d'exécution des processus

[modifier] Objectifs

Description : Les candidats devraient pouvoir gerer les priorités d'execution des processus. Ces taches incluent de lancer un programme avec une priorité haute ou basse, de déterminer la priorité d'un processus et le changement de priorité d'un processus en cours.

Key files terms and utilities include :
nice
ps
renice
top

[modifier] Priorités

Pour démarrer une commande avec une priorité donnée, utilisez la commande nice .

  • nice -n +2 [command]
  • nice -n -19 [command]

The program nice changes the base time quantum of the scheduler. Les valeurs sont comprises entre -19 (-20), qui correspond a une haute priorité à +20 (+19), basse priorité. La valeur par défaut est 0. Seul le superutilisateur root peut donner une priorité négative (haute priorité). To modify the priority of a running program, use renice.

  • renice +1 -u root # Change the priority for all root processes.
  • renice +2 -p 193 # Change the priority for PID 193

[modifier] Exercices

  1. Quels processus utilisateur et root utilisent le plus de mémoire?
  2. Ouvrez deux terminaux. Dans le premier, tapez ce qui suit :
while [ 1 ]
do
echo -n The date is:;
date;
done

From the other terminal see that you can stop and continue the print out.

3) Same start as 2) but, make the print out to stop for 3[s] and to continue for 1[s] repeatedly. 4) Make a shell script to renice all process called apache to a 19 value. 5) Do a print from ps formated as: “username”, “command”, “nice value” 6) Kill all the process called “bash” and owned by user polto.

[modifier] Expressions régulières

[modifier] Objectifs

Description: Les candidats devraient pouvoir manipuler des fichiers et des données textes en utilisant les expressions réguliéres. Cet objectif inclu la création simple d'expression réguliéres contenant plusieurs éléments d'écriture. Ceci inclu aussi l'utilisation réguliére d'outils pour réaliser des recherches à travers un filesystem ou le contenu d'un fichier.

Key files terms and utilities include:
grep
regexp
sed

[modifier] Pattern matching

There are two kinds of pattern matching:

  • Wildcards (File Name Generation)
  • Regexp (Regular Expression)

Wildcard characters are mainly applied when they are used in the current directory or subdirectories. When wildcard characters *, ?, [ - ], ~, and ! are used in regexp they no longer generate filenames.

Some of the utilities that us regexp are:

  • grep, egrep
  • vi
  • more
  • sed
  • Perl

Limited regexp search pattern Used by all utilities using regexp.

  • Any 1 char . Ab.a Abla or Abca
  • 1 char set [ ] Ab[sd]a Absa or Abda only
  • 1 char range [ - ] Ab[a-z]a Abaa or Abba or ...
  • Not in set [^ ] Ab[^0-9]a Abaa or Abba or ...
  • 0 or more * Ab*a Absala or Aba or ...
  • Begin line ^ ^Aba Line starts>Aba
  • End line $ Aba$ Aba<line ends
  • Literal \ Aba\$ Aba$

Example:

Ab[0-3]s
^Ab\^bA
[01]bin$
^..\\
[^zZ]oro

Combinations of limited regexp Combinaison used by all utilities using regexp.

  • Any string .* Ab.*a Abrahma or Abaa or ...
  • String from [ ]* th[aersti]* There or This or ...
  • Multi range [ - - ] Ab[0-2][a-c]a Ab0aa or Ab1aa or ...
  • Match \ \\ \\[a-zA-Z]* \Bethoven

Examples:

Ab[0-3][a-z]s
...$
^[01]\^2
[0-9][a-z] \$
[a-zA-Z]*
^[^c-zC-Z]*
^[a-zA-Z0-9]$

Modifier patterns Replace strings matched by regexp patterns

  • Match m \{m\} b[0-9]\{3\} b911
  • One or more \{m,\} b[0-9]\{2,\} b52
  • Up to n \{m,n\} b[0-9]\{2,4\} b1234
  • Begining of word \< \<wh where
  • End of word \> [0-9]\> bin01

[modifier] grep

To find text in a file, use grep.

grep [options] [string] [files]

Best to quote the string to prevent interpretation.

Common options: -i: Ignore case -l: List filename only if at least one matches -c: Display only count of matched lines -n: Also display line number -v: Must not match.

Examples:

grep host /etc/*.conf
grep -l '\<mai' /usr/include/*.h
grep -n toto /etc/group
grep -vc root /etc/passwd
grep '^user' /etc/passwd
grep '[rR].*' /etc/passwd
grep '\<[rR].*' /etc/passwd

[modifier] sed

To apply a command on a stream, use sed.

sed [address1][,address2][!]command[options] [files...]

The program sed will apply a command from address1 to address2 in a file. The address1 and address2 format are regular expressions. The sed program is a noninteractive editing tool.

Examples:

sed '1,3s/aa/bb/g' file # Replace in file from line 1 to 3 aa by bb.
sed '/here/,$d' file # Delete line from here to the end.
sed '/here/d' file # Delete lines with word here.
sed '1,/xxx/p' file # Print lines from 1 to xxx.
sed '/ll/,/ff/!s/maison/house/g' file # In file replace words maison by house excluding lines from ll to ff.

[modifier] Exercices

  1. Copy all the files from /etc in your home direcory etc/. Display the contents of all the *.conf files by replacing the word host by machine.
  2. Display the contents of all the *.conf files that don't contain the root word. What is the command using grep and sed?
  3. Print out all the group names where root belongs to.
  4. List all the group names that are 4 or 5 characters long.
  5. List all the files that contain character lines without spaces (blank).
  6. List in etc/ directory all the files that contain numerical characters.
  7. Print with ls only the directory names in /.
  8. Do “ps -aux” and replace user r_polto by root and print it in to a file called new_process.txt
  9. List all process called apache and owned by a usernames starting by “p” or “P”.

[modifier] Effectuer les modifications de base des fichiers avec vi

[modifier] Objectifs

Description: Les candidats devraient pouvoir éditer des fichiers texte en utilisant vi. Cet objectif inclu la navigation dans VI, les nodes de base VI, insertion, édition, effacement, et recherche de texte.

Key files terms and utilities include:
vi
/, ?
h,j,k,l
G, H, L
i, c, d, dd, p, o, a
ZZ, :w!, :q!, :e!
:!

[modifier] vi

When using X-Windows, you can use mouse oriented editors such as xedit. In a cross-development environment, users use their favorite editor. On a non-windowing system, you only need a keyboard editor such as vi. The vi editor on Linux is the same as on any Unix systems.

vi has two modes:

  • Command mode: Anything you type will be interpreted as a command
  • Input mode: Anything you type will be inserted into the file

Transition from one mode to another Command mode to Input mode: i, I, a, A, o, O keys Input mode to Command mode: ESC key The default starting mode is the Command mode The file configuration .exrc can be created in your HOME directory to setup some vi behavior.

set ignorecase # No case-sensitive
set tabs=3 # 3 space for tab character

Perform basic file editing using vi

Enter Input Mode

  • i before cursor
  • I at start of line
  • a after cursor
  • A at end of line
  • o open line below
  • O open line above

Delete

  • dw delete word
  • dd delete line
  • D delete to end of line
  • x delete char at cursor

Move cursor

  • l one space right
  • h one space left
  • j one line down
  • k one line up
  • $ end of line
  • ^ start of line
  • w next word
  • e end of word

[modifier] Exercices

  • Demo
  • Insertion mode
  • Command mode
  • Editing/Replace/Join/Truncate
  • Search/Search and replace
  • Commands ex