Petit Manuel Unix - La maison de Jacques Madelaine

Transcription

Petit Manuel Unix - La maison de Jacques Madelaine
Août 2010
Petit Manuel Unix®
Jacques MADELAINE
Département d’informatique
Université de CAEN
14032 CAEN CEDEX
La première édition de ce manuel décrivait SMX un Unix développé à l’INRIA pour la machine française SM90, la
deuxième édition une adaptation pour SPIX, un Unix pour SM90 basé sur System V et développé par Bull. Il a été
ensuite modifié et corrigé pour SunOS l’Unix de Sun Microsystems, puis pour Solaris. La cinquième version a été
adaptée pour tenir compte des particularités du système GNU-Linux. Un chapitre supplémentaire dédié aux accès
réseau a été ensuite ajouté. Rappelons que presque toutes les commandes décrites vont fonctionner comme indiqué
sur tout système Unix commercial (Solaris, HP-UX, AIX, ...) ou libre (Linux, OpenBSD, FreeBSD, NetBSD, ...).
Mes remerciements à Sara Aubry pour sa relecture attentive et à François Girault pour avoir fourni la mise en
tableau des commandes d’emacs.
Mes remerciements à Davy Gigan pour m’avoir poussé à publier la version html en octobre 2003.
1
INTRODUCTION()
2
INTRODUCTION()
Petit manuel Unix 2002
INTRODUCTION
NOM
intro − introduction to the mini manual − introduction au petit manuel
DESCRIPTION
Ce manuel donne les principales commandes de Unix. Unix est une famille de systèmes d’exploitation ; les
commandes décrites existent, sauf précision contraire, sous Linux et Solaris, les deux systèmes disponibles
au département. Seules les principales options sont données, reportez-vous au manuel en ligne pour une
liste exhaustive. Chaque commande est décrite par trois sections :
NOM qui donne le nom de la commande, son nom en anglais (le nom Unix étant un mnémonique anglais
ne correspondant pas toujours bien avec le français) et en français.
SYNTAXE donne la syntaxe. Les parties entre crochets ([ ]) sont optionnelles. Les noms en caractères gras
désignent la commande ou des options. Les arguments en italique désignent des noms de fichiers, les autres
arguments sont en police normale.
Les arguments de contrôle sont traditionnellement, sous Unix, introduits par le caractère tiret (-), et sont
composés d’une seule lettre, ex. : -alx. Avec les commandes GNU est apparu la possibilité de donner
l’option de contrôle en format long (un mot) introduit par deux tirets ; on est obligé alors de donner les
options une par une, cela donnera sur l’exemple précédent : --all --long. Les commandes qui suivent le
standard GNU doivent avoir les options --help et --version qui donnent respectivement une petite aide en
ligne et le numéro de version de la commande sans l’exécuter.
DESCRIPTION est la section qui donne les effets de la commande et de ces arguments.
Ce document se termine (uniquement dans la version papier) par quelques pages de manuels originales de
GNU/Linux : dash(1), ed(1), gawk(1), join(1), sed(1), sort(1).
La page de ed contient en particulier la définition des expressions régulières utilisées par grep.
Pour finir nous donnons les tables des codes ASCII et iso-latin9 obtenues comme page du manuel standard
asciii(7) et iso_8859_15(7) et les pages de manuel unicode(7) et utf-8(7).
Les commandes sont regroupées en chapitres :
GESTION DE L’ACCÈS UTILISATEUR
login stty passwd
ACCÈS EN RÉSEAU
rsync ssh scp sshfs
MANIPULATION DE RÉPERTOIRES
cd mkdir rmdir
MANIPULATION DE FICHIERS
a2ps ar basename bzip2 cat comm compress convert cp cut diff expand gzip head iconv lp more
paste pr recode sox split tail tar tee tr uniq wc
MANIPULATION D’ATTRIBUTS DE FICHIERS
chgrp chmod chown ln mv rm touch
PARCOURS DE HIÉRARCHIE
df du find locate whereis which
LANGAGES
cc cl f77 hugs javac pc perl php python
OUTILS DE DÉVELOPPEMENT
cpp cplus-dem doxygen eclipse gdb gprof grep indent javadoc ld ldd lint make netbeans nm nmap
od patch prof ranlib size strace strip time
EXÉCUTION DE PROGRAMMES
echo kill killall nice nohup script sleep
DEMANDES D’ÉTATS
date file id ls ps pwd rusers tty users w who
DIVERS
Petit manuel Unix 2002
3
INTRODUCTION
bc cal expr man test
COMMUNICATION ENTRE USAGERS
mail mesg talk write
OUTILS RÉSEAUX
ftp sftp web-browsers
MESURES ET SURVEILLANCE DE SYSTÈME
arch free fuser host lsof netstat perfmeter rup top uname uptime vmstat
ÉDITEURS DE TEXTES
emacs nano vi
COMPOSEURS DE TEXTES
groff latex
OUTILS GRAPHIQUES
4
Petit manuel Unix 2002
GESTION DE L’ACCÈS UTILISATEUR
NOM
login − login − connexion
SYNTAXE
login [utilisateur]
DESCRIPTION
Enregistre la connexion d’un utilisateur au système. Vérifie le mot de passe et établit l’identité de l’utilisateur et celle du groupe auquel il appartient. Fait l’initialisation du terminal. Établit le catalogue de travail.
Annonce la présence de courrier. Affiche les messages du jour. Exécute le fichier « .login » de l’usager.
Lance l’interpréteur de commande ou un autre programme initial suivant ce qui est indiqué dans le fichier
« /etc/passwd ». Si ce programme est un shell, ce dernier exécutera le fichier « ˜/.profile » ou « ˜/.bash_profile » s’il s’agit de bash ; notons que par défaut au département le bash_profile se contente d’exécuter le
« .bashrc » de l’utilisateur.
NOM
stty − set terminal type − positionner des options de terminal
SYNTAXE
stty [options]
DESCRIPTION
Positionne certaines options d’entrées-sorties pour le terminal. Les options sont données en argument de la
commande. Sans argument cette commande donne l’état actuel du terminal.
Voici quelques options :
-a
imprime toutes les options du terminal (à utiliser seul).
vitesse
change la vitesse de transmission. En général vitesse est 1200, 9600 ou 19200.
ctrlcar c
« c » devient le caractère de contrôle donné. Si « c » est précédé du chapeau « ˆ », la valeur
utilisée est le caractère de contrôle correspondant. Voici la liste des contrôles possibles avec
leur valeur par défaut :
erase
annulation du dernier caractère (DEL).
kill
annulation de la ligne (ˆU).
werase annulation du dernier mot (ˆW).
eof
fin de fichier (ˆD).
eol
fin de ligne (ˆJ).
intr
interruption , envoie le signal SIGINT(ˆC).
quit
quit, envoie le signal SIGQUIT (ˆ\).
start
caractère de contrôle de flux : reprend l’affichage (ˆQ).
stop
caractère de contrôle de flux : arrête l’affichage (ˆS).
susp
suspend la tâche courante (ˆZ).
rprnt
réaffiche la ligne courante (reprint) (ˆR).
flush
prise en compte immédiate de l’entrée (ˆO).
lnext
supprime le sens particulier du caractère suivant (ˆV).
echo
fait l’écho de tout caractère tapé (pas d’écho avec -echo).
echoe
fait l’écho du caractère « erase » de façon telle que le caractère annulé soit effacé d’un écran
vidéo (fonctionne très mal sur un terminal papier). Pas d’écho spécial de « erase » avec -echo.
echok
envoie (n’envoie pas avec -echok) un caractère de nouvelle ligne sur réception du caractère
« kill ».
icanon
les caractères sont disponibles après réception d’une fin de ligne. Les caractères erase, kill,
rprnt et werase sont traités.
-icanon
les caractères erase, kill, rprnt et werase n’ont plus de signification particulière. Le code du caractère eof indique le nombre de caractères à taper pour qu’ils soient disponibles. Il suffit de
prendre « ˆA » pour eof pour que les caractères soient immédiatement disponibles au
Petit manuel Unix 2002
5
GESTION DE L’ACCÈS UTILISATEUR
programme :
$ stty -icanon eof « ˆA »
Si on veut que le programme gère l’écho lui même (comme more, vi, emacs, ...), faire :
$ stty -icanon eof "ˆA" -echo Cf raw.
isig
les caractères INTR et QUIT envoient des signaux.
-isig
les caractères INTR et QUIT n’envoient pas de signaux.
ixon
permet (ne permet pas avec -ixon) d’arrêter la sortie avec « ˆS » et de la faire repartir avec
« ˆQ ».
ixany
permet de faire repartir la sortie avec n’importe quel caractère. Seul « ˆQ » est autorisé avec
-ixany.
ixoff
demande que le système envoie (n’envoie pas avec -ixoff) les caractères de contrôle de flux
(« ˆS » et « ˆQ ») quand la file d’entrée est presque vide ou pleine.
tabs
préserve le caractère de tabulation (« ˆI »). Avec -tabs ou tabs3, les caractères de tabulation
sont remplacés par des espaces (un taquet de tabulation toutes les 8 colonnes).
lcase
ne transforme plus les minuscules en majuscules. Utile si on a tapé un nom de login en majuscules.
Les options suivantes sont les combinaisons qui sont le plus souvent utilisées :
sane
positionne des options jugées « saines » par le système. Étant donné qu’en général la ligne n’est
pas « saine », il faut taper stty sane entre des control-J et non des retours-chariot.
raw
littéralement : le mode cru ; tous les caractères sont disponibles immédiatement au programme
sans traitement de erase ou kill. Attention ceci est valable aussi pour ˆD donc on ne peut plus
spécifier fin de fichier, et bien sûr pour ˆC et on ne peut plus arrêter l’exécution en envoyant un signal à l’aide du clavier. Pour lancer un programme qui veut gérer toutes les entrées faire :
stty raw; programme; stty sane
Ainsi après la fin d’exécution du programme, stty sane remet tout en place.
NOM
passwd − password − mot de passe
SYNTAXE
passwd
DESCRIPTION
Change le mot de passe de l’usager. L’ancien mot de passe est demandé et le nouveau mot de passe est
demandé deux fois. Un mot de passe doit avoir au moins 6 caractères, dont au moins 3 caractères
alphabétiques et un caractère spécial ou numérique. Rappelons qu’il faut choisir son mot de passe comme
n’étant pas un mot d’un dictionnaire français ou étranger.
Lorsque la station est cliente NIS (Network Information System), la commande passwd va en fait changer
le mot de passe valable sur toutes les stations du réseau.
6
Petit manuel Unix 2002
ACCÈS EN RÉSEAU
NOM
rsync − remote file synchronisation − synchronisation de fichiers à distance
SYNTAXE
rsync [options] source... [destination]
rsync [options] [utilisateur@]hôte:source... [destination]
rsync [options] source... [utilisateur@]hôte:destination
DESCRIPTION
rsync permet de synchroniser des arborescences de fichiers sur la même machine (première forme d’appel),
ou depuis ou vers des machines distantes (les deux dernières formes d’appel). La copie à distance utilise
une connexion ssh. rsync ne transfère que les différences entre contenus source et destination ce qui permet d’économiser de la bande passante pour réaliser sauvegardes et copies miroir.
Voici le liste des principales options :
-v, --verbose
mode verbeux ou bavard
-n, --dry-run
ne fait rien, mais affiche ce qu’il pourrait faire. Utile pour tester l’effet de la commande sans réaliser d’opérations irréversibles
-a, --archive
mode archive (équivalent à -rlptgoD)
-r, --recursive
descend récursivement dans les répertoires
-b, --backup
fait des copies de sauvegarde dans destination
-u, --update
ne copie pas les fichiers déjà présents dans destination et qui sont plus récents que
dans la source
-l, --links
copie les liens symboliques comme des liens symboliques
-o, --owner
préserve le propriétaire (pour le super-utilisateur seulement)
-g, --group
préserve le groupe propriétaire (pour le super-utilisateur seulement)
-t, --time
préserve la date de dernière modification
-D
préserve les fichiers spéciaux
-C, --cvs-exclude
ignore les fichiers de backup des éditeurs comme le fait cvs (ex.: *˜, *.back, *% ...)
--delete
détruit les fichiers dans destination non présents dans source
--exclude=modèle
exclut les fichiers dont le nom correspond au modèle
--include=modèle
n’exclut pas les fichiers qui correspondent au modèle
-z, --compress
compresse les fichiers pour le transfert
Quelques exemples :
rsync -t *.java archive.dom:src/
recopie le contenu des fichiers Java du répertoire courant dans le répertoire src de la machine distante
archive.dom. Seul les différences sont effectivement transférées.
rsync -avz mike.info.unicaen.fr:/users/info/ens/jacques/L3 /tmp
Transfère récursivement tous les fichiers de la hiérarchie .../L3 de la machine distante dans le répertoire
/tmp de la machine locale. Le transfert est en mode « archive », c’est-à-dire qu’il préserve les liens, les
fichiers spéciaux et les méta-données des fichiers. De plus (-z) les données sont compressées pendant le
transfert.
rsync -avz mike.info.unicaen.fr:/users/info/ens/jacques/L3/ /tmp
La présence d’un ’/’ final change le comportement en ne créant pas le répertoire L3 dans le répertoire
Petit manuel Unix 2002
7
ACCÈS EN RÉSEAU
destination. On peut penser à ce ’/’ comme signifiant « copie le contenu du répertoire ». Ainsi les deux commandes suivantes sont équivalentes :
rsync -av /src/toto /dest
rsync -av /src/toto/ /dest/toto
NOM
ssh − OpenSSH secure shell client − shell de sécurité à distance
SYNTAXE
ssh [-X] [utilisateur@]machine [commande]
DESCRIPTION
Exécute la commande sur la machine distante. Si la commande est vide ssh ouvre une session comme
login. ssh rend rsh et rlogin obsolètes, sans parler de telnet ; en effet ces deux commandes transmettent
les mots de passe en clair sur le réseau ce qui peut permettre à des personnes malveillantes de récupérer des
mots de passe.
Premier exemple d’utilisation : l’utilisateur jacques a une session ouverte sur flupke et veux en ouvrir
une à distance sur quick avec également l’identité jacques. Comme la machine flupke ne connait pas
la machine quick elle demande à l’utilisateur d’ajouter son empreinte (Key fingerprint) composée de 128
bits écrits ici en hexadécimal. Cette empreinte sera ajoutée au contenu du fichier
˜/.ssh/known_hosts. Ensuite le mot de passe Unix de jacques sur quick est demandé.
flupke:˜ $ ssh jacques@quick
The authenticity of host ’quick.info.unicaen.fr’ can’t be established.
Key fingerprint is 1024 b2:c7:72:59:12:cd:c7:14:e6:05:12:1a:f6:62:0a:24.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ’quick.info.unicaen.fr,193.55.128.152’
to the list of known hosts.
[email protected]’s password: mot de passe Unix
Last login: Mon Aug 20 14:53:04 2001 on :0
Linux quick 2.2.19pre17 #2 Sat Apr 21 06:59:50 MEST 2001 i686 unknown
You have mail.
quick:˜ $
ssh a l’avantage de permettre l’utilisation des protocoles RSA (avec la version 1 de ssh) ou DSA (avec la
version 2) pour s’authentifier. Ces protocoles nécessitent une paire de clés privée et publique que l’on doit
d’abord générer. En utilisant la ligne de commande ssh-keygen -t dsa, la clé publique générée sera
stockée dans le fichier ˜/.ssh/id_dsa.pub, tandis que la clé privée sera stockée dans le fichier
˜/.ssh/id_dsa préalablement encryptée à l’aide de la « phrase de passe ». Cette phrase est une ligne
d’au plus 255 caractères (qu’il est conseillé de choisir ASCII imprimables) ; on peut donc sans problème
choisir une phrase complète facile à mémoriser et difficile à deviner par un tiers.
flupke:˜ $ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/jacques/.ssh/id_dsa):
Created directory ’/home/jacques/.ssh’.
Enter passphrase (empty for no passphrase): vrai secret
Enter same passphrase again: faux secret
Passphrases do not match. Try again.
Enter passphrase (empty for no passphrase): laphrasesecretequ’ilfautserappeller
Enter same passphrase again: laphrasesecretequ’ilfautserappeller
Your identification has been saved in /home/toto/.ssh/id_dsa.
Your public key has been saved in /home/toto/.ssh/id_dsa.pub.
The key fingerprint is:
b2:d4:0f:bd:43:bd:dc:90:6d:1a:cd:ef:a9:33:82:dc jacques@flupke
Vérifions le contenu de ˜/.ssh/id_dsa.pub
8
Petit manuel Unix 2002
ACCÈS EN RÉSEAU
flupke:˜ $ cat ˜/.ssh/id_dsa.pub
ssh-dss AAAAB3NzaC1kc3MAAACBANzk2EnXa3We7m4M0/W39YwydTxdnKqHvB9Bsd8Mkrscv7Web+yCI
0Ri4FzIBDKev5JIGiuDxotgAqk78IVeB8boa0M6PzWoMeMfRHLrl4eUMUeRw7aeaPVEbKlCOpE2ShBUXb
6vFIGBnZ7S4phGy7I10rkVuVWEqSBnlS9lTEZbAAAAFQCQiZaAQ9WNv164wLiH8S0S0xVtWwAAAIEAgPk
KuxCqI4AP+kGSsUNixosyNig35HEMC83FZBpinh8c5YYFuV4e63SLgw2814drHnVyHoRAX04UtwFiMIxL
IsgrMF6QOlgUZn2ZHgLcw583lm/oAdzzAhwfCI89SK0J4OGfF1ZDtCUdHkngkrsfuKsKG5ufXWSGdqyOg
j6ka7EAAACBAKpBVB3eMkWHasKuo8TkvNTuRNFf9V7BdqoST9sMpA+2FQb0Pj9T+jmuA/enezdSHmWxDm
S0coC4HoeFDRkEtYSuoFGG3Lj5S0L/IX24z0RrR/IzpbDFak/oELwzcwvMDitYN4PhpflHxcfFIQpwiPy
L2t+vnQY98na97Baxk1NI jacques@flupke
Je n’affiche pas le contenu de ˜/.ssh/id_dsa ni la « passphrase » car ils constituent à eux deux la clé
privée (à toujours garder secret, notons d’ailleurs les droits -rw------- sur ce fichier).
La clé publique doit maintenant être contenue dans la fichier ˜/.ssh/authorized_keys du compte
distant. Il existe plusieurs solutions pour transmettre cette ligne. On peux choisir les pigeons voyageurs, le
courrier de surface ou électronique, une disquette ou la commande scp. Il est plus simple sur notre réseau
de profiter de NFS et du fait que les comptes utilisateurs des stations partagent le même répertoire de login,
en faisant :
flupke:˜ $ cat .ssh/id_dsa.pub >>.ssh/authorized_keys
Le fichier ˜/.ssh/authorized_keys peut bien sûr contenir différentes clés publiques pour différents
comptes utilisateurs, d’où l’utilisation de ’>>’. L’authentification d’une connexion à distance se fera maintenant avec RSA :
flupke:˜ $ ssh jacques@quick
Enter passphrase for key ’/home/jacques/.ssh/id_dsa’: **************
Last login: ...
Le fonctionnement de l’authentification est le suivant : le serveur sshd génère une phrase, l’encode avec la
clé publique de l’utilisateur et l’envoie au client qui doit la décoder avec la clé privée (que l’on obtient avec
le contenu de ˜/.ssh/id_dsa et la « passphrase ») pour la renvoyer pour comparaison au serveur ; il n’y
a ainsi aucun réel transfert de secret qu’un tiers malveillant pourrait acquérir.
On peut également maintenant se servir de ssh-agent qui peut se rappeler pour la session des « passphrase »
et les fournir sans intervention de l’utilisateur. Les « passphrase » sont ajoutées à la connaissance de l’agent
par ssh-add. Si vous utilisez Gnome, un agent ssh est lancé et connu de tous les processus que vous
lancerez, sinon il faut le lancer explicitement (dans le shell du login, avant de lancer X, pour que tous les
processus le connaissent) :
flupke:˜ $ eval ‘ssh-agent‘
Agent pid 3834
Le eval et les accents graves sont là pour que l’environnement du shell soit augmenté de deux variables ;
la sortie de ssh-agent étant :
SSH_AUTH_SOCK=/tmp/ssh-IzYV9651/agent.9651; export SSH_AUTH_SOCK;
SSH_AGENT_PID=9652; export SSH_AGENT_PID;
Il faudra donc toujours faire :
flupke:˜ $ ssh-add /home/jacques/.ssh/id_dsa
Enter passphrase for /home/jacques/.ssh/id_dsa: **************
Identity added: /home/jacques/.ssh/id_dsa (/home/jacques/.ssh/id_dsa)
Tout futur appel à ssh ne nécessitera plus de taper ni mot de passe ni « passphrase » :
flupke:˜ $ ssh jacques@quick
Last login: ...
Pour terminer la session à distance il suffit, comme d’habitude, de terminer le shell avec un contrôle D ou la
commande exit.
L’option -X permet d’acheminer les messages du protocole X11 par le canal ouvert par ssh au lieu de se
servir directement de TCP/IP, en utilisant ce canal comme un tunnel (tunelling). Ceci est réalisé en positionnant la variable d’environnement DISPLAY à machinedistante:10.0, 10 correspond à un écran virtuel
qui est réalisé par le passage des messages X11 par le canal ssh et l’affichage sur le serveur X du client ssh.
Notons que le serveur distant doit l’autoriser , ce qui est le cas de nos machines mais qui n’est pas toujours
le cas d’une installation par défaut de ssh.
Petit manuel Unix 2002
9
ACCÈS EN RÉSEAU
NOM
scp − secure copy − copie sûre
SYNTAXE
scp [-prvC] [[utilisateur1@]hôte1:]fichier1 [[utilisateur2@]hôte2:]fichier2
DESCRIPTION
scp permet de copier un fichier de la machine hôte1 de l’utilisateur1 sur la machine hôte2 pour le compte
de l’utilisateur2. Par défaut utilisateur et hôte sont l’utilisateur courant et la machine courante. scp utilise le
même mécanisme de sécurité que ssh et demande des mots de passe ou phrases de passe ; cette dernière
peut être fournie par un agent ssh.
L’option -p permet de conserver pour la copie, les dates d’accès, de modification et les protections du
fichier original. L’option -r permet de copier récursivement un répertoire en entier. L’option -C demande
d’utiliser le mode compression pour le transfert.
Pour gérer des copies de sauvegarde facilement, voir la commande rsync.
NOM
sshfs − ssh file system − système de fichiers sur ssh
SYNTAXE
sshfs [utilisateur@]machine:[répertoire] point-de-montage [options]
fusermount -u point-de-montage
DESCRIPTION
sshfs permet de disposer en local d’une arborescence de fichiers résidant sur une machine distante. Il
utilise une connexion ssh et le module noyau FUSE (Filesystem in Userspace). Du côté machine distante, le
sous-sytème sftp de ssh est utilisé de façon transparente.
Le point de montage doit être un répertoire accessible en lecture écriture par l’utilisateur local.
fusermount avec l’option -u permet le démontage.
Exemple :
$ sshfs [email protected]:/ ˜/web/
Démontage :
$ fusermount -u ˜/web/
10
Petit manuel Unix 2002
MANIPULATION DE RÉPERTOIRES
NOM
cd − change working Directory − change le répertoire de travail
SYNTAXE
cd [répertoire]
DESCRIPTION
cd change le répertoire de travail. En l’absence d’arguments, le nouveau répertoire de travail est la valeur de
la variable HOME.
NOM
mkdir − make directory − création de répertoire
SYNTAXE
mkdir répertoire
DESCRIPTION
Crée un nouveau répertoire. Il contient les deux entrées ‘.’ pour le répertoire lui même et ‘..’ pour son père
dans la hiérarchie. L’ utilisateur doit avoir le droit ‘w’ dans le répertoire père.
L’option -p permet de créer les répertoires parents intermédiaires s’ils n’existent pas ; cette option est utile
dans des scripts d’installation.
NOM
rmdir − remove directory − destruction de répertoire
SYNTAXE
rmdir répertoire
DESCRIPTION
Détruit un répertoire. Ce dernier doit être vide (plus exactement, ne contenir que les deux entrées . et ..).
Petit manuel Unix 2002
11
MANIPULATION DE FICHIERS
NOM
a2ps − anything to PostScript − n’importe quoi en PostScript
SYNTAXE
a2ps[options]fichiers
DESCRIPTION
a2ps permet de transformer les fichiers en PostScript et de visualiser (avec gv) le résultat avant impression.
Cette commande est assez intelligente pour réaliser un rendu à l’aide de différentes polices afin de faciliter
la lecture des textes de programmes. Elle est cependant parfois trop intelligente quand, par exemple, au lieu
d’imprimer un source HTML, elle va imprimer son rendu par un navigateur. Les principales options sont :
-1, -2, ...,-9 pour demander l’impression d’une à neuf pages de texte par feuille (2 par défaut).
-s 1
pour une sortie en recto seul.
-s 2
pour une sortie en recto-verso.
-Elangage force le langage du fichier. Utiliser -Etext pour imprimer du source HTML et -Ejava pour du
source PHP.
-Lnombre
adapte la taille de la fonte pour obtenir nombre lignes par page.
-lnombre
adapte la taille de la fonte pour obtenir nombre caractères par ligne.
NOM
ar − archive − archive
SYNTAXE
ar clés fichier_archive [ fichiers]
DESCRIPTION
ar permet de créer et de maintenir un groupe de fichiers dans un seul fichier archive. Un fichier archive permet, entre autre, de regrouper les différents modules d’un programme (cf ranlib).
clé est un caractère parmi d, r, t ou x, éventuellement suivi de c, u ou v. fichier_archive est le nom du fichier
archive. fichiers sont les noms des composants. La signification des clés est la suivante :
c
crée l’archive.
d
détruit les fichiers de l’archive.
r
met à jour (remplace) ou ajoute les composants fichiers. Si la clé optionnelle u est utilisée, seuls les
composants ayant une date de modification plus tardive que dans l’archive seront remplacés.
t
affiche une table du contenu de l’archive.
u
ne remplace que les fichiers qui sont modifiés.
x
extrait une copie des composants « fichiers » de l’archive. Si aucun fichier n’est précisé, tous les composants de l’archive sont copiés dans le catalogue de travail.
v
option « verbeuse » : ar affiche tout ce qu’il fait.
Par exemple, pour créer une archive utilisable par ld faire :
$ ar ruv libexemple.a ex1.o ex2.o ex3.o
puis
$ ranlib libexemple.a
NOM
basename − base name − nom de base
SYNTAXE
basename fichier [suffixe]
12
Petit manuel Unix 2002
MANIPULATION DE FICHIERS
DESCRIPTION
basename détruit tout préfixe se terminant par ’/’ et le suffixe s’il est présent dans le nom de fichier. Cette
commande est surtout utile dans des procédures shell. Par exemple, la procédure suivante appelée avec
l’argument /users/bernard/lib/toto.c compile un programme C et renomme le fichier objet « toto » dans le
répertoire de travail :
#!/bin/sh
gcc $1
mv a.out ‘basename $1 .c‘
Notons que l’on pourrait faire simplement : gcc $1 -o ‘basename $1 .c‘
NOM
bzip2 bunzip2 − compress − compresse
SYNTAXE
bzip2 fichiers
bunzip2 fichiers
bunzip2 -c fichiers
DESCRIPTION
bzip2 produit un fichier d’extension « .bz2 ». Le taux de compression est encore meilleur qu’avec gzip
grâce à l’utilisation de l’algorithme de compression de Burrows-Wheeler et un codage de Huffman.
L’option -c permet d’utiliser bzip2 et bunzip2 comme un filtre (à la façon de zcat). Voir aussi la commande
gzip.
NOM
cat − catenate − concaténer
SYNTAXE
cat [-vte] fichiers
DESCRIPTION
cat lit chaque fichier en séquence et l’écrit sur la sortie. Exemples :
$ cat fich
imprime le fichier fich, et
$ cat fich1 fich2 >fich3
concatène les deux fichiers fich1 et fich2 et écrit le résultat dans
fich3. Il est illégal d’utiliser en entrée et en sortie le même fichier, ainsi on ne peut pas faire :
$ cat fich1 fich2 >fich1
Pour ajouter le contenu de fich2 à fich1, faire : $ cat fich2 >>fich1 .
L’option -v permet de visualiser les caractères de contrôle. Si on précise -t en plus, les caractères de tabulation sont visualisés « ˆI ». Avec -e, les fins de lignes sont signalées par un dollar ($). -t et -e n’ont aucun
effet sans l’option -v. Voir od pour une visualisation plus complète des caractères de contrôle.
NOM
comm − common − commun
SYNTAXE
comm [ - [123] ] fichier1 fichier2
DESCRIPTION
comm lit les fichiers dont les lignes doivent être triées suivant le code ASCII (cf la commande sort), et produit une sortie sur trois colonnes : les lignes présentes uniquement dans fichier1, les lignes présentes
uniquement dans fichier2 et les lignes en commun dans les deux fichiers.
Les arguments de contrôle 1, 2 et 3 suppriment l’impression de la colonne correspondante.
Gag : comm -123 f1 f2 est une opération nulle.
Petit manuel Unix 2002
13
MANIPULATION DE FICHIERS
NOM
compress uncompress zcat − compress − compresse
SYNTAXE
compress fichiers
uncompress fichiers
zcat fichiers
DESCRIPTION
compress réduit la taille d’un fichier en utilisant l’algorithme de codage adaptatif de LZW. Le taux de
compression typique d’un texte source est de 50 à 60%. Le fichier compressé à l’extension « .Z ».
uncompress restaure les fichiers dans leur contenu original. zcat se contente d’afficher le contenu décompressé.
pack, unpack et pcat utilisent le codage de Huffman et produisent des fichiers à l’extension « .z ». Ce
codage donne en général de moins bons résultats que Lempel-Ziv.
gzip, gunzip et zcat de GNU utilisent Lempel-Ziv qui donnent de meilleurs résultats que compress.
NOM
convert − convert image format − convertir des formats d’images
SYNTAXE
convert fichier-source fichier-résultat
DESCRIPTION
Cette commande fait partie de l’ensemble Image Magick qui permet de manipuler des images. convert va
créer une image dans le fichier résultat selon le format défini par l’extension du nom. Voici quelques principaux formats connus avec leurs extensions : Adobe PostScript file (ps), Adobe Encapsulated PostScript
file (eps), Portable Document Format (pdf), Portable Network Graphics (png), Joint Photographic
Experts Group JFIF format (jpeg ou jpg), Group 3 Fax (fax), CompuServe Graphics Interchange Format (gif), Microsoft Windows bitmap image file (bmp).
Ex. pour transformer une image png en PostScript (pour l’intégrer dans du LaTeX par exemple) :
convert image.png image.ps
convert connaît énormément de formats d’image mais ignore tout à l’heure actuelle du format vectoriel :
Scalable Vector Graphics (svg), mais cela ne saurait tarder ...
convert permet aussi d’appliquer des transformations de taille, de couleurs, d’ajouter des annotations. Il
peut aussi créer des images animées, par exemple : convert -delay 20 tintin.* tintin.gif
NOM
cp − copy − copier
SYNTAXE
cp [-ip] fichier1 fichier2
cp [-ip] fichiers répertoire
cp [-ip] -R répertoire1 répertoire2
DESCRIPTION
cp copie fichier1 sur fichier2. Si fichier2 existe déjà, son contenu est écrasé par le contenu de fichier1 mais
les attributs de fichier2 sont conservés (droits d’accès, propriétaire, date de modification). Si le fichier destination n’existe pas ou si l’option -p est précisée, les attributs du fichier source sont repris. Tout ceci sous
réserve de droits d’accès corrects.
Dans la seconde forme d’appel, les fichiers sont copiés dans le répertoire avec le même nom de base. Dans
la troisième forme d’appel, le répertoire1 est copié récursivement sur le deuxième.
L’option -i pour interactive demande confirmation avant d’écraser un fichier.
cp refuse de copier un fichier sur lui même.
14
Petit manuel Unix 2002
MANIPULATION DE FICHIERS
NOM
cut − cut − couper
SYNTAXE
cut -cliste fichiers
cut -fliste [-dc] [-s] fichiers
DESCRIPTION
cut imprime certaines parties des lignes des fichiers donnés en arguments, ou à défaut de l’entrée standard.
De plus, par convention un nom de fichier ‘-’ signifie l’entrée standard.
Les listes sont formées d’un ou plusieurs nombres ou intervalles séparés par des virgules. La numérotation
commencent à 1. Un intervalle est donné comme deux nombres séparés par un tiret ‘-’ ; des intervalles
incomplets peuvent être donnés, par exemple : ‘-4’ signifie ‘1-4’ et ‘2-’ signifie du deuxième jusqu’à la fin
de la ligne.
Dans la première forme d’appel la liste précise avec -c les caractères à conserver. Dans la deuxième forme,
on précise derrière -f, les champs à conserver. Le séparateur de champ, par défaut le caractère de tabulation
(ˆI), peut être précisé avec -d. L’option -s, permet de ne pas imprimer les lignes qui ne contiennent pas le
caractère de séparation de champs.
Exemples : cut -c1 poeme va écrire le premier caractère de chaque ligne (vers ?) du fichier ; cut -f1
-d: /etc/passwd imprime tous les comptes locaux à la machine.
NOM
diff − differences − différences
SYNTAXE
diff [-ce] fichier1 fichier2
DESCRIPTION
diff donne les différences entre les deux fichiers. Si fichier1 (resp. fichier2) est un répertoire alors un fichier
dans ce répertoire de même nom que fichier2 (resp. fichier1) est utilisé. On peut également donné deux
noms de répertoires, auquel cas tous les fichiers de mêmes noms des deux répertoires sont comparés successivement. L’option -c donne trois lignes de contexte.
Si on précise l’option -e, la sortie de cette commande est directement utilisable par l’éditeur de lignes ed
pour construire fichier2 à partir de fichier1. On peut ainsi reconstruire une version d’un fichier à partir
d’une version de base et d’une chaîne de différences de version à version. Exemple :
$ diff -e f.new f.old >f.diff
$ rm f.old
$ { cat f.diff; echo ’1,$p’ } | ed - f.new
*** affichage du contenu de f.old ***
Note : l’option « - » de la commande ed supprime l’affichage du nombre de caractères.
La procédure suivante reconstruit une ancienne version à partir d’une version courante ($1) et des
différences successives trouvées par diff ($2, $3...). La version reconstruite est affichée sur la sortie.
(shift; cat $*; echo ’1,$p’) | ed - $1
Note : on utilise des parenthèses au lieu des accolades de l’exemple précédent, afin que shift n’affecte pas
le premier paramètre pour ed.
Voir aussi la commande patch.
NOM
expand − expand − expanser
SYNTAXE
expand [-taquet1[,taquet2[,...]]] fichiers
unexpand [-taquet1[,taquet2[,...]]] fichiers
Petit manuel Unix 2002
15
MANIPULATION DE FICHIERS
DESCRIPTION
expand recopie les fichiers ou l’entrée sur la sortie en remplaçant les caractères de tabulation par autant
d’espaces pour atteindre le taquet suivant. Par défaut les taquets sont tous les 8 caractères. Si une seule
valeur de taquet est donnée, elle change l’espacement de tous les taquets. Sinon les taquets sont positionnés
aux colonnes taquet1, taquet2, etc. .
unexpand remplace les séries d’espaces successifs par des tabulations.
NOM
gzip gunzip zcat − compress − compresse
SYNTAXE
gzip fichiers
gunzip fichiers
zcat fichiers
DESCRIPTION
gzip produit un fichier d’extension « .gz ». Le taux de compression sur du texte est de 60 à 70 % ce qui est
meilleur qu’avec compress. Ne pas confondre avec zip disponible sur MSDOG (et sur Linux) bien qu’il
utilise le même algorithme de compression. Voir aussi la commande bzip2 qui utilise un algorithme plus
performant.
NOM
head − head − tête
SYNTAXE
head [-c nombre] [-n nombre] [fichier]
DESCRIPTION
head liste les 10 premières lignes du fichier argument ou à défaut de l’entrée standard. L’option -n permet
de spécifier le nombre de ligne à afficher. Avec -c le nombre d’octets à afficher est spécifié ; ce nombre peut
être suivi d’un ‘b’ pour spécifier des bloc de 512 octets, d’un ‘k’ pour kilo-octets ou d’un ‘m’ pour megaoctets.
NOM
iconv − input convert − conversion
SYNTAXE
iconv -f encodage [ -t encodage] fichiers...
iconv -l
DESCRIPTION
Agit comme un filtre et affiche sur la sortie standard, la conversion de l’encodage des caractères du contenu
du ou des fichiers donnés en argument. L’option -f donne l’encodage utilisé actuellement pour le fichier.
L’option -t permet de précisé l’encodage du résultat. Si cette otopn est omise, c’est l’encodage donné par
les locales qui sera utilisé. L’option -l liste tous les encodages connus par ce programme.
NOM
lp − off line printer − impression en différé
SYNTAXE
lp [-dimprimante] [fichiers]
cancel [-a] [imprimante] [id]
lpstat [-t] [-l]
DESCRIPTION
lp permet l’impression sur imprimante des fichiers arguments en utilisant CUPS (Common Unix Printing
System). Si aucun fichier n’est mentionné, lp utilise l’entrée standard. Le fichier nommé « - » est compris
16
Petit manuel Unix 2002
MANIPULATION DE FICHIERS
comme étant l’entrée standard et peut être ajouté à d’autres fichiers. lp associe à chaque requête d’impression un identificateur qui s’affiche sur le terminal.
cancel annule la requête d’identificateur « id » ou la requête en cours d’impression sur l’imprimante
dénommée « imprimante ». Avec -a, toutes les requêtes de l’utilisateur sont annulées.
lpstat affiche le statut courant du « spooler ». Sans option, seul le statut des requêtes de l’utilisateur
exécutant lpstat est fourni.
Les options principales sont :
-l
affichage du statut de toutes les requêtes.
-t
statut général du « spooler ».
Le format d’un statut de requête est : id propriétaire taille date imprimante. La taille est donnée en octets.
La date est la date de création de la requête.
Les causes de mauvais fonctionnement et leurs remèdes :
Le fichier ne sort pas du tout :
− Vérifiez que vous attendez votre listing sur la bonne imprimante.
− Vérifiez que l’imprimante est allumée.
− Vérifiez le nom du fichier.
− Vérifiez que votre arborescence a bien les droits x pour tout le monde, sinon utilisez une redirection :
lp options < fichier
− Vérifiez qu’il vous reste des crédits imprimante. La commande locale au département lpquota peut être
utilisée pour les contrôler.
Le fichier sort incomplètement :
− Vérifiez que vous n’avez pas supprimé le fichier durant l’impression.
En dernier recours, appelez l’administrateur système.
Un dernier conseil : visualisez toujours votre impression avant de l’envoyer vraiment sur l’imprimante avec
la commande a2ps.
NOM
more − more and more − de plus en plus
SYNTAXE
more fichiers
DESCRIPTION
more affiche de façon interactive les fichiers donnés en arguments écran par écran. Les principales commandes sont :
ESPACE
affiche l’écran suivant
RC
affiche la ligne suivante
/modèle
reprend l’affichage sur l’écran commençant deux lignes avant la ligne contenant une expression
correspondant au modèle.
b ou ˆB
affiche l’écran précédent
:p
passe au fichier précédent
:n
passe au fichier suivant
q
sort de more
h
aide en ligne
Note : La commande GNU less, malgré son nom peut en faire plus :-).
Petit manuel Unix 2002
17
MANIPULATION DE FICHIERS
NOM
paste − paste − coller
SYNTAXE
paste fichiers
DESCRIPTION
paste colle les fichiers côte à côte en séparant chaque ligne par des tabulations. On peut utiliser la convention ‘-’ pour l’entrée standard.
NOM
pr − print − imprimer
SYNTAXE
pr [options] fichiers
DESCRIPTION
pr imprime un fichier sur la sortie standard avec sur chaque page le titre, la date et le numéro de page. Cette
commande permet également la sortie multi-colonne et la sortie de plusieurs fichiers sur des colonnes parallèles suivant les options. Les options sont :
-n
produit une sortie sur n colonnes.
+n
commence à la page n.
-h t le texte t est écrit comme titre.
-wn la largeur de page est n caractères (72 par défaut).
-ln
la longueur de page est n lignes (66 par défaut).
-t
supprime les 5 lignes de tête et de pied de page.
-sc
sépare les colonnes par le caractère c (par défaut un espace).
-m
imprime tous les fichiers simultanément, chacun dans sa colonne.
Cette vieille commande était prévue pour être utilisée pour préparer la sortie sur des imprimantes à chasse
fixe. Avec les imprimantes PostScript, on peut lui préférer des commandes donnant directement du PostScript telles que a2ps.
NOM
recode − recode text file − recoder des fichiers texte
SYNTAXE
recode -l
recode [-qd] charset [fichier]
recode [-qd] charset1..charset2 [fichier]
DESCRIPTION
recode permet de transcoder en place les fichiers textes en tenant compte des codages de fins de ligne et des
jeux de caractères. recode -l permet de lister tous les systèmes de codage de caractères disponibles. Les
principaux sont : mac pour Macintosh, latin1 pour le code ISO_8859-1, pc pour MicroSoft, html pour le
codage avec des entités comme dans &eacute;, latex pour le codage des accents en LaTeX. Si un fichier est
précisé en argument, le fichier est réécrit en place, sinon recode agit comme un filtre.
L’option -q (quiet) supprime toute sortie d’erreur sur d’éventuels non réversibilités dans le codage. L’option
-d (diacritic) est utile pour le format html ou latex car alors recode ne s’occupe pricipalement que du
codage des signes diacritiques en ne touchant pas aux balises html ou aux commandes LaTeX.
Pour transformer un fichier venant de DOS, il suffit d’utiliser fromdos fichier
18
Petit manuel Unix 2002
MANIPULATION DE FICHIERS
NOM
sox − sound exchange − conversion de fichiers son
SYNTAXE
sox fichier-source fichier-résultat
DESCRIPTION
Cette commande est aux sons ce que convert est aux images et permet de convertir des fichiers sons, le format étant donné par l’extension. sox connait entre autres les formats suivants (avec leur extension) : .au
pour le fichier AU de SUN Microsystems, .gsm pour le format de compression utilisé par GSM 06.10, .sf
pour le fichier son de l’IRCAM, et enfin .wav pour le format Microsoft.
sox permet aussi d’appliquer des effets de toutes sortes sur le son, le tout en ligne de commande, un peu
comme ImageMagick pour les images.
NOM
split − split − découper un fichier
SYNTAXE
split [-n] [-b bytes[bkm]] [ fichier [nom] ]
DESCRIPTION
split lit le fichier donné, et le découpe en fichiers de n lignes (par défaut 1000). S’il n’y a pas d’arguments
ou si l’argument est - il lit l’entrée standard. Le nom des fichiers de sortie est construit à partir du nom
donné en argument (« x » par défaut) avec des suffixes allant de aa à zz en suivant l’ordre lexicographique.
La version GNU de split admet aussi l’argument -b suivi du nombre d’octets (b), de kilo-octets (k) ou de
méga-octets (m) suivant la lettre qui suit le nombre. Cette commande est utile pour découper une grosse archive (.tar.gz ou .tgz) pour la recopier sur des disquettes : split -b 1400k fichier.
Pour reconstituer l’archive sous Unix, il suffit de faire : cat xaa xab xac xad xae > fichier
Sous Dos, on peut faire : copy /b xaa+xab+xac+xad+xae fichier
NOM
tail − tail − queue
SYNTAXE
tail [±[nombre][lbc[r][f]]] [fichier]
DESCRIPTION
tail liste le contenu du fichier argument ou à défaut l’entrée standard à partir d’un endroit donné. « nombre » s’exprime en lignes, blocs ou caractères respectivement suivant les options l, b ou c. L’unité par
défaut est la ligne. tail copie l’entrée à partir de +nombre unités comptées en partant du début ou de -nombre unités comptées en partant de la fin. Avec l’option r les lignes sont listées en commençant par la fin.
L’option f permet de forcer une attente lors de la rencontre de la fin de fichier ; tail sera capable d’afficher
les éventuels ajouts. Utile pour surveiller la croissance d’un fichier en cours d’écriture comme un fichier de
journalisation. Il n’y a pas d’option +f.
NOM
tar − tape archive − archive sur bande
SYNTAXE
tar [zy] [cxt] [v] f archive fichiers
DESCRIPTION
La commande tar permettait originalement de gérer une bande magnétique ou un streamer, mais peut gérer
des archives dans un fichier ordinaire. L’argument archive peut donc être un nom de fichier ordinaire ou pour l’entrée ou la sortie standard, /dev/rst0 ou /dev/rmt/0 pour le streamer ¼", /dev/fd0 pour le lecteur
de disquette. Il faut préciser une des trois options suivantes :
Petit manuel Unix 2002
19
MANIPULATION DE FICHIERS
c
crée l’archive avec comme composants les fichiers dont les noms sont donnés en argument.
x
extrait de l’archive les composants dont les noms sont donnés en argument. Si aucun composant n’est
nommé, la totalité des composants sont extraits.
t
affiche la table du contenu. Les noms peuvent être utilisés ensuite avec l’option x.
On peut de plus préciser l’option v qui permet à tar d’afficher ce qu’il fait.
tar peut être utilisé pour recopier des arborescences :
( cd dir_source ; tar cf - .) | ( cd dir_destination; tar xvf - )
Cette recopie est différente d’une recopie faite par cp -R car le contenu des liens ne sont pas recopiés.
La plupart des logiciels sont livrés sous forme de « tars compressés » (tarball), c’est-à-dire que les divers
fichiers sont regroupés à l’aide de tar puis compressés avec compress (extension .tar.Z) ou de gzip (extension .tar.gz ou .tgz pour faire plaisir à MSDOG). Pour extraire le contenu, il suffit de « piper » le tar dans un
zcat ainsi : zcat archive.tar.gz | tar xvf Il est prudent de faire un tar tvf avant, pour vérifier le nom des fichiers créés. Si vous avez la chance
d’utiliser la commande tar de GNU, l’option supplémentaire z (dé)compresse automatiquement et on
peut écrire : tar zcvf archive.tgz racine
On peut aussi utiliser l’option y pour (dé)compresser avec bzip2.
NOM
tee − tee − té
SYNTAXE
tee [-a] fichiers
DESCRIPTION
tee recopie l’entrée sur la sortie et sur le(s) fichier(s) désigné(s). L’option -a ajoute la copie aux fichiers; par
défaut, l’ancien contenu des fichiers est écrasé.
Cette commande permet de journaliser les entrées et/ou sorties d’un programme tout en tapant les entrées et
en voyant les sorties normalement à l’écran comme ceci :
tee journal-entrée | programme | tee journal-sortie
Malheureusement, on ne peut pas avoir un journal d’entrées/sorties et la ligne de commande suivante ne
fonctionne pas à cause des accès concurrents au fichier journal :
tee journal | programme | tee journal
tee est utile pour créer un fichier vide, ce que l’on peut faire aussi avec : cp /dev/null fichiervide.
NOM
tr − translate − remplace
SYNTAXE
tr [-cds] ensemble1 [ensemble2]
DESCRIPTION
tr va remplacer chaque occurrence des caractères de ensemble1 de l’entrée standard par le caractère correspondant dans ensemble2. Un caractère peut aussi être spécifié par son code octal précédé de \. On peut
spécifier pour les ensembles des intervalles de caractères entre crochets. Ex. :
tr ’[A-Z]’ ’[a-z]’
va passer le texte en minuscules en remplaçant chaque majuscule par la minuscule correspondante. On peut
avec l’option -c ou --complement indiquer que l’on spécifie l’ensemble par son complémentaire. De
plus, tr peux non seulement remplacer des caractères un à un, mais aussi en supprimer si on précise
l’option -d ou --delete. Ex. :
tr -cd ’\012[a-z][0-9]’
va supprimer tous les caractères de l’entrée qui ne sont pas des fins de ligne (012 octal vaut 10 en décimal,
ce qui correspond au caractère Control-J ou \n) des lettres en minuscules ou des chiffres.
20
Petit manuel Unix 2002
MANIPULATION DE FICHIERS
NOM
uniq − unique − unique
SYNTAXE
uniq [- udc [+n] [-n]] [entrée [sortie] ]
DESCRIPTION
uniq compare les lignes adjacentes de l’entrée. Les duplications de lignes sont supprimées. Avec l’option
-u seules les lignes non répétées figurent dans la sortie. L’option -d ne provoque la sortie que des lignes
répétées. L’option -c donne le nombre de duplicata trouvés pour chaque ligne.
L’argument +n fait que les n premiers caractères de chaque ligne sont ignorés dans la comparaison. L’argument -n ignore les n premiers mots (un mot est une chaîne séparée par des espaces ou des tabulations).
NOM
wc − word count − compte de mots
SYNTAXE
wc [-lwc] [fichiers]
DESCRIPTION
wc compte les lignes (l), les mots (w) et les caractères (c) des fichiers ou à défaut de l’entrée standard. Par
défaut les trois sont comptés.
Petit manuel Unix 2002
21
MANIPULATION D’ATTRIBUTS DE FICHIERS
NOM
chgrp − change group − changer le groupe
SYNTAXE
chgrp [-R] groupe fichiers
DESCRIPTION
Change le groupe propriétaire des fichiers (qui peut bien sûr être différent du groupe du propriétaire). Cette
commande est réservée au super-utilisateur.
NOM
chmod − change mode − changer le mode
SYNTAXE
chmod [-R] mode fichiers
DESCRIPTION
Le mode des fichiers est changé en fonction de l’argument mode. Cet argument a la syntaxe suivante :
[catégorie] op droit [op droit] ...
Plusieurs arguments mode peuvent être donnés séparés par des virgules.
catégorie est une combinaison des lettres u (pour utilisateur propriétaire), g (pour groupe propriétaire) et o
(pour les autres : « others »). Si catégorie est omise la combinaison ugo est prise par défaut.
op est un caractère parmi +, - , =. + ajoute le droit pour la catégorie, - le retire et = assigne les droits de
façon absolue (tous les droits existant avant sont supprimés).
droit est une lettre parmi r (lecture : « read »), w (écriture : « write »), x (exécution : « execute »), s (positionner : « set »). Le droit s permet de prendre les droits du propriétaire pendant l’exécution d’un fichier. Le
droit x pour un répertoire permet d’exploiter un répertoire pour accéder à un fichier connaissant son nom, et
non de le lister entièrement.
Les droits d’accès ne peuvent être changés que par le propriétaire du fichier ou par le super-utilisateur. Avec
l’option -R, chmod change les droits dans toute la sous arborescence.
Le premier exemple retire le droit d’exécution du fichier aux utilisateurs non membres du groupe du propriétaire. Le deuxième met le droit d’exécution pour toutes les catégories, mais retire tous les autres droits y
compris pour le propriétaire ! Ces droits peuvent être remis par le troisième exemple.
$ chmod o-x fichier
$ chmod =x fichier
$ chmod u+r,u+w fichier
NOM
chown − change owner − changer le propriétaire
SYNTAXE
chown [-R] propriétaire fichiers
DESCRIPTION
Change le propriétaire des fichiers. Cette commande est réservée au super-utilisateur.
NOM
ln − link − lier
SYNTAXE
ln [-s] [-i] nom1 [nom2]
DESCRIPTION
Un lien est une entrée dans un répertoire faisant référence à un fichier. Un même fichier (avec son contenu
et tous ses attributs) peut avoir plusieurs liens dans le même système de fichiers. ln crée un lien sur le
fichier donné par nom1. Si nom2 est donné alors le lien porte ce nom, sinon le nom de base du fichier de
22
Petit manuel Unix 2002
MANIPULATION D’ATTRIBUTS DE FICHIERS
nom1 (cf basename) est placé dans le répertoire de travail. Du point de vue du système de fichier, après
l’exécution de ln, il n’y a pas de différence entre les deux liens nom1 et nom2.
Ces liens s’appellent également liens physiques par opposition aux liens symboliques crées à l’aide l’option
-s. Un lien symbolique est en fait une indirection vers un autre fichier. Ce lien a une nature spéciale signalée
par la lettre l dans le résultat de ls en format long.
L’option -i (pour interactif) demande confirmation avant d’écraser un nom existant.
NOM
mv − move − déplacer
SYNTAXE
mv [-i] fichier1 fichier2
mv [-i] fichiers répertoire
DESCRIPTION
mv déplace (renomme) fichier1 en fichier2. En fait, seul le lien est déplacé par rapport à la hiérarchie, mais
le contenu reste en place (cf. ln). Dans la deuxième forme d’appel, tous les liens sont déplacés vers le répertoire. Il faut bien comprendre que cette commande n’affecte que des entrées dans des répertoires (des liens
ou noms de fichiers) et non le contenu des fichiers, sauf si le fichier est déplacé au travers de deux systèmes
de fichiers différents auquel cas il est bien sûr recopié avec cp ; notons que certains Unix refusent d’utiliser
mv au travers de deux systèmes de fichiers.
L’option -i (pour interactif) demande confirmation avant d’écraser un nom existant.
NOM
rm − remove − enlever
SYNTAXE
rm [-ir] fichiers
DESCRIPTION
rm supprime l’entrée correspondante aux fichiers dans le répertoire. Si l’entrée est le dernier lien sur le
contenu du fichier alors ce fichier est détruit. Supprimer un fichier nécessite le droit w sur le répertoire,
mais aucun droit spécial sur le fichier (une question est quand même posée dans ce dernier cas).
Si le fichier est un répertoire, une erreur sera signalée sauf si l’option -r est employée. Dans ce cas rm supprime récursivement tout le contenu du répertoire et le répertoire lui-même (suppression de tout le sous
arbre).
Sous l’option -i, rm demande pour chaque fichier s’il doit le supprimer et avec l’option -r s’il doit examiner
chaque répertoire.
NOM
touch − touch − touche
SYNTAXE
touch fichiers
DESCRIPTION
touch met à jour la date de dernière modification des fichiers avec la date courante. Ceci est très utile avec
la commande make pour forcer une recompilation.
Petit manuel Unix 2002
23
PARCOURS DE HIÉRARCHIE
NOM
df − disk space on filesystems − espace disque des systèmes de fichiers
SYNTAXE
df [-l] [-i] [-hkm] [fichiers]
DESCRIPTION
df affiche la taille, l’espace utilisé, l’espace libre, le pourcentage utilisé et le point de montage de chaque
système de fichiers. Sont listés tous les systèmes de fichiers contenant les fichiers donnés en argument. Si
aucun fichier n’est donné, tous les systèmes de fichiers montés sont listés.
L’option -l ne va lister que les système de fichiers locaux en excluant, entre autres, les systèmes de fichiers
montés par NFS.
L’option -h affiche les tailles en format lisible par un humain (par ex. : 1K 42M 3G). Les options -k et -m
affiche les tailles respectivement en kilo et méga octets.
L’option -i affiche les informations de tailles relatives aux i-nodes des systèmes de fichiers.
Si l’on désire connaître l’espace utilisé par un sous arbre de la hiérarchie, il faut utiliser la commande du.
NOM
du − disk usage − usage disque
SYNTAXE
du [-hkm] fichiers
DESCRIPTION
du calcule la quantité d’espace disque utilisé par chaque fichier argument et par le sous-arbre pour les
répertoires. Les options -k et -m utilise le kilo ou le méga octet comme unité au lieu du bloc de 512 octets.
L’option -h affiche les tailles en format lisible par un humain (par ex. : 1K 42M 3G).
La commande df, ne fait pas de parcours de hiérarchie et donne l’espace libre sur le disque.
Exemple : du -sh ˜/{.[ˆ.]*,*} | less donne la place occupée tous les fichiers (cachés ou
non) du répertoire racine utilisateur ce qui peut être utile à ceux qui utilisent du cache pour leurs navigateurs.
NOM
find − find − trouver
SYNTAXE
find répertoire expression
DESCRIPTION
find parcourt récursivement le sous arbre de racine répertoire cherchant les fichiers rendant vraie l’expression. L’expression est formée de termes primaires décrits ci-après, ou de combinaisons de termes primaires
en utilisant les opérateurs suivants (ordre de précédence décroissant) :
1) Un groupe de termes primaires et d’opérateurs parenthésés (Attention : les parenthèses ayant une signification spéciale pour shell doivent être précédées de \).
2) La négation d’un terme primaire avec l’opérateur !.
3) La concaténation : la juxtaposition de termes primaires sous-entend le ET.
4) -o est l’opérateur OU.
Dans la description des termes primaires n désigne un entier décimal. L’entier sans signe n signifie exactement n; +n signifie plus que n et -n signifie moins que n.
24
Petit manuel Unix 2002
PARCOURS DE HIÉRARCHIE
-name fichier
vrai si fichier correspond au nom du fichier examiné ; le nom peut contenir les caractères jokers du shell ‘*’, ‘?’ et ‘[]’.
-type c
vrai si le type de fichier est c, où c est b, c, d, f, l ou p pour fichier spécial bloc, fichier
spécial caractère, répertoire, fichier ordinaire, lien symbolique ou fifo (i.e. « pipe »
nommé).
-links n
vrai si le fichier a n liens.
-user utilisateur
vrai si le fichier a utilisateur pour créateur.
-size n
vrai si le fichier a la taille n (en blocs de 512 octets).
-atime n
vrai si le fichier n’a pas été accédé depuis n jours.
-mtime n
vrai si le fichier n’a pas été modifié depuis n jours.
-exec commande
vrai si la commande rend le code de sortie 0. La fin de commande est marquée par : \;
(le ‘;’ est précédé du caractère d’échappement). {} comme argument est remplacé par le
nom du fichier examiné.
-ok commande
idem a « exec » sauf que le système demande s’il doit exécuter la commande.
-print
toujours vrai. A comme effet d’imprimer le nom du fichier examiné (est sous-entendu
avec GNU).
-newer fichier
vrai si le fichier examiné a été modifié plus récemment que l’argument fichier.
Exemples :
Chercher tous les fichiers de notre compte qui s’appelle ’toto’ :
$ find ˜ -name toto -print
ou simplement sur Linux :
$ find ˜ -name toto
Pour chercher tous les fichiers d’images PNG du compte (notez les apostrophes pour empêcher l’expansion
de l’étoile dans le shell) :
$ find ˜ -name ’*.png’
Pour chercher l’emplacement de la commande find :
$ find / -name find -print
Pour détruire tous les fichiers de l’arborescence de l’utilisateur de nom ’a.out’ ou ’*.o’ qui n’ont pas été
utilisés depuis une semaine (notez les anti-slashs devant les parenthèses et le point-virgule final) :
$ find ˜ \( -name a.out -o -name ’*.o’ \) -atime +7 -exec rm {} \;
Ce genre de recherche à partir de « / » avec find est très coûteux en temps et en ressource si on la lance sur
une machine du département, car elle revient à faire une recherche sur plusieurs dizaine de giga octects !
Par contre, pour une simple recherche de nom de fichier la commande locate est très efficace.
NOM
locate − locate − localiser
SYNTAXE
locate modèle
DESCRIPTION
Recherche dans une base de données des fichiers les noms correspondant au modèle à la manière du shell.
Les méta-caractères ‘*’, ‘?’, et ‘[]’ sont reconnus. La base est mise à jour automatiquement la nuit par un
‘cron’ à l’aide de la commande updatedb. Les répertoires personnels ne sont pas explorés par updatedb
pour des raisons de confidentialité. Cette commande est disponible sous Linux et n’est pas disponible en
standard sous Solaris.
Petit manuel Unix 2002
25
PARCOURS DE HIÉRARCHIE
NOM
whereis − where is − où est-ce
SYNTAXE
whereis commandes
DESCRIPTION
Cherche dans les répertoires systèmes les commandes données en argument.
NOM
which − which − lequel
SYNTAXE
which noms
DESCRIPTION
Indique comment sont évalués des noms de commande en tenant compte des éventuels alias et de la variable PATH. On peut lui préférer la commande type intégrée (builtin) au shell.
26
Petit manuel Unix 2002
LANGAGES
NOM
cc − C compiler − compilateur C
SYNTAXE
cc [options] fichiers
gcc [options] fichiers
g++ [options] fichiers
DESCRIPTION
cc est un compilateur C. Il utilise le pré-processeur cpp et l’éditeur de liens ld et accepte leurs options.
Plusieurs types de fichiers arguments sont acceptés. gcc et g++ sont les compilateurs C et C++ de la suite
GNU.
Les fichiers suffixés par .c sont considérés par le compilateur C comme des sources C. g++ considère les
fichiers suffixés par .cc, .C, .cxx, .cpp ou .c++ comme contenant du C++. Ceux-ci sont compilés, produisant pour chaque source un fichier objet de même nom de base suffixé par .o. Si on compile un seul programme, le fichier .o est détruit car cc enchaîne avec l’édition de lien à l’aide de ld qui produit un fichier
exécutable de nom a.out par défaut.
Traités de la même manière, les fichiers arguments suffixés par .s, sont considérés comme des sources
assembleur, et sont assemblés pour produire des programmes objets .o.
Les fichiers arguments suffixés par .o sont considérés comme des programmes objets. Ceux-ci sont liés
(dans l’ordre où ils sont rencontrés) éventuellement avec d’autres fichiers .o issus de la compilation de
fichiers .c arguments, pour produire un fichier exécutable nommé par défaut a.out.
Les options suivantes sont communes aux compilateurs C et C++ :
-c
supprime l’édition de liens. Un fichier .o est systématiquement produit.
-g
génère une table des symboles complète pour être utilisée par un débogueur.
-p
après compilation et édition de liens, production d’un fichier mon.out utilisable par prof (cf prof).
-pg
après compilation et édition de liens, production d’un fichier gmon.out utilisable par gprof
(cf gprof).
-O
optimiseur.
-S
compilation des programmes sources C et production de sources assembleur dans les fichiers correspondants suffixés par .s.
-E
lance uniquement le pré-processeur (cpp) avec sortie du résultat sur l’écran.
-pipe utilise des pipes plutôt que des fichiers intermédiaires temporaires.
Les autres options sont passées à ld.
NOM
cl − common lisp − lisp commun
SYNTAXE
cl
gcl
DESCRIPTION
Interprète, compilateur et environnement de programmation autour du langage ‘common lisp’.
Petit manuel Unix 2002
27
LANGAGES
NOM
f77 − fortan 77 − fortran 77
SYNTAXE
f77 ...
g77 ...
DESCRIPTION
Compilateur fortran 77. Non disponible en standard. g77 est la version de gcc qui comprend le fortran.
NOM
hugs − hugs − hugs
SYNTAXE
hugs ...
DESCRIPTION
hugs est un interprète du langage fonctionnel Haskell 98.
NOM
javac − java compiler − compilateur de java
SYNTAXE
javac fichiers
DESCRIPTION
javac est le compilateur du langage Java distribué par Sun Microsystems.
NOM
pc − pascal compiler − compilateur pascal
SYNTAXE
pc ...
DESCRIPTION
Compilateur pascal libre sémantiquement compatible avec Turbo Pascal 7.0 et supportant certaines extensions utilisées par Delphi. Voir http://www.freepascal.org/
NOM
perl − practical extraction and report language − perle
SYNTAXE
perl fichier
DESCRIPTION
perl est un langage interprété optimisé pour l’analyse et l’extraction d’informations de fichiers textes quelconques et l’impression de rapports basés sur ces informations. Il est également adapté à beaucoup de
tâches d’administration système. D’après les auteurs du langage, perl combine les avantages de C, sed,
awk et sh. Il existe des traducteurs de sed et awk en perl qui sont a2p et s2p. Il a été beaucoup utilisé
pour réaliser des scripts CGI pour le Web.
(Un autre acronyme de perl est « Pathologically Eclectic Rubbish Lister » :-).
NOM
php − php − php
SYNTAXE
php4 [ fichier ]
28
Petit manuel Unix 2002
LANGAGES
DESCRIPTION
php est un langage de programmation objet interprété et interactif. Il est beaucoup plus souvent utilisé
comme module apache pour publier des pages web dynamiques.
Certains disent que php est un acronyme signifiant : « People Hate Perl ».
NOM
python − python − python
SYNTAXE
python [ -ccommande | fichier ]
DESCRIPTION
python est un langage de programmation objet interprété et interactif. C’est un langage très propre que certains préfèrent à perl pour la programmation de CGI Web. Il existe une nombreuse bibliothèque de classes
qui rend ce langage adapté à toutes sortes d’applications.
Pour la petite histoire, certaines rumeurs parlent d’un nouveau langage qui réunirait les avantages de python
et de perl : parrot.
Petit manuel Unix 2002
29
OUTILS DE DÉVELOPPEMENT
NOM
cpp − C language preprocessor − pré-processeur de langage C
SYNTAXE
cpp [options] [entrée[sortie]]
DESCRIPTION
cpp est un pré-processeur C qui est invoqué par cc en première passe à chaque compilation. On peut également l’invoquer avec l’option -E de gcc. cpp accepte optionnellement deux fichiers arguments « entrée »
et « sortie » qui sont respectivement l’entrée et la sortie de cpp. Par defaut, si « entrée » (resp. « sortie »)
n’est pas mentionné, cpp lit l’entrée standard (resp. écrit sur la sortie standard). cpp n’est en général
invoqué qu’à partir de cc.
Les options sont les suivantes :
-Dnom=def
-Dnom définit la constante « nom » au sens d’une directive #define. Si « =def » est omis, « nom » aura la
valeur 1.
-Irep
change le mode de recherche des fichiers arguments des directives #include. Les fichiers arguments délimités par des guillemets sont recherchés dans le répertoire de « entrée », puis dans les
répertoires mentionnés par les options -I, puis dans le répertoire /usr/include. Pour les fichiers
délimités par <>, il n’y a pas de recherche dans le répertoire de « entrée ».
Toute directive cpp commence avec le caractère # en début de ligne. Voici la liste des directives :
#define nom chaîne
remplace chaque occurrence de « nom » par « chaîne » dans la suite du programme. « Chaîne » est
une suite de caractères délimitée par le premier séparateur après « nom » et la fin de la ligne. En
cas de longue définition, il possible de plier la ligne par « \newline ».
#define nom(arg1, ..., argN) chaîne
definit une macro instruction. Chaque occurrence de « nom » suivi de sa liste d’arguments (« nom »
et la première parenthèse doivent être impérativement accolés) est remplacée par « chaîne » où
chacun des paramètres « arg1 »... « argN » rencontrés, sont remplacés par leur valeur respective.
Exemple, avec la définition :
#define max(a,b) ((a) >(b) ? (a) : (b))
L’appel : max(x,y) donne après substitution : ((x) > (y) ? (x) : (y))
Le parenthésage est fortement conseillé pour éviter les effets de bord. Il faut aussi prendre garde à
la manière dont sont évalués les arguments. Exemple, l’appel : max(x++,y++) donnera après
substitution : ((x++) > (y++) ? (x++) : (y++)) et à l’exécution, on aura incrémenté x
ou y deux fois, ce qui n’est pas forcément ce qui était désiré.
#undef nom
annule la définition de « nom ».
#include “fichier”
#include < fichier>
inclut à cet endroit le contenu de « fichier » (ce contenu passera également dans cpp). Avec la
notation <fichier>, les fichiers sont uniquement recherchés dans le répertoire /usr/include.
L’usage veut que de tels fichiers soient suffixés par .h (head).
#endif termine une section de programme commençant par une directive de test (#if, #ifdef ou #ifndef).
Obligatoire après chaque directive de test.
#ifdef name
jusqu’au premier #endif ou #else rencontré, les lignes suivantes seront présentes dans le programme si et seulement si « name » a été défini précédemment à l’aide de la directive #define et
ceci sans avoir été l’objet d’un #undef.
30
Petit manuel Unix 2002
OUTILS DE DÉVELOPPEMENT
#ifndef name
jusqu’au premier #endif ou #else rencontré, les lignes suivantes ne seront pas présentes dans le
programme si et seulement si « name » a été défini précédemment à l’aide de la directive #define
et ceci sans avoir été l’objet d’un #undef.
#if expression
jusqu’au premier #endif ou #else rencontré, les lignes suivantes seront présentes dans le programme si la valeur de « expression » est non nulle. Sont utilisables dans « expression », tous les
opérateurs binaires du C exceptés les opérateurs d’assignation, l’opérateur ternaire ?:, les
opérateurs unaires -, ! et ˜. Les opérateurs ont la même précédence qu’en C. Un opérateur unaire
supplémentaire peut être utilisé. La syntaxe est defined nom ou defined ( nom ). Son évaluation
est vraie si nom a été l’objet d’un #define précédent. « Expression » peut contenir également des
constantes entières et des noms ayant été définis précédemment par une directive #define.
#else
si la directive de test précédente a pour valeur faux, les lignes suivantes jusqu’au premier #endif
apparaîtront dans le programme.
NOM
cplus-dem − C++ demangler − “démangleur” C++
SYNTAXE
cplus-dem [noms]
DESCRIPTION
cplus-dem permet de transformer un nom de variable ou fonction C++ encodé (“mangler”) en nom en clair.
En l’absence d’arguments, il décode les noms lus sur l’entrée standard. Exemple :
azrael $ cplus-dem __10PsqlstreamPCcT1i
Psqlstream::Psqlstream(char const *, char const *, int)
Cette commande peut être très utile pour retrouver des noms que l’éditeur de liens (ld) ne sait pas résoudre.
NOM
doxygen − documentatin generator − générateur de documentation
SYNTAXE
doxygen
DESCRIPTION
Ce programme permet de générer de la documentation de programmes C++ un peu comme javadoc fait
avec des programmes Java.
NOM
eclipse − extensible tool platform and Java IDE − EDI Java
SYNTAXE
eclipse [ options ] [ -vmargs arguments pour la JVM]
DESCRIPTION
Eclipse est un environnement de développement intégré écrit en Java. C’est une plate-forme ouverte et
extensible qui supporte des développements de projets plusieurs langages de programmation.
Sa lourdeur lui fait préférer netbeans par certains.
NOM
gdb − gnu debugger − débogueur de gnu
SYNTAXE
gdb [programme [core | N°Processus]]
Petit manuel Unix 2002
31
OUTILS DE DÉVELOPPEMENT
DESCRIPTION
gdb est un dégogueur symbolique qui permet d’exécuter sous son contrôle un programme compilé, avec
l’option -g. On peut examiner une exécution post-mortem en donnant le fichier core ou déboguer un programme qui tourne en donnant le numéro du processus exécutant ce programme. Les principales commandes sont :
break [fichier:]num_ligne
break [fichier:]fonction
break ... if condition
pose un point d’arrêt qui arrêtera l’exécution chaque fois que num_ligne est
atteinte, fonction est appelée, la variable change de valeur ou la condition
devient vraie.
run [ arguments ]
lance l’exécution du programme avec les arguments.
bt
‘backtrace’ : trace la pile d’exécution.
where
idem.
print expression
affiche la valeur de l’expression qui peut inclure des appels de fonctions.
c
relance (continue) l’exécution arrêtée par un point d’arrêt.
next
exécute la ligne suivante du source.
step [n]
exécute la ligne suivante du source en rentrant dans les fonctions.
info break
affiche les points d’arrêt ou de trace.
delete numéro
supprime les points d’arrêt ou de trace de numéros donnés.
tbreak [fichier:]num_ligne
pose un point d’arrêt temporaire, c’est-à-dire valable que pour une seule fois.
display expression
de même que print, mais s’exécute automatiquement à chaque arrêt.
quit
sort de gdb.
help [commande]
aide en ligne.
gdb peut être exécuté sous le contrôle d’interface graphique. Il existe le vieux programme xxgdb et le nouveau ddd qui sait même afficher les données structurées de façon graphique ; notons que ddd peut utiliser
d’autres débogueurs spécialisés pour d’autres languages que le C ou le C++. Les inconditionels d’emacs
pourront toujours l’utiliser pour contrôler gdb ; il suffit de l’appeler avec la commande emacs : M-x gdb.
emacs prompte alors pour la ligne de commande, un menu permet ensuite de contrôler l’exécution (break,
cont, run, etc.). emacs charge automatiquement le fichier source et laisse le curseur au point où l’exécution
est arrêtée. De plus, on peut poser un point d’arrêt sur la ligne courante d’un source avec la commande Cx espace.
NOM
gprof − graph profile − profileur graphique
SYNTAXE
gprof [-a][fichier]
DESCRIPTION
gprof interprète le fichier gmon.out produit par le monitor. Ce dernier fichier est produit automatiquement
pour toute exécution d’un programme compilé avec l’option -pg. gprof donne en plus d’une sortie comparable à celle de gprof, le graphe d’appel des fonctions avec les temps d’exécution cumulés. L’option -a
supprime l’impression des données liées à des fonctions statiques.
32
Petit manuel Unix 2002
OUTILS DE DÉVELOPPEMENT
NOM
grep − global regexp print − imprime un expresion régulière
SYNTAXE
grep [-vni] [-e] expression fichiers
egrep [-vni] [-e] expression fichiers
fgrep [-vni] [-e] expression fichiers
DESCRIPTION
grep dont le nom vient de la commande de ed : g/re/p qui permet d’imprimer toutes les lignes qui correspondent à l’expression régulière réalise exactement ceci. La variante egrep utilise les expressions
régulières étendues telles que décrites dans la documentation de awk, fgrep est seulement capable de
rechercher des chaînes fixes. grep ne comprend pas les méta-caractères + ? | ne sait pas faire des
regroupements avec des parenthèses, et l’étoile (*) ne peut s’appliquer qu’à une expression régulière s’exprimant sur un caractère.
L’option n permet de numéroter les lignes retenues. L’option i permet d’ignorer les différences de casses
majuscules/minuscules (sauf pour les lettres accentuées !). L’option e permet de donner une expression
commençant par un tiret, qui ne sera pas prise pour une option. Ex. : grep -e -i fichier permet de
récupérer les lignes qui contiennent l’expression régulière -i.
L’option v permet d’inverser la mise en correspondance, pour sélectionner les lignes ne correspondant pas
au motif donné par l’expression régulière.
NOM
indent − indent − indenter
SYNTAXE
indent fichier-source
DESCRIPTION
indent permet de rendre conforme à des règles de présentation données des sources C ou C++. Il existe une
foule de paramètres pour adapter le “look” de sortie. Ce programme est-il nécessaire quand on a emacs ?
NOM
javadoc − java documentatin − documentation java
SYNTAXE
javadoc
DESCRIPTION
Ce programme permet de générer de la documentation de programmes Java un peu comme doxygen fait
avec des programmes C++.
NOM
ld − link editor − éditeur de liens
SYNTAXE
ld [options] fichiers
DESCRIPTION
ld fusionne plusieurs programmes objets en un seul, résout les références externes, recherche les bibliothèques. Dans le cas le plus simple, plusieurs fichiers objets (.o) sont donnés en arguments. ld fait alors
l’édition des liens et produit un module objet (nommé par défaut a.out) directement exécutable ou réutilisable par ld (dans ce dernier cas, il faut mentionner l’option -r). Le droit x est donné au fichier a.out si
aucune erreur ne s’est produite.
Pour chaque bibliothèque argument (fichier suffixé par .a), ld ne charge uniquement que les routines
résolvant des références externes. La recherche ne s’effectue qu’une seule fois et à l’endroit où la bibliothèque a été mentionnée. Une bibliothèque doit donc être mentionnée après les fichiers lui faisant
Petit manuel Unix 2002
33
OUTILS DE DÉVELOPPEMENT
référence.
Les principales options :
-lx
ceci est une abréviation pour la bibliothèque libx.so ou à défaut libx.a, avec « x » chaîne de
caractères (par exemple libm.a pour la bibliothèque mathématique). Cette bibliothèque est
successivement recherchée dans les répertoires /lib, /usr/lib, /usr/local/lib. Attention,
pour des raisons susmentionnées la position de l’option -l est significative. Dans le cas
d’une bibliothèque partagée (« so » veut dire ‘shared object’), il faudra que la variable
d’environnement LD_LIBRARY_PATH contienne le répertoire où se trouve le fichier
« .so ».
-Lrépertoire
ajoute le répertoire à la liste des répertoires utilisés pour chercher les bibliothèques données
par l’option -l.
-o
la chaîne argument de l’option -o est utilisée pour nommer le fichier de sortie de ld
(nommé par défaut a.out).
-Bstatic
n’utilise pas les bibliothèques partagées.
-shared
permet de créer une bibliothèque partagée.
NOM
ldd − shared libraries dependencies − dépendances par rapport aux bibliothèques partagées
SYNTAXE
ldd fichier-exécutable
DESCRIPTION
ldd imprime les bibliothèques partagées nécessaires au chargement dynamique du programme exécutable.
NOM
lint − C program checker − vérificateur de sources C
SYNTAXE
lint [options] fichiers
DESCRIPTION
lint effectue une vérification de type beaucoup plus sévère que cc. Il détecte les instructions non-portables,
les bogues, les instructions jamais exécutées, les variables automatiques déclarées mais jamais utilisées, les
expressions logiques à valeur constante. Il effectue de plus des vérifications sur les fonctions. Détection des
fonctions appelées avec un nombre ou des types d’arguments différents, des fonctions retournant une valeur
à certains endroits et rien à d’autres, des fonctions dont la valeur retournée n’est pas utilisée ou est utilisée
mais pas retournée.
Ce programme est rendu obsolète avec le C ANSI et l’option -Wall de gcc ou de g++ qui signalent alors
tous les warnings.
NOM
make − make − fabriquer
SYNTAXE
make [-f fichier_make] [noms]
DESCRIPTION
make permet le contrôle de la création et la mise à jour de gros programmes modulaires. Il utilise les dates
de dernières modifications des fichiers sources pour minimiser le travail.
fichier_make (par défaut makefile) est constitué d’une suite d’entrées spécifiant les dépendances entre
modules et décrit les commandes à exécuter pour faire les mises à jour. Une entrée est constituée d’une liste
de noms (séparés par des espaces) suivi de ‘:’, puis d’une liste de noms dont dépendent les noms précédants
‘:’ ; cette liste est terminée par une fin de ligne ou un point virgule (Rappel : une ligne peut être continuée si
34
Petit manuel Unix 2002
OUTILS DE DÉVELOPPEMENT
elle se termine par ‘\’). Toutes les lignes suivantes qui commencent par un caractère tabulation (‘ˆI’) constituent des ordres Bourne-shell à exécuter pour mettre à jour les noms de l’entrée. Chaque ligne doit être
une commande shell complète ; par exemple, for do done doivent être sur la même ligne (ou sur des
lignes terminées par ‘\’).
Exemple : le fichier_make suivant spécifie que ’turlututu’ dépend des deux fichiers ’toto.o’ et ’titi.o’ construits à partir de source C++ et que l’édition de liens nécessite l’utilisation de la bibliothèque
mathématique.
turlututu : toto.o titi.o
g++ toto.o titi.o -o turlututu -lm
toto.o : toto.cc toto.h
g++ -c toto.cc
titi.o : titi.cc titi.h toto.h
g++ -c titi.cc
make met à jour les fichiers dont les noms sont passés en arguments; si aucun nom n’est donné, il met à
jour les noms de la première entrée du fichier_make. Il est d’usage de nommer cette première entrée all.
Dans un fichier_make une entrée peut être constituée d’une définition de macro de la forme :
chaine1=chaine2
ou
c=chaine2
Les occurrences suivantes de $(chaine1) ou $c seront remplacées par chaine2. De plus toute ligne
commençant par # est un commentaire ignoré par make.
Il est également d’usage d’avoir un entrée clean permettant de faire le ménage, comme :
/bin/rm -f *.o *.out core *˜
Il peut y avoir une entrée install pour installer le logiciel.
NOM
netbeans − Java IDE − EDI Java
SYNTAXE
netbeans [ options ] [fichiers]
DESCRIPTION
Netbeans est un environnement de développement intégré écrit en Java. Il supporte le développement de
projets en Java, mais aussi avec d’autres langages.
NOM
nm − name − nom
SYNTAXE
nm [-gu] [fichiers_objets ou archive]
DESCRIPTION
nm affiche la table des symboles des fichiers. Un nom précédé de U signifie un symbole utilisé et non
défini. D signifie un nom défini dans la section data, B un nom défini dans la section bss (données non initialisées) et T un nom défini dans la section texte de programme. Avec l’option -g seuls les symboles
externes (globaux) sont affichés. L’option -u n’affiche que les symboles non définis.
NOM
nmap − network map − carte réseau
SYNTAXE
nmap [machinefB]
Petit manuel Unix 2002
35
OUTILS DE DÉVELOPPEMENT
DESCRIPTION
nmap permet d’explorer tous les ports réseau ouverts de la machine cible. Attention, certains administrateurs de machine peuvent considérer cela comme une attaque !
NOM
od − octal dump − impression en octal
SYNTAXE
od [-bcdox] [fichier]
DESCRIPTION
od imprime le contenu d’un fichier en un ou plusieurs formats spécifiés. Si l’argument fichier n’est pas
précisé, l’entrée standard est utilisée. Les options de format sont :
b
interprète les octets en octal.
c
interprète les octets en ASCII. Les caractères non affichables sont donnés comme trois chiffres octal
ou comme caractère d’échappement du langage C.
d
interprète les mots en décimal.
o
interprète les mots en octal.
x
interprète les mots en hexadécimal.
NOM
patch − patch − rustine
SYNTAXE
patch < fichier-rustine
DESCRIPTION
patch permet d’appliquer des différences produites par diff à un ou plusieurs fichiers. Les modifications
sont faites en place ; on peut demander une copie de sauvegarde des fichiers avant modification avec
l’option -b. patch détecte automatiquement si les différences sont contextuelles (produites avec l’option
-c) ou au format admissible par ed. Il fonctionne aussi sur des fichiers binaires.
NOM
prof − profile − profil
SYNTAXE
prof [-a] [-l] [fichier]
DESCRIPTION
prof interprète le fichier mon.out produit par le monitor. Ce dernier fichier est produit automatiquement
pour toute exécution d’un programme compilé avec l’option -p. prof donne en sortie pour chaque
procédure externe le pourcentage de temps passé à exécuter cette procédure, le nombre d’appels et le temps
en millisecondes par appel. Par défaut, la table des symboles de a.out est utilisée.
Avec l’option -a, tous les symboles sont utilisés et non seulement les symboles externes. Avec l’option -l, la
sortie est triée sur les noms des symboles et non par ordre décroissant des pourcentages du temps
d’exécution.
NOM
ranlib − make a random library − fabriquer une bibliothèque
SYNTAXE
ranlib fichier-archive
36
Petit manuel Unix 2002
OUTILS DE DÉVELOPPEMENT
DESCRIPTION
ranlib permet de créer une table d’index des symboles contenus dans les composants d’un fichier-archive
(cf ar). Cette table __.SYMDEF devient le premier composant. Cette bibliothèque peut être utilisé ensuite
par ld si elle a le suffixe .a.
Sous Solaris ranlib est inutile car réalisé automatiquement par ar ; pour que les makefiles ne posent pas de
problèmes ranlib est un alias de true dans /usr/local/bin.
NOM
size − size − taille
SYNTAXE
size [fichier-objet]
DESCRIPTION
size donne le nombre (en décimal) d’octets occupés par le texte et les données d’un fichier-objet. Par défaut
a.out est utilisé.
NOM
strace − system call trace − trace des appels systèmes
SYNTAXE
strace ligne de commande
DESCRIPTION
strace va lancer la ligne de commande et tracer chaque appel système avec leurs arguments et leur code
retour.
NOM
strip − strip − enlever
SYNTAXE
strip fichier-objet
DESCRIPTION
strip supprime la table des symboles contenus par défaut dans un fichier objet. Cette opération permet de
gagner de la place (et donc du temps) quand un programme est au point (est ce que cela arrive parfois ;-).
NOM
time − time − temps
SYNTAXE
time commande
DESCRIPTION
La commande est exécutée normalement. time donne ensuite en secondes le temps réel écoulé pendant la
commande, le temps pris par le système et le temps passé en exécution pour la commande. time ne donne
pas l’heure.
Petit manuel Unix 2002
37
EXÉCUTION DE PROGRAMMES
NOM
echo − echo − écho
SYNTAXE
echo [-ne] arguments
echo arguments
DESCRIPTION
echo écrit ses arguments séparés par des espaces sur une ligne de la sortie standard. Sous les unix dérivés
de BSD, si l’argument -n est employé, la fin de ligne n’est pas ajoutée. Sous les unix dérivés de System V
ou avec l’option -e sous GNU, echo comprend également quelques séquences d’échappement du langage
C:
\b « backspace »
\c impression sans fin de ligne (identique à l’option -n)
\f « form-feed »
\n fin de ligne (« new-line »)
\r retour chariot
\t tabulation
\\ « backslash »
\n Le caractère dont le code ASCII est le nombre octal n de 1, 2 ou 3 chiffres, le tout précédé d’un
zéro (ex : « \033 » pour « escape »)
Les ‘\’ doivent être protégés de l’évaluation par le shell, soit en les doublant, soit en les encadrant par des
‘"’. Attention, comme echo est une commande intégrée au shell, les effets de /bin/echo et de echo sont en
général différents.
NOM
kill − kill − tuer
SYNTAXE
kill [-signal] N°Processus
kill -l
DESCRIPTION
kill envoie un signal au processus de numéro N°Processus. Par défaut, le signal 15 (SIGTERM) est envoyé.
On peut spécifier le signal par son numéro ou par son nom (sans SIG). kill -l rappelle la liste des signaux. Avec bash sous Linux, on obtient
felix:˜ $ kill -l
1) SIGHUP
2) SIGINT
3) SIGQUIT
4) SIGILL
5) SIGTRAP
6) SIGIOT
7) SIGBUS
8) SIGFPE
9) SIGKILL
10) SIGUSR1
11) SIGSEGV
12) SIGUSR2
13) SIGPIPE
14) SIGALRM
15) SIGTERM
17) SIGCHLD
18) SIGCONT
19) SIGSTOP
20) SIGTSTP
21) SIGTTIN
22) SIGTTOU
23) SIGURG
24) SIGXCPU
25) SIGXFSZ
26) SIGVTALRM
27) SIGPROF
28) SIGWINCH
29) SIGIO
30) SIGPWR
En général, le processus est tué lors de la réception d’un signal sauf s’il le prend en compte ; mais il existe
le signal 9 (SIGKILL) qui ne peut pas être détourné, et kill -9 nnn ou kill -KILL nnn tue toujours le processus identifié par nnn.
Par convention, le numéro de processus 0 signale tous les processus du groupe courant (c’est-à-dire en
général fils du login courant ou contrôlés par le terminal).
Les processus « signalés » (ils ne sont pas toujours tués, contrairement au nom de la commande) doivent
appartenir à l’usager, sauf si l’usager est le super utilisateur. Les numéros de processus peuvent être
obtenus par la commande ps. Voir aussi la commande killall.
38
Petit manuel Unix 2002
EXÉCUTION DE PROGRAMMES
NOM
killall − kill all − tuer les tous
SYNTAXE
killall [-signal] [-i] commande
kill -l
DESCRIPTION
killall fonctionne comme kill mais envoie des signaux aux processus faisant tourner la commande donnée,
ce qui permet de n’avoir pas à chercher leurs numéros. L’option -i demande confirmation avant d’envoyer le
signal à chaque processus.
NOM
nice − nice − mignon
SYNTAXE
nice [-nombre] commande
DESCRIPTION
nice exécute la commande avec une priorité faible. La priorité est incrémentée de la valeur de nombre (10
par défaut), un nombre élevé donnant une plus faible priorité.
Cette commande est utile pour exécuter une commande en arrière plan.
NOM
nohup − no hangup − ne pas raccrocher
SYNTAXE
nohup ligne de commande
DESCRIPTION
nohup permet de lancer une exécution qui pourra se poursuivre après la fin de session, car les signaux
SIGHUP et SIGTERM sont ignorés. La priorité est incrémentée automatiquement de 5 (correspond à
nice -5). Si les sorties standard et d’erreur ne sont pas détournées dans un fichier, elles se retrouvent
déviées dans le fichier ./nohup.out ou à défaut de droits d’écriture dans $HOME/nohup.out.
NOM
script − script − script
SYNTAXE
script [ fichier ]
DESCRIPTION
script fait une copie dans le fichier (typescript par défaut) de tout ce qui s’affiche à l’écran. Attention,
il y a bien stockage de tous les caractères tapés ou affichés y compris les caractères d’effacement de caractère, de mot ou de ligne). Pour conserver l’image d’une session, on pourra préférer le mode shell de
emacs.
NOM
sleep − sleep − dormir
SYNTAXE
sleep temps
DESCRIPTION
sleep suspend l’exécution du processus pendant un certain temps exprimé en secondes.
On peut utiliser sleep pour exécuter une commande après un certain temps :
{ sleep 500; commande } &
ou pour exécuter une commande périodiquement :
Petit manuel Unix 2002
39
EXÉCUTION DE PROGRAMMES
while true; do commande ; sleep 60; done
ou mieux :
while commande; do sleep 60; done
qui permet d’arrêter l’exécution périodique lors du premier échec de la commande.
40
Petit manuel Unix 2002
DEMANDES D’ÉTATS
NOM
date − date − date
SYNTAXE
date
DESCRIPTION
date écrit comme son nom le laisse supposer la date mais aussi l’heure courante. Attention time donne des
temps machine et non l’heure courante.
NOM
file − file − fichier
SYNTAXE
file fichiers
DESCRIPTION
file essaie de déterminer le type des fichiers (texte, binaire, C, ...) par examen des 512 premiers caractères
et du système de fichiers.
Note : il arrive que file se trompe!
NOM
id − identifier − identifiant
SYNTAXE
id
DESCRIPTION
id imprime les noms et les numéros d’identifiants (ID) réels et effectifs de l’utilisateur et de ses groupes.
NOM
ls − list − lister
SYNTAXE
ls [-abCcdFfgilmnopqRrstux] [noms]
DESCRIPTION
Pour chaque nom de répertoire argument ls liste leurs contenus. Pour chaque fichier argument, ls redonne
le nom du fichier et, suivant les options, fourni d’autres informations. Par défaut, ls donne une liste triée
par ordre alphabétique. Si aucun nom n’est donné en argument, le répertoire de travail est listé. Voici une
description des options les plus importantes :
-a
toutes les entrées sont listées y compris celles dont le nom commence par « . ».
-c
utilise la date de dernière modification du « i-node » (droits, créateur,. . .) à la place de la date de
dernière modification du fichier pour le tri (-t) ou l’affichage (-l).
-C
force la sortie en multi colonne.
-d
si un argument est un répertoire, liste juste son nom et non son contenu.
-g
liste en format long comme -l mais indique le nom du groupe du créateur au lieu du créateur. -lg
donne les deux.
-F
met un « slash » (/) après chaque répertoire, une étoile (*) après chaque fichier exécutable et une
arobace (@) après des liens symboliques.
-i
imprime le « i-number » en première colonne pour chaque entrée.
-l
liste en format long donnant le type (d, b, c, p, l, s ou -), les droits (pour le créateur, le groupe du
créateur, les autres), le nombre de liens, le nom du créateur, la taille en octets, la date de dernière
modification et le nom de l’entrée.
Petit manuel Unix 2002
41
DEMANDES D’ÉTATS
-m
la liste est séparée par des virgules.
-n
identique à l’option -l à l’exception du nom du créateur et de son groupe, qui ont remplacés par leurs
numéros (UID et GID).
-R
liste récursivement les sous répertoires.
-r
renverse l’ordre du tri.
-s
donne la taille en blocs de 512 octets (tient compte des blocs indirects).
-t
la liste est triée par date de dernière modification (les plus anciens d’abord).
-u
utilise la date de dernière utilisation pour le tri (-t) ou pour l’affichage (-l).
Notons enfin l’option h non standard bien pratique avec l’option l qui affiche la taille en format plus lisible
pour un humain.
NOM
ps − process status − statut des processus
SYNTAXE
ps [options]
DESCRIPTION
ps donne la description des processus en cours. Sans option, ps fournit des informations sur les processus
associés au terminal courant. Ces informations sont le numéro de processus, le nom de la ligne associé au
terminal, le temps total d’exécution (min:sec) et le nom de la commande.
Cette commande n’a pas les mêmes options, ni les mêmes sorties sous les unix dérivés de BSD (SunOs 4.1)
et sous SVR4
Description de ps sous System V :
Certaines options utilisent des listes en argument. Ces listes peuvent être spécifiées sous deux formes : une
liste d’items séparés par des virgules ou une liste délimitée par des doubles quotes, contenant des items
séparés soit par des virgules, soit par un ou plusieurs blancs.
Les principales options sont les suivantes :
-e
description de tous les processus.
-d
description de tous les processus, exceptés les processus pères d’un groupe de processus.
-a
identique à l’option -d, sans la description des processus associés à un terminal.
-f
génère un listing complet (voir ci-dessous).
-l
génère un listing en format long (voir ci-dessous).
-tlisterm
description uniquement des processus attachés aux terminaux spécifiés par « listerm ». Un terminal peut être identifié soit par le nom de base du fichier spécial associé (ex : tty14), soit
seulement par le numéro de la ligne si le nom de base du fichier spécial commence par « tty »
(ex : 14).
-plistproc
description uniquement des processus dont le numéro (pid) est contenu dans « listproc ».
-ulistuid
description uniquement des processus dont le numéro de propriétaire (uid) est contenu dans
« listuid ».
Avec l’option -f, ps tente pour chaque processus de donner le nom complet de la commande ainsi que ses
arguments. En cas d’échec, ps affiche entre crochets le nom de la commande tel qu’il apparaît sans l’option
-f.
Le nombre de colonnes affichées varie avec les options -f et -l. Elles sont notées entre parenthèses en face
des colonnes qu’elles font apparaître. La liste vide « () » signifie que la colonne apparaît dans tous les cas.
F
42
(l)
flag associé au processus. 0: « swappé », 1 : en mémoire, 2 : processus système, 4 : en
Petit manuel Unix 2002
DEMANDES D’ÉTATS
attente, 10 : en cours de « swapping ».
S
(l)
état du processus. 0 : non existant, S : endormi, W : en attente, R : en exécution, I :
intermédiaire, Z : terminé, T : arrêté, X : en croissance.
UID
(f,l)
numéro d’utilisateur du propriétaire. Sans l’option -f, celui-ci est remplacé par le
nom de l’utilisateur.
PID
()
numéro du processus (utile pour le tuer).
PPID
(f,l)
numéro du processus père.
C
(f,l)
utilisation du processeur.
PRI
(l)
priorité du processus; un grand nombre donne une faible priorité.
NI
(l)
lancé avec une priorité calculée.
ADDR
(l)
adresse du processus en mémoire si résident ou sur disque.
SZ
(l)
taille en blocs de l’image mémoire du processus.
WCHAN
(l)
événement pour lequel le processus attend ou est endormi.
STIME
(f)
date de création du processus.
TTY
()
numéro du terminal contrôlant le processus.
TIME
()
temps total d’exécution du processus.
COMMAND ()
le nom de la commande.
Description de ps sous BSD :
ps sans autre option liste les processus de l’utilisateur courant avec leur identifiant PID, le terminal de
contrôle TT, le temps total unité centrale utilisé TIME, l’état du processus STATE et le nom de la commande COMMAND.
L’état est donné avec 4 lettres, exemple « RWNA ».
La première lettre indique si le processus est éligible ou non :
R éligible
T processus stoppé
P en attente d’une page
D attente non interruptible
S endormi depuis moins de 20 secondes
I (idle) endormi depuis plus de 20 secondes
Z (zombie) terminé et attendant un wait du père.
La deuxième lettre indique si le processus est « swappé »
un espace signifie que le processus est chargé en mémoire.
W swappé
> le processus a précisé une limite sur ces besoins en mémoire et les a dépassé, ce processus ne peut
pas être swappé.
La troisième lettre donne des informations sur sa priorité (cf nice)
espace pour une priorité ordinaire
N la priorité du processus est réduite
Petit manuel Unix 2002
43
DEMANDES D’ÉTATS
<
la priorité du processus est augmentée
La dernière lettre donne des indications sur le remplacement des pages tel qu’il peut être spécifié par le programme :
un espace pour un traitement ordinaire
A
spécifie que le processus fait des références aléatoires sur toutes les pages, typiquement un
programme qui fait du ramasse miettes.
S
pour un programme qui utilise la mémoire virtuelle pour traiter séquentielement une grande
quantité de données.
Les principales options supplémentaires sont :
-a
description des processus possédés par un utilisateur quelconque.
-x
description des processus non associés à un terminal.
-tterm
description uniquement des processus attachés au terminal spécifiés par « term ». Un terminal doit être identifié de la même façon que ps l’affiche. Doit être la dernière option.
L’affichage peut être contrôlé par les options jlun. Avec j on a un affichage utile pour le contrôle des
tâches : PPID, PID, PGID, SID, TT, TPGID, STAT, UID, TIME et COMAND. Avec l sont affichés : F,
PPID, CP, PRI, NI, SZ, RSS et WCHAN. L’option u donne plus d’informations sur les usagers : USER,
%CPU, %MEM, SZ, RSS et START. L’option v donne des informations sur l’utilisation de la mémoire
virtuelle : RE, SL, PAGEIN, SIZE, RSS, LIM, %CPU et %MEM.
USER
nom de l’utilisateur.
%CPU
pourcentage de temps CPU utilisé (moyenne sur la dernière minute).
NI
modification de la priorité (cf nice).
SZ
44
SIZE
taille totale des segments de données et de la pile en kilo-octets.
RSS
taille mémoire physique utilisée.
LIM
limite logicielle à la taille mémoire.
%MEM
pourcentage de la mémoire physique de la machine utilisée par le processus.
RE
temps en secondes pendant lequel le processus a été résident en mémoire.
SL
temps pendant lequel le processus a été endormi.
PAGEIN
nombre d’entrées sorties disques résultant de défaut de pages.
UID
identifiant de l’utilisateur.
PPID
identifiant du processus père.
SID
identifiant du processus initiateur de la session.
PGID
identifiant du groupe de processus du processus.
TPGID
identifiant du groupe de processus associé au terminal TT.
Petit manuel Unix 2002
DEMANDES D’ÉTATS
CP
utilisation CPU à court terme utilisé pour l’ordonnancement.
PRI
priorité du processus (valeur négative en cas d’attente ininterruptible).
START
date et heure de création.
WCHAN
événement sur lequel le processus est bloqué.
F
état donné par un nombre correspondant à l’état du processus STAT.
NOM
pwd − print working directory − imprime le répertoire de travail
SYNTAXE
pwd
DESCRIPTION
pwd imprime le nom du répertoire de travail ou courant.
NOM
rusers − remote users − utilisateurs distants
SYNTAXE
rusers
DESCRIPTION
Donne le nom de login des utilisateurs connectés sur les machines du réseau local.
NOM
tty − terminal − terminal
SYNTAXE
tty
DESCRIPTION
tty donne le nom du terminal de contrôle du processus.
NOM
users − users − utilisateurs
SYNTAXE
users
DESCRIPTION
Donne le nom de login des utilisateurs connectés.
NOM
w − who and what − qui et quoi
SYNTAXE
w [utilisateur]
DESCRIPTION
w fait un résumé de l’utilisation du système. Si utilisateur est précisé, seule son activité est rapportée.
Petit manuel Unix 2002
45
DEMANDES D’ÉTATS
NOM
who − who − qui
SYNTAXE
who [am i]
whoami
DESCRIPTION
who donne pour chaque usager connecté : le nom de login, le nom de la ligne associée au terminal, la date
de connexion. whoami donne le nom de l’utilisateur connecté.
46
Petit manuel Unix 2002
DIVERS
NOM
bc − basic calculator − calculette basique
SYNTAXE
bc
DESCRIPTION
bc est une calculette interactive en précision illimitée. Elle affiche la valeur des expressions tapées en
entrée. Il est également possible de définir des fonctions, et il existe des ordres de contrôle ressemblant à
ceux du C.
Un programme bc est composé de définitions de fonctions et d’une suite d’instructions. Les expressions
sont des instructions particulières. Les expressions peuvent utiliser des noms de variables. Voici une définition plus formelle du langage :
Nom
Variables simples sur une lettre : l.
Élément de tableau : t[expr], où t est le nom du tableau et l’expr est une expression valide de bc. Les
mots obase ibase et scale qui représentent respectivement les bases de sortie, d’entrée et le nombre
de chiffres décimaux après la virgule à afficher.
Expressions
Un nom
Un nombre de longueur quelconque
( expression )
sqrt( expression )
length( expression )
scale( expression )
l( expression, expression, ...)
pour la racine carrée
pour le nombre de chiffres significatifs
pour le nombre de chiffres après la virgule
pour un appel de fonction
Opérateurs
+ - * / % ˆ
++ -== <= >= != < >
= += -= *= /= %= ˆ=
% pour le reste, ˆ pour la puissance
pré et post incrémentation
opérateurs relationnels
affectations
Instructions
l’instruction vide est une instruction
expression
{ instruction ; instruction ... }
if ( expression ) instruction
while ( expression ) instruction
for ( expression ; expression ; expression ) instruction
break
quit
Définition de fonction
define l (l, ..., l ) {
auto l, ...,l
instruction; ... instruction
return( expression )
}
le nom est sur une lettre l
définition de variables locales
NOM
cal − calendar − calendrier
SYNTAXE
cal [mois] année
Petit manuel Unix 2002
47
DIVERS
DESCRIPTION
cal imprime un calendrier de l’année donnée comprise entre 1 et 9999. Si mois est spécifié (un nombre de 1
à 12) le calendrier de ce seul mois est produit.
Ce calendrier est valable pour l’Angleterre et ses colonies.
Essayez septembre 1752.
NOM
expr − expression − expression
SYNTAXE
expr arguments
DESCRIPTION
expr écrit sur la sortie standard le résultat de l’évaluation de l’expression donnée en argument. Est surtout
utilisé dans des procédures de commandes du Bourne shell. Chacun des mots de l’expression est un argument séparé, ainsi les termes de l’expression doivent être séparés par des espaces.
Dans la liste des opérateurs qui sont donnés ensuite, les méta-caractères du shell qu’il est nécessaire de
quoter sont précédés de ’\’. Les opérateurs sont donnés par ordre de priorité croissante. Les opérateurs de
même priorité sont regroupés entre accolades {}.
expr \| expr
Retourne la première expression si elle n’est ni vide ni égale à 0, la deuxième sinon.
expr \& expr
Retourne la première expression si aucune des deux ne sont vides ou égales à 0, renvoie 0 sinon.
expr { =, \>, \>=, \<, \<=, != } expr
renvoie le résultat de la comparaison numérique si les deux expressions sont entières, lexicale
sinon.
expr { + , - }
rend la somme ou la différence des deux entiers.
expr { \*, /, % } expr
rend le produit, le quotient ou le reste de la division des deux entiers.
chaîne : expression-régulière
filtrage. Rend le nombre de caractères correspondants, 0 en cas d’échec. Une portion de la chaîne
peut être extraite en mettant une partie de l’expression régulière entre \( et \).
match chaîne expression-régulière
autre syntaxe plus explicite pour le filtrage.
substr chaîne entier1 entier2
extrait la sous chaîne de caractères commençant à la position entier1 et de longueur entier2. Ne
pas donner de valeur négative aux 2 entiers.
index chaîne liste-de-caractères
renvoie la position du premier caractère de la chaîne qui est membre de la liste de caractères.
lenght chaîne
rend la longueur de la chaîne.
( expression )
parenthésage.
expr ne traite les opérations arithmétiques que sur des entiers. Exemples :
48
a=‘expr $a + 1‘
ajoute 1 à la valeur de a.
expr $a : ’.*/\(.*\)’ \| $a
si a contient un nom de fichier, expr renvoie le nom de base du
fichier. Ne marche pas si a vaut seulement /, car expr le
Petit manuel Unix 2002
DIVERS
comprend comme un opérateur de division.
expr /$a : ’/.*/\(.*\)’
l’ajout de / supprime l’ambiguïté.
expr $VAR : ’.*’
retourne la longueur de la chaîne de caractères.
NOM
man − manuel − manuel
SYNTAXE
man [chapitre] commande
man -k mot
DESCRIPTION
man trouve et affiche la section du manuel correspondant au titre dans le chapitre donné. Le titre doit être
donné en minuscules. Si le chapitre n’est pas précisé le titre est cherché dans tous les chapitres du manuel.
Pour préciser le chapitre, deux méthodes : sous Linux c’est à la BSD et il suffit de donner un numéro, sous
Solaris c’est à la System V, il faut faire précéder le numéro de l’option -s. La variable d’environnement
MANPATH précise quels sont les répertoires dans lesquels on peut trouver des chapitres du manuel.
Avec l’option -k man affiche les noms des commandes dont le nom ou la description brève contiennent le
mot.
Le manuel unix est découpé en chapitres qui décrivent :
1−
Les commandes utilisables à partir du shell.
2−
Les appels systèmes réalisés par le noyau.
3−
Les fonctions des bibliothèques standards.
4−
Les fichiers spéciaux que l’on trouve dans /dev.
5−
Le fichiers de configuration (ex. : /etc/passwd).
6−
Les jeux.
7−
En autres choses le code ascii : ascii et iso_8859_1.
8−
Les commandes d’administration système.
9−
Sur Linux seulement, la description des fonctions internes au noyau.
Exemples, man(1)
du manuel :
$ man
$ man
$ man
décrit la commande man, alors que man(7) décrit le paquetage de macros de formatage
man
7 man
-s 7 man
NOM
test − test − tester
SYNTAXE
test expression
[ expression ]
DESCRIPTION
test évalue l’expression. Si l’expression est vraie, le code retour est zéro, sinon un code retour non nul est
retourné. L’expression vide est considérée comme fausse. La deuxième forme d’appel est équivalente à la
Petit manuel Unix 2002
49
DIVERS
première.
L’ expression est construite à partir de :
-r fichier
vrai si le fichier existe avec le droit r.
-w fichier
vrai si le fichier existe avec le droit w.
-x fichier
vrai si le fichier existe avec le droit x.
-f fichier
vrai si le fichier existe et qu’il n’est pas un répertoire.
-d fichier
vrai si fichier est un répertoire.
-s fichier
vrai si le fichier existe avec une taille non nulle.
-t [descripteur_de_fichier]
vrai si le fichier de descripteur donné (par défaut 1 : l’entrée standard) est ouvert et est
associé avec un terminal.
-z c1
vrai si la longueur de la chaîne c1 est zéro.
-n c1
vrai si la longueur de la chaîne c1 est non nulle.
c
vrai si c n’est pas la chaîne nulle.
c1 = c2
vrai si les chaînes sont égales.
c1 != c2
vrai si les chaînes sont différentes.
n1 -eq n2
vrai si les entiers sont égaux. -ne, -gt, -ge, -lt ou -le peuvent être utilisé à la place de -eq
pour tester respectivement la non égalité, >, >=, < ou <=.
Ces termes primaires peuvent être combinés avec les opérateurs suivants :
!
négation unaire
-a
et logique
-o
ou logique
( expr )
regroupement; les parenthèses ayant une signification spéciale pour shell doivent être
précédées de « \ ».
Note : -a a une plus grande priorité que -o.
50
Petit manuel Unix 2002
COMMUNICATION ENTRE USAGERS
NOM
mail − mail − courrier
SYNTAXE
mail adresse-email
mail
DESCRIPTION
mail permet d’échanger du courrier entre les utilisateurs.
Dans la première forme d’appel, mail dépose dans la boîte à lettres de ou des utilisateurs une copie de
l’entrée standard jusqu’à une ligne constituée uniquement d’un point ou du caractère fin de fichier (ˆD).
L’adresse e-mail est de la forme alias@domaine ; la vôtre est :
n°[email protected]
Vous avez la possibilité de créer des alias du style :
[email protected]
Vos enseignants ont des comptes dans le domaine unicaen.fr et, par exemple, mon adresse officielle est :
[email protected]
La deuxième forme d’appel permet la lecture du courrier reçu dans la boîte à lettres locale à la machine.
Ces boîtes locales ne sont maintenant utilisées que pour les comptes administrateurs locaux aux machines.
Si la boîte à lettres est vide, vous sortez automatiquement de mail. Si elle contient des messages, mail
affiche leur nombre et le nombre d’entre eux que vous n’avez jamais lu. Le message courant est alors le
dernier message lu.
Après avoir lu un message, vous pouvez le détruire (d). Ceci n’est pas irréversible; le message peut être
rappelé (u) par son numéro, ou la session peut être annulée (x). Vous pouvez répondre à un message (r
ou R), le faire suivre (f). Vous pouvez terminer une session en mettant à jour votre boîte à lettres (q)
ou non (x). En cas de mise à jour, les destructions de messages deviendront effectives (vous ne pourrez
plus les récupérer).
Notez qu’au département, comme vos boîtes à lettres ne sont pas directement accessible sur les stations,
vous ne pourrez jamais les lire avec la simple commande mail. Vous pouvez le lire par l’interface web ou à
l’aide de programmes clients dont les principaux sont : thunderbird, claws-mail, kmail, ou enfin avec les
modes RMAIL ou vm sous emacs.
NOM
mesg − message − message
SYNTAXE
mesg [n] [y]
DESCRIPTION
mesg permet de protéger son terminal en écriture (option n) ou non (option y). Ceci permet de suspendre
ou non la réception de messages interactifs (cf write).
NOM
talk − talk − parler
SYNTAXE
talk usager
DESCRIPTION
talk permet de mener une discussion interactive par écrit (et non pas par oral) avec l’usager. Ce dernier peut
être connecté sur une machine distante, et dans ce cas, il faut préciser le nom de la machine :
usager@machine.
Petit manuel Unix 2002
51
COMMUNICATION ENTRE USAGERS
NOM
write − write − écrire
SYNTAXE
write usager [terminal]
DESCRIPTION
write recopie les lignes entrées sur votre terminal sur le terminal de l’usager spécifié. L’usager ne doit pas
avoir protégé son terminal en écriture à l’aide de la commande : mesg n
52
Petit manuel Unix 2002
OUTILS RÉSEAUX
NOM
ftp − file transfer program − programme de transfert de fichier
SYNTAXE
ftp machine
DESCRIPTION
Ce programme permet de transférer des fichiers sur le réseau entre deux machines. Les principales commandes sont :
cd répertoire
pwd
dir
put nom-local [ nom-distant ]
get nom-distant [ nom-local ]
On peut préférer utiliser un programme avec interface graphique et menus déroulants comme ftptool ou un
navigateur Web en précisant comme URL : ftp://[login@]machine.
NOM
sftp − secure file transfer program − programme de transfert sécurisé de fichier
SYNTAXE
ftp machine
DESCRIPTION
Ce programme de transfert de fichier a une interface identique à ftp mais utilise un canal ssh pour le transport. Est utilisé par sshfs.
NOM
web-browsers −
− navigateurs web
SYNTAXE
lynx
mosaic
firefox
konqueror
opera
DESCRIPTION
Ces navigateurs permettent de surfer sur les vagues binaires de l’internet. lynx permet de fonctionner sans
mode graphique. mosaic est cité simplement à titre historique.
Vous avez la possibilité de créer votre page personnelle qui sera accessible par l’URL :
http://votre_login.perso.info.unicaen.fr/
Les directives pour activer votre site sont accessibles à l’adresse :
https://perso.info.unicaen.fr/
Petit manuel Unix 2002
53
MESURES ET SURVEILLANCE DE SYSTÈME
NOM
arch − architecture − architecture
SYNTAXE
arch
DESCRIPTION
arch affiche le nom de l’architecture de la machine courante. Sous Linux, cette commande est équivalente à
uname -m et affiche en fait le type du processeur : « i386 », « i686 », « sparc », ...
NOM
free − free memory − mémoire libre
SYNTAXE
free [-t] [-s délai]
DESCRIPTION
free affiche la mémoire centrale et d’échange (swap) libre et utilisée. L’option -t ajoute une ligne donnant
le total de la mémoire virtuelle. L’option -s active un affichage périodique tous les délais secondes à la
manière de vmstat.
NOM
fuser - file or socket used - fichiers utilisés
SYNTAXE
fuser nom [-v] [-c] [-m] [-k [-i] [-signal] ]
DESCRIPTION
fuser liste les processus qui utilise une ressource ficher ou réseau (socket) donnée. Une ressource réseau est
précisée en indiquant l’espace de nom upd ou tcp avec un slash après le numéro de port local seul ou de la
machine distante et d’un numéro de port. Ces champs sont optionnels mais pas les virgules les séparant ce
qui est résumé par : [port_local][,[machine_distante][,[port_distant]]]
Le numéro de port peut être donné par un nom de protocole connu dans /etc/services. Exemples :
35029/tcp ssh/tcp ,www,80/tcp
Le type d’accès est indiqué par une lettre :
c
répertoire courant
e
exécutable chargé
f
fichier ouvert
F
fichier ouvert en écriture
r
répertoire racine
m
fichier mappé en mémoire ou bibliothèque partagée
Avec -k, un signal est envoyé à chaque processus. Par défaut SIGKILL est envoyé, on peut le changer en le
précisant, soit en nombre, soit par le mnémonique (ex.: -1 ou -HUP). L’option -i demande confirmation
avant d’envoyer le signal à chaque processus.
Les options équivalentes -c ou -m permettent de lister les processus utilisant un quelconque fichier d’un
système de fichier monté désigné par un de ces fichiers.
L’option -v liste les processus comme la commande ps.
54
Petit manuel Unix 2002
MESURES ET SURVEILLANCE DE SYSTÈME
NOM
host − host − hôte
SYNTAXE
host [options] nom
DESCRIPTION
host permet d’interroger le service de noms de domaines (Domain Name Service). Par défaut, il donne la
correspondance entre noms et numéro Internet. L’option -v ajoute les informations sur les durées de vie
(ttl) des données, ainsi que sur les noms de serveurs qui ont autorités pour ces noms. L’option -a va lister
toutes les données définies pour ce nom (utile pour un nom de domaine). Enfin essayer la ligne suivante
pour avoir un résumé et une validation d’une zone entière : host -G -S -C -A -L 1 zone.
NOM
lsof − list open files − liste des fichiers ouverts
SYNTAXE
lsof
DESCRIPTION
lofs affiche les fichiers ouverts de chaque processus sous forme d’un tableau de 9 colonnes :
COMMAND
pour le nom de la commande.
PID
pour le numéro du processus.
USER
pour le login de l’utilisateur.
FD
indique le numéro descripteur de fichier ouvert suivi de r, w ou u suivant qu’il est ouvert en
lecture, écriture ou les deux et éventuellement d’un caractère indiquant le type de verrou
(lock) appliqué au fichier. Sinon, il est indiqué : cwd pour le répertoire courant, ltx pour
une bibliothèque partagée (library text), mem pour un fichier « mappé » en mémoire, txt
pour un fichier programme (segment texte).
TYPE
pour le type, ex. : REG pour un fichier ordinaire, DIR pour un répertoire, PIPE pour un
pipe, BLK pour un fichier spécial block, CHR pour un fichier spécial charactère, inet
pour une socket internet, unix pour une socket Unix.
DEVICE
pour les numéros de périphérique contenant le fichier.
SIZE
donne la taille en octets.
NODE
donne le numéro de i-node.
NAME
donne le nom complet dans la hiérarchier du système de fichiers.
NOM
netstat − net statistics − statistiques réseau
SYNTAXE
netstat [-irgM] [-vnp]
DESCRIPTION
netstat sans argument liste toutes les connexions établies sur des sockets du domaine IP ou Unix. Avec
l’argument -a, mêmes les sockets sans connexions sont listées. Avec les arguments :
-r
affiche la table de routage comme route.
-g
affiche les appartenances des interfaces aux groupes multicast.
-i
liste les interfaces à la manière de ifconfig.
-M liste toutes les sessions.
Les options de contrôle v n p permettent respectivement d’être plus bavard (verbeux), de n’afficher que les
numéros des machines et de ne pas faire la résolution de noms DNS et enfin d’afficher les numéros de
Petit manuel Unix 2002
55
MESURES ET SURVEILLANCE DE SYSTÈME
processus ayant établi les connexions.
NOM
perfmeter − performance meter − mesure de performance
SYNTAXE
perfmeter
DESCRIPTION
C’est un outil graphique d’affichage de plusieurs mesures d’utilisation de la machine locale ou d’une
machine distante. Cette commande est spécifique à Solaris. Des applettes équivalentes sont disponibles
dans tous les environnements de bureau graphique, mais ne permettent pas de monitorer une machine distante.
NOM
rup − remote time up − temps de marche distant
SYNTAXE
rup [machines]
DESCRIPTION
Idem à uptime, mais pour toutes les machines du réseau local.
NOM
top − top − dessus
SYNTAXE
top
DESCRIPTION
top affiche et rafraîchit toutes les secondes diverses statistiques d’utilisation du système et les processus les
plus gourmands. Est disponible sur Linux.
NOM
uname − name of current system − nom du système
SYNTAXE
uname [-snrvma]
DESCRIPTION
uname affiche des informations concernant la machine et le système d’exploitation sur lequel il est
invoqué. Les options :
-s --sysname
affiche le nom du système d’exploitation (ex. : Linux, SunOS).
-n --nodename
affiche le nom de l’hôte, comme hostname.
-r --release
affiche le numéro de version du système d’exploitation.
-v
affiche la version du système d’exploitation (celui de la commande est affiché par --version).
-m --machine
affiche le type du processeur (comme arch).
-a --all
affiche toutes les informations précédentes. Ex. :
Linux london 2.4.9-3-dep #3 ven aoû 24 20:45:31 CEST 2001 i686 unknown
56
Petit manuel Unix 2002
MESURES ET SURVEILLANCE DE SYSTÈME
NOM
uptime − time up − temps de marche
SYNTAXE
uptime
DESCRIPTION
Donne l’heure, le temps écoulé depuis le démarrage du système, le nombre d’utilisateurs, et la charge
(« load ») exprimée comme le nombre moyen de processus actifs dans la dernière minute, les 5 dernières
minutes et les 15 dernières minutes.
NOM
vmstat − virtual memory statistics − statistique de la mémoire virtuelle
SYNTAXE
vmstat délai nombre_de_fois
DESCRIPTION
vmstat affiche des statistiques d’utilisation de la machine un certain nombre de fois et tous les délais secondes.
Petit manuel Unix 2002
57
ÉDITEURS DE TEXTES
NOM
emacs - emacs - emacs
SYNTAXE
emacs [ fichier ]
DESCRIPTION
est l’éditeur plein écran le plus complet du marché. Il est disponible sur la quasi totalité des systèmes
d’exploitation. Il ne différencie pas mode de commande ou mode d’insertion, en fait tout caractère est une
commande et l’action associée à un caractère imprimable est d’insérer ce caractère dans le tampon courant.
Les commandes sont les caractères de contrôle ou une séquence escape [<esc>,caractère] ; les premiers
sont notés ˆX ou C-X, les séquences escape sont notées M-X, car on peut les obtenir en enfonçant simultanément la touche Méta (parfois Alt avec certains claviers) et le caractère. Attention les touches contrôle et
méta sont des modificateurs qu’il faut enfoncer simultanément avec une autre touche (comme pour les
majuscules), alors que <esc> est un caractère ASCII.
emacs possède des modes lui permettant, en particulier, de faire de la coloration syntaxique en fonction du
langage édité, et ceci de façon automatique (s’il est bien configuré :-).
emacs peut gérer plusieurs tampons (buffer) qui contiennent des images de fichiers et il vous demandera
d’enregistrer les modifications si ce n’est pas fait lorsque vous le quitterez. Une copie de l’ancienne version
du fichier est toujours créée avec comme nom le nom du fichier plus un tilde (˜). En cours de travail, emacs
sauvegarde périodiquement l’état courant du tampon dans un fichier de nom le nom du fichier original
encadré de dièses (#).
emacs peut afficher le contenu des tampons dans différentes fenêtres d’un ou plusieurs cadres (frame).
Les fichiers et les tampons
Séquence
Menu
Commande
Action
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
Files->Open File
find-file
find-alternate-file
insert-file
save-buffer
write-filed
save-buffers-kill-emacs
switch-to-buffer
list-buffers
charge un fichier
remplace un fichier
insère un fichier sous le curseur
enregistre le fichier
enregistre sous ...
sort d’Emacs
affiche le buffer choisi
affiche la liste des tampons
C-f
C-v
i
C-s
C-w
C-c
b
C-b
Files->Insert File
Files->Save Buffer
Files->Save Buffer As
Files->Exit Emacs
Buffers->tampon
Buffers->list All Buffers
Déplacement, édition, suppression, régions et recouvrement
58
Séquence
Commande
Action
C-a
C-b
C-e
C-f
C-n
C-o
C-p
C-t
C-v
beginning-of-line
backward-char
end-of-line
forward-char
next-line
open-line
previous-line
transpose-chars
scroll-up
début de la ligne
caractère précédent
fin de ligne
caractère suivant
ligne suivante
ouvre la ligne
ligne précédente
échange deux caractères
défilement vers le haut
C-d ou Suppr
M-d
M-DEL
C-k
delete-char
kill-word
backward-kill-word
kill-line
suppr. du car. sous le curseur
suppr. du mot suivant
suppr. du mot précédent
suppr. du reste de la ligne
Petit manuel Unix 2002
ÉDITEURS DE TEXTES
C-w
M-w
C-y
C-@ ou C-espace
C-
kill-region
kill-ring-save
yank
set-mark-command
undo
suppr. de la région marquée
copie la région
Recopie la dernière suppression
Marque la fin ou le début d’une région
annuler
Recherche et substitution
Séquence
Suppression
C-s
C-r
RETURN
C-g
DEL
C-s RETURN
C-r RETURN
Mespace ou y
DEL ou n
,
!
Lance une recherche incrémentale
Recherche incrémentale arrière
Sortie de la recherche en cours
Annule la recherche en cours
Efface un caractère de la chaîne de recherche
Recherche non incrémentale
Recherche arrière non incrémentale
Substitution interactive
Affectue la substitution et reprend la recherche
N’effectue pas la substitution et reprend la recherche
Effectue la substitue et montre le résultat
Effectue toutes les substitutions sans rien demander
Revient à la dernière substitution
Termine la fonction
RETURN
Les fenêtres et les cadres
Séquence
Suppression
C-x 2
C-x o
C-x 0
C-x 1
C-x
M-C-v
C-x 4 f
Découpe la fenêtre en deux
Passe à la fenêtre suivante
Supprime la fenêtre courante
Supprime toutes les fenêtres sauf la courante
Augmente la hauteur
Fait défiler la fenêtre suivante
Ouvre un fichier dans la fenêtre suivante.
C-x
C-x
C-x
C-x
C-x
Active le cadre suivant
Supprime le cadre courant
Crée un nouveau cadre contenant le tampon courant
Créé un nouveau cadre avec un nouveau fichier
Créé un nouveau cadre contenant un autre tampon
5
5
5
5
5
o
0
2
C-f
b
La souris
Séquence
Commande
Action
C-down-mouse-3
S-down-mouse-1
C-down-mouse-1
mouse-3
mouse-2
mouse-1
double-mouse-1
triple-mouse-1
mouse-major-mode-menu
mouse-set-font
mouse-buffer-menu
mouse-save-then-kill
mouse-yank-at-click
mouse-set-point
mouse-set-point
mouse-set-point
menu du mode majeur
choix de la fonte
menu tampon
copie et efface
colle
place le curseur
sélectionne le mot
sélectionne la ligne
Petit manuel Unix 2002
59
ÉDITEURS DE TEXTES
Toutes les commandes (Emacs Wall Chart)
Clé
Commande
Clé
Commande
C-@
C-a
C-b
C-d
C-e
C-f
C-g
C-h
TAB
C-k
C-l
RET
C-n
C-o
C-p
set-mark-command
beginning-of-line
backward-char
delete-char
end-of-line
forward-char
keyboard-quit
help-command
indent-for-tab-command
kill-line
hilit-recenter
newline
next-line
open-line
previous-line
C-r
C-s
C-t
C-u
C-v
C-w
C-x
C-y
C-z
ESC
C-\
C-]
C-_
DEL
isearch-backward
isearch-forward
transpose-chars
universal-argument
scroll-up
kill-region
Control-X-prefix
hilit-yank
shell
ESC-prefix
toggle-input-method
abort-recursive-edit
undo
delete-backward-char
view-hello-file
describe-coding-system
describe-input-method
describe-input-method
describe-language-environment
describe-language-environment
help-quit
describe-variable
where-is
help-with-tutorial
describe-syntax
finder-by-keyword
view-emacs-news
view-emacs-news
describe-mode
view-lossage
info-lookup-symbol
Info-goto-emacs-key-command-node
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-f
4
i
F
f
d
k
c
b
a
C-p
C-w
C-d
C-c
?
f1
help
C-h
Info-goto-emacs-command-node
Prefix Command
info
view-emacs-FAQ
describe-function
describe-funct
describe-key
describe-key-briefly
describe-bindings
apropos-command
describe-project
describe-no-warranty
describe-distribution
describe-copying
help-for-help
help-for-help
help-for-help
help-for-help
set-language-environment
universal-coding-system-argument
set-input-method
set-next-selection-coding-system
set-selection-coding-system
C-x
C-x
C-x
C-x
RET
RET
RET
RET
set-buffer-process-coding-system
set-keyboard-coding-system
set-terminal-coding-system
set-buffer-file-coding-system
hilit-repaint-command
delete-char
mouse-major-mode-menu
mouse-set-font
mouse-buffer-menu
mouse-save-then-kill
mouse-yank-at-click
mouse-set-point
deletechar
deleteline
S-insert
C-insert
insert
M-begin
begin
M-end
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
C-h
h
C
I
C-\
L
C-l
q
v
w
t
s
p
n
C-n
m
l
TAB
C-k
C-x
C-x
C-x
C-x
C-x
RET
RET
RET
RET
RET
l
c
C-\
X
x
S-C-l
delete
C-down-mouse-3
S-down-mouse-1
C-down-mouse-1
mouse-3
mouse-2
triple-mouse-1
60
p
k
t
f
delete-char
kill-line
hilit-yank
kill-ring-save
overwrite-mode
beginning-of-buffer-other-window
beginning-of-buffer
end-of-buffer-other-window
Petit manuel Unix 2002
ÉDITEURS DE TEXTES
double-mouse-1
drag-mouse-1
mouse-1
down-mouse-1
M-mouse-2
M-mouse-3
M-down-mouse-1
M-drag-mouse-1
M-mouse-1
C-down-mouse-2
S-delete
C-delete
C-left
C-right
M-left
M-right
mouse-movement
mouse-set-point
mouse-set-region
mouse-set-point
mouse-drag-region
mouse-yank-secondary
mouse-secondary-save-then-kill
mouse-drag-secondary
mouse-set-secondary
mouse-start-secondary
facemenu-menu
kill-region
backward-kill-word
backward-word
forward-word
backward-word
forward-word
ignore
end
M-prior
M-next
C-next
C-prior
C-down
C-up
next
prior
down
right
up
left
M-home
home
C-SPC
C-/ C-_
end-of-buffer
scroll-other-window-down
scroll-other-window
scroll-left
scroll-right
forward-paragraph
backward-paragraph
scroll-up
scroll-down
next-line
forward-char
previous-line
backward-char
beginning-of-buffer-other-window
beginning-of-buffer
set-mark-command
undo
C-x
C-x
C-x
C-x
C-x
4
4
4
4
4
0
.
d
a
C-o
kill-buffer-and-window
find-tag-other-window
dired-other-window
add-change-log-entry-other-window
display-buffer
C-x
C-x
C-x
C-x
C-x
4
4
4
4
4
b
C-f
r
f
m
switch-to-buffer-other-window
find-file-other-window
find-file-read-only-other-window
find-file-other-window
compose-mail-other-window
C-x
C-x
C-x
C-x
C-x
5
5
5
5
5
o
0
2
.
d
other-frame
delete-frame
make-frame-command
find-tag-other-frame
dired-other-frame
C-x
C-x
C-x
C-x
C-x
5
5
5
5
5
r
C-f
f
b
m
find-file-read-only-other-frame
find-file-other-frame
find-file-other-frame
switch-to-buffer-other-frame
compose-mail-other-frame
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-b
C-c
C-d
C-e
C-f
TAB
C-k
C-l
C-n
C-o
C-p
C-q
C-r
C-s
C-t
C-u
C-v
C-w
C-x
C-z
ESC
$
’
list-buffers
save-buffers-kill-emacs
list-directory
eval-last-sexp
find-file
indent-rigidly
edit-kbd-macro
downcase-region
set-goal-column
delete-blank-lines
mark-page
vc-toggle-read-only
find-file-read-only
save-buffer
transpose-lines
upcase-region
find-alternate-file
write-file
exchange-point-and-mark
iconify-or-deiconify-frame
Prefix Command
set-selective-display
expand-abbrev
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
6
8
;
<
=
>
[
]
ˆ
‘
a
b
d
e
f
g
h
i
j
k
l
m
n
Petit manuel Unix 2002
2C-command
8859-1-map
set-comment-column
scroll-left
what-cursor-position
scroll-right
backward-page
forward-page
enlarge-window
next-error
Prefix Command
switch-to-buffer
dired
call-last-kbd-macro
set-fill-column
insert-register-compatibility-binding
mark-whole-buffer
insert-file
jump-to-register-compatibility-binding
kill-this-buffer
count-lines-page
compose-mail
Prefix Command
61
ÉDITEURS DE TEXTES
62
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
(
)
+
.
/
0
1
2
3
4
5
start-kbd-macro
end-kbd-macro
balance-windows
shrink-window-if-larger-than-buffer
set-fill-prefix
point-to-register-compatibility-binding
delete-window
delete-other-windows
split-window-vertically
split-window-horizontally
ctl-x-4-prefix
ctl-x-5-prefix
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
o
q
r
s
u
v
x
z
{
}
DEL
C-SPC
other-window
kbd-macro-query
Prefix Command
save-some-buffers
advertised-undo
Prefix Command
copy-to-register-compatibility-binding
repeat
shrink-window-horizontally
enlarge-window-horizontally
backward-kill-sentence
pop-global-mark
C-x
C-x
C-x
C-x
C-x
a
a
a
a
a
expand-jump-to-next-slot
expand-jump-to-previous-slot
expand-abbrev
expand-abbrev
inverse-add-global-abbrev
C-x
C-x
C-x
C-x
C-x
a
a
a
a
a
Prefix Command
add-mode-abbrev
add-global-abbrev
add-mode-abbrev
add-mode-abbrev
C-x n p
C-x n d
narrow-to-page
narrow-to-defun
C-x n w
C-x n n
widen
narrow-to-region
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
mark-sexp
beginning-of-defun
backward-sexp
exit-recursive-edit
down-list
end-of-defun
forward-sexp
mark-defun
complete-symbol
indent-new-comment-line
kill-sexp
reposition-window
forward-list
split-line
backward-list
fill-region
isearch-backward-regexp
isearch-forward-regexp
transpose-sexps
backward-up-list
scroll-other-window
append-next-kill
Prefix Command
indent-region
just-one-space
shell-command
calc-dispatch
ispell-word
query-replace
abbrev-prefix-mark
backward-list
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
beginning-of-buffer
count-lines-region
end-of-buffer
mark-word
delete-horizontal-space
delete-indentation
tmm-menubar
backward-sentence
backward-word
capitalize-word
kill-word
forward-sentence
forward-word
goto-line
mark-paragraph
tab-to-tab-stop
indent-new-comment-line
kill-sentence
downcase-word
compile
fill-paragraph
move-to-window-line
transpose-words
upcase-word
scroll-down
kill-ring-save
execute-extended-command
hilit-yank-pop
zap-to-char
shrink-window
shell-command-on-region
n
p
’
e
-
C-@
C-a
C-b
C-c
C-d
C-e
C-f
C-h
TAB
C-j
C-k
C-l
C-n
C-o
C-p
C-q
C-r
C-s
C-t
C-u
C-v
C-w
ESC
C-\
SPC
!
#
$
%
’
(
<
=
>
@
ˆ
‘
a
b
c
d
e
f
g
h
i
j
k
l
m
q
r
t
u
v
w
x
y
z
{
|
i
+
g
C-a
l
Petit manuel Unix 2002
ÉDITEURS DE TEXTES
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
)
*
,
.
/
0 .. ESC 9
:
;
forward-list
pop-tag-mark
tags-loop-continue
negative-argument
find-tag
dabbrev-expand
digit-argument
eval-expression
indent-for-comment
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
ESC
}
˜
DEL
C-%
C-.
C-/
S-C-v
C-SPC
C--
enlarge-window
not-modified
backward-kill-word
query-replace-regexp
find-tag-regexp
dabbrev-completion
scroll-other-window-down
mark-sexp
negative-argument
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
r
r
r
r
r
r
r
r
r
r
r
r
r
r
r
r
r
r
r
r
r
r
bookmark-bmenu-list
bookmark-set
bookmark-jump
frame-configuration-to-register
window-configuration-to-register
string-rectangle
open-rectangle
yank-rectangle
delete-rectangle
kill-rectangle
clear-rectangle
increment-register
number-to-register
copy-rectangle-to-register
insert-register
insert-register
copy-to-register
copy-to-register
jump-to-register
point-to-register
point-to-register
point-to-register
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
C-x
v
v
v
v
v
v
v
v
v
v
v
v
v
v
vc-version-other-window
vc-diff
vc-next-action
vc-revert-buffer
vc-create-snapshot
vc-retrieve-snapshot
vc-merge
vc-print-log
vc-register
vc-insert-headers
vc-annotate
vc-directory
vc-cancel-version
vc-update-change-log
l
m
b
f
w
t
o
y
d
k
c
+
n
r
g
i
x
s
j
SPC
C-SPC
C-@
˜
=
v
u
s
r
m
l
i
h
g
d
c
a
Si vous êtres fatigués essayer les commandes M-Xhanoi<cr> ou M-Xdoctor<cr>. Pour finir, voici
deux significations possibles d’emacs comme acronyme :
Escape-Meta-Alt-Control-Shift
Emacs Makes All Computing Simple
NOM
nano - Nano’s ANOther editor - NAno un NOuvel éditeur
SYNTAXE
nano [ fichier ]
DESCRIPTION
nano est un petit éditeur plein écran qui peut fonctionner avec des modes d’éditions (comme vi) ou sans
(comme emacs). Il est hautement configurable et n’a pas besoin de X11. La configuration par défaut donne
des commandes qui le font ressembler à un petit emacs. Voici la liste des commandes dans laquelle ˆX signifie Contrôle-X ou C-X :
Message d’aide de nano
L’éditeur nano est conçu pour reproduire les fonctions et la facilité d’utilisation de l’éditeur Pico de l’Université de Washington. Il comporte quatre sections principales : la ligne du haut affiche la version du programme, le fichier actuellement en cours d’édition et s’il a été modifié ou non. En dessous se trouve la
fenêtre principale d’édition qui affiche le fichier en cours de modification. La ligne d’état est la troisième
Petit manuel Unix 2002
63
ÉDITEURS DE TEXTES
ligne en partant du bas, elle affiche les messages importants. Les deux dernières lignes affichent les raccourcis les plus couramment utilisés.
Dans les raccourcis présentés C-x désigne « Contrôle x » qui peut être entrée en enfonçant en même temps
la touche Contrôle (Ctrl) et la touche de la lettre. nano admet de rentrer ces raccourcis en pressant successivement 2 fois la touche « Échap. ». Les séquences d’échappement sont représentées par le symbole
« Méta » (M) et peuvent être entrées via les touches « Échap. », « Alt. » ou « Méta » selon la configuration
de votre clavier. Appuyer 2 fois sur la touche « Échap. » puis entrer un nombre à 3 chiffres entre 000 et 255
insère le caractère de code correspondant. Les combinaisons suivantes sont disponibles dans la fenêtre principale de l’éditeur. Les combinaisons pouvant être utilisées comme alternatives sont affichées entre parenthèses :
C-G
C-X
C-O
C-J
(F1)
(F2)
(F3)
(F4)
Affiche de message
Fermer l’espace en cours / Quitter nano
Écrire le fichier en cours sur le disque
Justifier le paragraphe courant
C-R
C-W
C-Y
C-V
(F5)
(F6)
(F7)
(F8)
Insérer un autre fichier dans l’espace en cours
Recherche d’une chaîne ou d’une expression rationnelle
Aller à l’écran précédent
Aller à l’écran suivant
C-K
C-U
C-C
C-T
(F9)
(F10)
(F11)
(F12)
Couper la ligne courante vers le presse-papiers
Coller le presse-papiers à partir de la ligne courante
Indiquer la position du curseur
Appeler le correcteur orthographique (si dispo.)
C-_
CC-ˆ
(F13)
(F14)
(F15)
(F16)
M-ˆ
M-}
M-{
64
(M-G)
(M-R)
(M-A)
(M-W)
Aller à la ligne et à la colonne indiquées
Remplacer une chaîne ou une expression rationnelle
Marquer le texte à la position du curseur
Recommencer la dernière recherche
(M-6)
Copier la ligne courante dans le presse-papiers
Mise en retrait de la ligne courante
Annuler le retrait de la ligne courante
C-F
C-B
C-blanc
M-blanc
C-P
C-N
Avancer d’un caractère
Reculer d’un caractère
Avancer d’un mot
Reculer d’un mot
Aller à la ligne précédente
Aller à la ligne suivante
C-A
C-E
M-(
M-)
MM-/
(M-9)
(M-0)
(M-|)
(M-?)
Aller au début de la ligne courante
Aller à la fin de la ligne courante
Aller au début du paragraphe
Aller à la fin du paragraphe
Aller à la première ligne du fichier
Aller à la dernière ligne du fichier
M-]
M--
(M-_)
Aller au crochet correspondant
Remonter d’une ligne sans déplacer le curseur
Petit manuel Unix 2002
ÉDITEURS DE TEXTES
M-+
(M-=)
Descendre d’une ligne sans déplacer le curseur
M-<
M->
(M-,)
(M-.)
Basculer vers l’espace précédent
Basculer vers l’espace suivant
M-V
C-I
C-M
C-D
C-H
M-T
Insérer le prochain caractère tel quel
Insérer une tabulation à la position du curseur
Insérer un passage à la ligne à la position du curseur
Supprimer le caractère sous le curseur
Supprimer le caractère à la gauche du curseur
Coupe du curseur à la fin du fichier
M-J
M-D
C-L
Justifier le fichier entier
Compter le nombre de mots, de lignes et de caractères
Rafraîchir (redessiner) l’écran courant
M-X
M-C
M-O
M-S
M-P
M-Y
Mode aide (commutateur)
Afficher la position du curseur (commutateur)
Utiliser 1 ligne de plus pour l’édition (commutateur)
Défilement progressif (commutateur)
Afficher les blancs (commutateur)
Colorisation syntaxique (commutateur)
M-H
M-I
M-K
M-L
M-Q
Touche « Début » intelligente (commutateur)
Indenter automatiquement (commutateur)
Couper jusqu’en fin de ligne (commutateur)
Passer à la ligne automatiquement (commutateur)
La touche tabulation ajoute des espaces (commutateur)
M-B
M-F
M-M
M-N
M-Z
Conserver des copies de sécurité (commutateur)
Mode multi-espace (commutateur)
Utiliser la souris (commutateur)
Pas de conversion des formats DOS et Mac (commutateur)
Autoriser à suspendre (commutateur)
NOM
vi - visual editor - éditeur visuel
SYNTAXE
vi [ fichier ]
DESCRIPTION
vi est l’éditeur plein écran traditionnel d’Unix. Son grand avantage est que l’on peut utiliser toutes les commandes de ed(1) en les préfixant par :. Son grand inconvénient est de travailler par modes (mode commande/mode insertion) ce qui est relativement insupportable pour un utilisateur d’emacs. Je ne vais donc
vous donnez ici que la façon de sortir de vi, ce qui est la seule chose raisonnable à faire si on y est entré par
inadvertance :
1- sortir éventuellement du mode d’insertion en tapant : <esc>
2- sortir de l’éditeur sans enregistrer les modifications avec la séquence de 4 caractères :
:q!<retour-chariot>
Petit manuel Unix 2002
65
COMPOSEURS DE TEXTES
NOM
groff - groff - groff
SYNTAXE
groff [-Tascii] [-Thtml] [-mxx] fichiers
DESCRIPTION
groff est la version GNU du composeur de texte troff qui est utilisé pour formatter le manuel Unix. Il a été
bien sûr utiliser pour ce petit manuel. Il permet de réaliser une sortie en PostScript comme celle que vous
lisez et également une sortie en ascii si on précise -Tascii (ce que LaTeΧ ne sait pas bien faire), ou en
HTML avec -Thtml.
Il existe trois grands paquetages de macros pour troff et groff : ms, me et man. Nous ne décrirons ici que le
paquetage man.
Lignes de texte et requêtes de formatage.
Le texte peut être entré ‘au kilomètre’, la mise en page de l’éditeur étant complètement ignorée.
Cependant si une ligne commence par un espace ou est vide, la ligne précédente ne sera pas justifiée et
la ligne suivante ne sera pas collée à la précédente (comme pour cette ligne).
Le paragraphe précédent a été saisi ainsi:
Le texte peut être entré ‘au kilomètre’,
la mise en page de l’éditeur étant complètement ignorée.
Cependant si une ligne commence par un espace ou est vide,
la ligne précédente ne sera pas justifiée et
la ligne suivante ne sera pas collée à la précédente (comme pour cette
ligne).
En fait, le source de groff est composé de deux sortes de lignes:
− les lignes de texte,
− les lignes de commandes de formattages qui commencent par un point.
Ces commandes prennent ou non des arguments que l’on peut regrouper entre des guillemets (double
quote).
Commandes de base que l’on peut utiliser avec man.
.bp
Commence une nouvelle page.
.br
Force le passage à la ligne.
.ce n
Centre les n lignes suivantes.
.sp n
Insère n lignes blanches.
.ta i1 i2 . . .
Définit les nouveaux taquets de tabulation qui sont utilisés pour interpréter le caractère de tabulation (ascii 9 ou 011).
.ul n
souligne les n lignes suivantes.
.nf
Commande l’arrêt du remplissage (no fill) ; les fins de lignes sont conservées en sortie.
.fi
Commande le mode normal de remplissage dans lequel les fins de ligne du source ne sont pas conservées.
On peut également mettre dans le texte la commande \fx, avec x valant R, I, H, S, C et P pour respectivement : Roman, Italique, Helvetica, Courrier et la fonte précédente. Ex. : \fR Roman, \fI
Italique \fR, \fH Helvetica \fR, \fC Courrier\fR va donner
Roman, Italique , Helvetica , Courrier.
Pour afficher un anti-slash, on devra le doubler : \\ (je l’ai bien sûr quadruplé afin qu’il apparraisse deux
fois !-). Pour afficher un point en début de ligne, il suffit de le faire précéder de \& qui est une commande
nulle. Il existe également \| et \0 qui produisent un demi espace ou un espace mais qui empêchent des
66
Petit manuel Unix 2002
COMPOSEURS DE TEXTES
césures intempestives (par exemple, il est prudent d’employer \| avant deux points :).
Titres et sections.
Une page de manuel doit toujours commencer par la commande :
.TH titre section date source manuel
Exemple :
.TH MAN 7 "25 July 1993" "Linux" "Linux Programmer’s Manual"
Ensuite, on met les sections dont les entêtes sont définies par la commande .SH (pour section heading). Elle
ne prend qu’un argument, donc, si le titre contient un espace il faut regrouper les mots entre des guillemets.
Les sections possibles sont traditionnellement : NAME, SYNOPSIS, DESCRIPTION, OPTIONS, FILES,
SEE ALSO, DIAGNOSTICS, BUGS et AUTHOR.
On peut commencer un nouveau paragraphe avec .PP sans argument.
Commandes de sélection de fontes.
.B
Gras
.BI
Gras alternant avec italiques
.BR Gras alternant avec Roman
.I
Italiques
.IB
Italiques alternant avec gras
.IR
Italiques alternant avec Roman
.RB Roman alternant avec gras
.RI
Roman alternant avec italiques
.SB
Petit alternant avec gras
.SM Petit
Autres commandes.
Les commandes suivantes peuvent prendre un argument numérique (i), ou un texte (t). Le nombre peut être
suivi de l’unité : i, c, n, m, p, u pour respectivement : inch, centimètre, la largeur d’un n, la largeur d’un m,
un point (= 1/72 inch), l’unité de base (1/6 de point). On peut aussi utiliser la construction : \w’texte, qui
signifie la longueur de ‘texte’.
.DT
Remet les taquets de tabulation à leur valeur par défaut (Default tabs).
.HP i
Commence un paragraphe indenté de i sauf sa première ligne.
.IP t
Commence un paragraphe indenté avec le drapeau t. Même effet que .TP, sauf que le texte est
donné en argument et non sur la ligne suivante.
.LP
Idem .PP
.PD i
Positionne l’espacement entre paragraphe à i.
.PP
Nouveau paragraphe.
.RE
Fin de paragraphe indenté (relative end).
.RS
Commence un paragraphe indenté (relative start).
.SS t
Sous-section (comme .SH, mais pour les sous-sections).
.TP
Commence un paragraphe indenté avec un drapeau donné sur la ligne suivante. Similaire à .IP,
mais on peut ainsi appliquer une commande au drapeau (comme dans cette liste).
Note : il n’est pas interdit pour apprendre à utiliser ces commandes d’aller consulter des exemples de source des
pages de manuel dans les répertoires /usr/man/man?.
Petit manuel Unix 2002
67
COMPOSEURS DE TEXTES
NOM
latex − latex − latex
SYNTAXE
latex fichiers
DESCRIPTION
latex se dit ‘latek’ car la dernière lettre est un chi χ majuscule ‘X’ est non un simple x majuscule. Ce composeur de textes donne de merveilleux résultats, mais sa description brève dépasse pour la moment le but de
ce petit manuel.
68
Petit manuel Unix 2002
OUTILS GRAPHIQUES
Les outils graphiques sont d’une utilisation simple et intuitive, est-il donc besoin d’une documentation ?
Beaucoup de ces programmes sont de simples frontaux graphiques pour des commandes à l’interface texte
déjà existante. Voici donc une simple présentation de ces programmes.
La famille xterm, emacs
xterm,emacs forment le couple d’utilitaires que j’utilise, car ils sont disponibles sur tous les unix et emacs
permet de tout faire (sauf le café !-) : éditeur de texte avec contrôle et coloration syntaxique, gestionnaire de
courrier (RMAIL ou vm), lecteur de news (GNUS). La souris s’utilise avec les conventions suivantes :
Bouton 1 (gauche)
sélection
Bouton 2 (milieu)
insérer sélection (paste)
Bouton 3 (droite)
extension de sélection
Un clic avec Control ou Shift fait apparaître des menus.
Les commandes d’édition de lignes d’emacs sont disponibles dans beaucoup de champ texte (netscape, outils faits avec GTK+, ...) et aussi dans les interprètes qui utilisent la bibliothèque readline comme bash,
mysql et bien d’autres. Les principales commandes sont : C-a, C-e, C-d, C-k, C-y, C-t, M-d, M-l, M-u, M-c,
M-t ; elles sont décrites dans la documentation de bash dans ce manuel.
Outils de gestion de fichiers
Il existe de nombreux gestionnaires de fichiers graphiques à la Mac ou à la Windows. Ces programmes sont
bien sûr des frontaux aux commandes de base Unix décrites dans ce manuel. On peut citer : xfm, tkdesk,
mc.
Les vieux outils X11
xedit,xlsfonts,xfd,xwd,xwininfo,xmag,xman,. . . Ces programmes sont ceux du MIT X Consortium et sont
toujours disponibles avec X11. xedit est un (mauvais?) éditeur de texte, xlsfonts permet de lister les fontes
connues du serveur X, et xfd permet d’afficher une fonte particulière. xwininfo donne toutes les informations de position, taille, etc. d’une fenêtre. xmag est une loupe. xman est une interface graphique pour le
lire le manuel Unix. xwd permet de créer l’image d’une fenêtre que xwdtopnm peut transformer en pnm et
que pnmtops permet de passer en PostScript (xwd | xwdtopnm | pnmtops) crée une image PostScript de la fenêtre pointée par la souris). On peut aussi utiliser un outil de gestion d’images comme eeyes
ou gimp
pour faire une copie de l’écran ou d’une fenêtre.
GNOME
Le projet GNOME (http://www.gnome.org/) a pour but de construire un environnement de bureau
graphique complet et simple d’utilisation. C’est un projet dont tous les composants sont en sources ouverts.
Tous les composants utilisent la boîte à outils graphiques GTK+ et la technologie CORBA pour communiquer. Les principaux composants sont : le tableur gnumeric, le traitement de texte abiword, le visualiseur
d’images eog (Eye Of GNOME) ou de collections d’images gqview, l’outil de dessin vectoriel sketch,
l’éditeur de diagramme dia et enfin le célèbre gimp (GNU Image Manipulation Program) pour éditer les
images raster ; il permet (presque ?) autant de choses que le logiciel commercial Photophop.
De plus Sun Microsystems a décidé d’intégrer à GNOME son ancien StarOffice qui redécoupé est devenu
OpenOffice (http://www.openoffice.org/). Il est composé du tableur opencalc, du traitement de texte
openwriter, de l’outil de dessin vectoriel opendraw et de l’outil de présentation impress.
Voir http://www.gnome.org/gnome-office/ pour une liste plus complète.
KDE
Le projet KDE avait comme objectif de faire un environnement commun de bureau en logiciel libre (pour
remplacer CDE : Common Desktop Environment). Il est basé sur la boîte à outils graphiques Qt (prononcez
kiouti) et est composé de nombreux programmes et utilitaires dont les noms commencent par un K ce qui
permet de faire des jeux de mots très appréciés dans le milieu : Komba, Konqueror, Kmail, ...
Je n’utilise personnellement pas cet environnement et je ne développerai pas plus cette section.
Petit manuel Unix 2002
69
OUTILS GRAPHIQUES
Outils de dessin et de gestion d’images
gv, xfig, xpaint, inkscape, gimp sont d’excellents programmes disponibles gratuitement. gv permet de
visualiser du PostScript et du pdf. xfig est un outil de dessin vectoriel, xpaint un outil de dessin bitmap ; on
peut leur préférer maintenant inkscape qui produit du svg et gimp l’outil de manipulation d’images. Il
existe également la suite Image Magick (convert est décrit dans ce manuel) avec son outil d’affichage
d’images display ou l’ensemble pnm des programmes utilisables en ligne de commande ou dans des scripts
shell. N’oublions pas dans cette section eog et gqview qui font partie de Gnome.
Le son
esd (The Enlightened Sound Daemon) est un processus serveur qui permet de partager le périphérique son
d’une machine. La commande esdplay permet de jouer un fichier son et reconnaît les principaux formats
reconnus par sox. Les commandes esdcat, esdrec d’envoyer des fichiers sons bruts vers le serveur ou
d’enregistrer.
BSD
January 19, 2003
70
DASH (1)
BSD General Commands Manual
DASH (1)
NAME
dash — command interpreter (shell)
SYNOPSIS
dash [ −aCefnuvxIimqVEb] [+aCefnuvxIimqVEb] [ −o option_name] [+o option_name]
[command_file [argument . . .]]
dash −c [ −aCefnuvxIimqVEb] [+aCefnuvxIimqVEb] [ −o option_name]
[+o option_name] command_string [command_name [argument . . .]]
dash −s [ −aCefnuvxIimqVEb] [+aCefnuvxIimqVEb] [ −o option_name]
[+o option_name] [argument . . .]
DESCRIPTION
dash is the standard command interpreter for the system. The current version of dash is in the process of
being changed to conform with the POSIX 1003.2 and 1003.2a specifications for the shell. This version has
many features which make it appear similar in some respects to the Korn shell, but it is not a Korn shell clone
(see ksh(1)). Only features designated by POSIX, plus a few Berkeley extensions, are being incorporated
into this shell. This man page is not intended to be a tutorial or a complete specification of the shell.
Overview
The shell is a command that reads lines from either a file or the terminal, interprets them, and generally
executes other commands. It is the program that is running when a user logs into the system (although a user
can select a different shell with the chsh(1) command). The shell implements a language that has flow control constructs, a macro facility that provides a variety of features in addition to data storage, along with built
in history and line editing capabilities. It incorporates many features to aid interactive use and has the advantage that the interpretative language is common to both interactive and non-interactive use (shell scripts).
That is, commands can be typed directly to the running shell or can be put into a file and the file can be
executed directly by the shell.
Invocation
If no args are present and if the standard input of the shell is connected to a terminal (or if the −i flag is set),
and the −c option is not present, the shell is considered an interactive shell. An interactive shell generally
prompts before each command and handles programming and command errors differently (as described
below). When first starting, the shell inspects argument 0, and if it begins with a dash ‘-’, the shell is also
considered a login shell. This is normally done automatically by the system when the user first logs in. A
login shell first reads commands from the files /etc/profile and .profile if they exist. If the environment variable ENV is set on entry to an interactive shell, or is set in the .profile of a login shell, the
shell next reads commands from the file named in ENV. Therefore, a user should place commands that are to
be executed only at login time in the .profile file, and commands that are executed for every interactive
shell inside the ENV file. To set the ENV variable to some file, place the following line in your .profile of
your home directory
ENV=$HOME/.shinit; export ENV
substituting for “.shinit” any filename you wish.
If command line arguments besides the options have been specified, then the shell treats the first argument as
the name of a file from which to read commands (a shell script), and the remaining arguments are set as the
positional parameters of the shell ($1, $2, etc). Otherwise, the shell reads commands from its standard input.
Argument List Processing
All of the single letter options that have a corresponding name can be used as an argument to the −o option.
The set −o name is provided next to the single letter option in the description below. Specifying a dash “-”
turns the option on, while using a plus “+” disables the option. The following options can be set from the
71
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
command line or with the set builtin (described later).
−a allexport
Export all variables assigned to.
−c
Read commands from the command_string operand instead of from the
standard input. Special parameter 0 will be set from the command_name
operand and the positional parameters ($1, $2, etc.) set from the remaining
argument operands.
−C noclobber
Don’t overwrite existing files with “>”.
−e errexit
If not interactive, exit immediately if any untested command fails. The exit
status of a command is considered to be explicitly tested if the command is
used to control an if, elif, while, or until; or if the command is the
left hand operand of an “&&” or “||” operator.
−f noglob
Disable pathname expansion.
−n noexec
If not interactive, read commands but do not execute them. This is useful for
checking the syntax of shell scripts.
−u nounset
Write a message to standard error when attempting to expand a variable that
is not set, and if the shell is not interactive, exit immediately.
−v verbose
The shell writes its input to standard error as it is read. Useful for debugging.
−x xtrace
Write each command to standard error (preceded by a ‘+ ’) before it is
executed. Useful for debugging.
−I ignoreeof
Ignore EOF’s from input when interactive.
−i interactive
Force the shell to behave interactively.
−l
Make dash act as if it had been invoked as a login shell.
−m monitor
Turn on job control (set automatically when interactive).
−s stdin
Read commands from standard input (set automatically if no file arguments
are present). This option has no effect when set after the shell has already
started running (i.e. with set).
−V vi
Enable the built-in vi(1) command line editor (disables −E if it has been
set).
−E emacs
Enable the built-in emacs(1) command line editor (disables −V if it has been
set).
−b notify
Enable asynchronous notification of background job completion. (UNIMPLEMENTED for 4.4alpha)
Lexical Structure
The shell reads input in terms of lines from a file and breaks it up into words at whitespace (blanks and tabs),
and at certain sequences of characters that are special to the shell called “operators”. There are two types of
operators: control operators and redirection operators (their meaning is discussed later). Following is a list of
operators:
Control operators:
& && ( ) ; ;; | || <newline>
BSD
January 19, 2003
72
DASH (1)
BSD General Commands Manual
DASH (1)
Redirection operators:
< > >| << >> <& >& <<- <>
Quoting
Quoting is used to remove the special meaning of certain characters or words to the shell, such as operators,
whitespace, or keywords. There are three types of quoting: matched single quotes, matched double quotes,
and backslash.
Backslash
A backslash preserves the literal meaning of the following character, with the exception of 〈newline〉. A
backslash preceding a 〈newline〉 is treated as a line continuation.
Single Quotes
Enclosing characters in single quotes preserves the literal meaning of all the characters (except single quotes,
making it impossible to put single-quotes in a single-quoted string).
Double Quotes
Enclosing characters within double quotes preserves the literal meaning of all characters except dollarsign
( $ ) , backquote ( ‘ ) , and backslash ( \ ) . The backslash inside double quotes is historically weird, and
serves to quote only the following characters:
$ ‘ " \ <newline>.
Otherwise it remains literal.
Reserved Words
Reserved words are words that have special meaning to the shell and are recognized at the beginning of a line
and after a control operator. The following are reserved words:
!
else
do
elif
for
done
fi
then
until
while case
{
}
if
esac
Their meaning is discussed later.
Aliases
An alias is a name and corresponding value set using the alias(1) builtin command. Whenever a reserved
word may occur (see above), and after checking for reserved words, the shell checks the word to see if it
matches an alias. If it does, it replaces it in the input stream with its value. For example, if there is an alias
called “lf” with the value “ls -F”, then the input:
lf foobar 〈return〉
would become
ls -F foobar 〈return〉
Aliases provide a convenient way for naive users to create shorthands for commands without having to learn
how to create functions with arguments. They can also be used to create lexically obscure code. This use is
discouraged.
Commands
The shell interprets the words it reads according to a language, the specification of which is outside the scope
of this man page (refer to the BNF in the POSIX 1003.2 document). Essentially though, a line is read and if
the first word of the line (or after a control operator) is not a reserved word, then the shell has recognized a
simple command. Otherwise, a complex command or some other special construct may have been recognized.
73
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
Simple Commands
If a simple command has been recognized, the shell performs the following actions:
1.
Leading words of the form “name=value” are stripped off and assigned to the environment of the
simple command. Redirection operators and their arguments (as described below) are stripped
off and saved for processing.
2.
The remaining words are expanded as described in the section called “Expansions”, and the first
remaining word is considered the command name and the command is located. The remaining
words are considered the arguments of the command. If no command name resulted, then the
“name=value” variable assignments recognized in item 1 affect the current shell.
3.
Redirections are performed as described in the next section.
Redirections
Redirections are used to change where a command reads its input or sends its output. In general, redirections
open, close, or duplicate an existing reference to a file. The overall format used for redirection is:
[n] redir-op file
where redir-op is one of the redirection operators mentioned previously. Following is a list of the possible
redirections. The [n] is an optional number, as in ‘3’ (not ‘[3]’), that refers to a file descriptor.
[n]> file
Redirect standard output (or n) to file.
[n]>| file
Same, but override the −C option.
[n]>> file
Append standard output (or n) to file.
[n]< file
Redirect standard input (or n) from file.
[n1]<&n2
Duplicate standard input (or n1) from file descriptor n2.
[n]<&-
Close standard input (or n).
[n1]>&n2
Duplicate standard output (or n1) to n2.
[n]>&-
Close standard output (or n).
[n]<> file
Open file for reading and writing on standard input (or n).
The following redirection is often called a “here-document”.
[n]<< delimiter
here-doc-text . . .
delimiter
All the text on successive lines up to the delimiter is saved away and made available to the command on standard input, or file descriptor n if it is specified. If the delimiter as specified on the initial line is quoted, then
the here-doc-text is treated literally, otherwise the text is subjected to parameter expansion, command substitution, and arithmetic expansion (as described in the section on “Expansions”). If the operator is “<<-”
instead of “<<”, then leading tabs in the here-doc-text are stripped.
Search and Execution
There are three types of commands: shell functions, builtin commands, and normal programs -- and the command is searched for (by name) in that order. They each are executed in a different way.
When a shell function is executed, all of the shell positional parameters (except $0, which remains
unchanged) are set to the arguments of the shell function. The variables which are explicitly placed in the
environment of the command (by placing assignments to them before the function name) are made local to
the function and are set to the values given. Then the command given in the function definition is executed.
BSD
January 19, 2003
74
DASH (1)
BSD General Commands Manual
DASH (1)
The positional parameters are restored to their original values when the command completes. This all occurs
within the current shell.
Shell builtins are executed internally to the shell, without spawning a new process.
Otherwise, if the command name doesn’t match a function or builtin, the command is searched for as a normal program in the file system (as described in the next section). When a normal program is executed, the
shell runs the program, passing the arguments and the environment to the program. If the program is not a
normal executable file (i.e., if it does not begin with the "magic number" whose ASCII representation is "#!",
so execve(2) returns ENOEXEC then) the shell will interpret the program in a subshell. The child shell will
reinitialize itself in this case, so that the effect will be as if a new shell had been invoked to handle the ad-hoc
shell script, except that the location of hashed commands located in the parent shell will be remembered by
the child.
Note that previous versions of this document and the source code itself misleadingly and sporadically refer to
a shell script without a magic number as a "shell procedure".
Path Search
When locating a command, the shell first looks to see if it has a shell function by that name. Then it looks
for a builtin command by that name. If a builtin command is not found, one of two things happen:
1.
Command names containing a slash are simply executed without performing any searches.
2.
The shell searches each entry in PATH in turn for the command. The value of the PATH variable should
be a series of entries separated by colons. Each entry consists of a directory name. The current directory may be indicated implicitly by an empty directory name, or explicitly by a single period.
Command Exit Status
Each command has an exit status that can influence the behaviour of other shell commands. The paradigm is
that a command exits with zero for normal or success, and non-zero for failure, error, or a false indication.
The man page for each command should indicate the various exit codes and what they mean. Additionally,
the builtin commands return exit codes, as does an executed shell function.
If a command consists entirely of variable assignments then the exit status of the command is that of the last
command substitution if any, otherwise 0.
Complex Commands
Complex commands are combinations of simple commands with control operators or reserved words,
together creating a larger complex command. More generally, a command is one of the following:
•
simple command
•
pipeline
•
list or compound-list
•
compound command
•
function definition
Unless otherwise stated, the exit status of a command is that of the last simple command executed by the
command.
Pipelines
A pipeline is a sequence of one or more commands separated by the control operator |. The standard output
of all but the last command is connected to the standard input of the next command. The standard output of
the last command is inherited from the shell, as usual.
75
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
The format for a pipeline is:
[!] command1 [| command2 ...]
The standard output of command1 is connected to the standard input of command2. The standard input,
standard output, or both of a command is considered to be assigned by the pipeline before any redirection
specified by redirection operators that are part of the command.
If the pipeline is not in the background (discussed later), the shell waits for all commands to complete.
If the reserved word ! does not precede the pipeline, the exit status is the exit status of the last command
specified in the pipeline. Otherwise, the exit status is the logical NOT of the exit status of the last command.
That is, if the last command returns zero, the exit status is 1; if the last command returns greater than zero,
the exit status is zero.
Because pipeline assignment of standard input or standard output or both takes place before redirection, it
can be modified by redirection. For example:
$ command1 2>&1 | command2
sends both the standard output and standard error of command1 to the standard input of command2.
A ; or 〈newline〉 terminator causes the preceding AND-OR-list (described next) to be executed sequentially; a
& causes asynchronous execution of the preceding AND-OR-list.
Note that unlike some other shells, each process in the pipeline is a child of the invoking shell (unless it is a
shell builtin, in which case it executes in the current shell -- but any effect it has on the environment is
wiped).
Background Commands -- &
If a command is terminated by the control operator ampersand (&), the shell executes the command asynchronously -- that is, the shell does not wait for the command to finish before executing the next command.
The format for running a command in background is:
command1 & [command2 & ...]
If the shell is not interactive, the standard input of an asynchronous command is set to /dev/null.
Lists -- Generally Speaking
A list is a sequence of zero or more commands separated by newlines, semicolons, or ampersands, and
optionally terminated by one of these three characters. The commands in a list are executed in the order they
are written. If command is followed by an ampersand, the shell starts the command and immediately proceed onto the next command; otherwise it waits for the command to terminate before proceeding to the next
one.
Short-Circuit List Operators
“&&” and “||” are AND-OR list operators. “&&” executes the first command, and then executes the second
command iff the exit status of the first command is zero. “||” is similar, but executes the second command iff
the exit status of the first command is nonzero. “&&” and “||” both have the same priority.
Flow-Control Constructs -- if, while, for, case
The syntax of the if command is
if list
then list
[ elif list
then
list ] ...
BSD
January 19, 2003
76
DASH (1)
BSD General Commands Manual
DASH (1)
[ else list ]
fi
The syntax of the while command is
while list
do
list
done
The two lists are executed repeatedly while the exit status of the first list is zero. The until command is similar, but has the word until in place of while, which causes it to repeat until the exit status of the first list is
zero.
The syntax of the for command is
for variable [ in [ word ... ] ]
do
list
done
The words following in are expanded, and then the list is executed repeatedly with the variable set to each
word in turn. Omitting in word ... is equivalent to in "$@".
The syntax of the break and continue command is
break [ num ]
continue [ num ]
Break terminates the num innermost for or while loops. Continue continues with the next iteration of the
innermost loop. These are implemented as builtin commands.
The syntax of the case command is
case word in
pattern) list ;;
...
esac
The pattern can actually be one or more patterns (see Shell Patterns described later), separated by “|” characters.
Grouping Commands Together
Commands may be grouped by writing either
(list)
or
{ list; }
The first of these executes the commands in a subshell. Builtin commands grouped into a (list) will not
affect the current shell. The second form does not fork another shell so is slightly more efficient. Grouping
commands together this way allows you to redirect their output as though they were one program:
{ printf " hello " ; printf " world\n" ; } > greeting
Note that “}” must follow a control operator (here, “;”) so that it is recognized as a reserved word and not as
another command argument.
77
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
Functions
The syntax of a function definition is
name () command
A function definition is an executable statement; when executed it installs a function named name and returns
an exit status of zero. The command is normally a list enclosed between “{” and “}”.
Variables may be declared to be local to a function by using a local command. This should appear as the first
statement of a function, and the syntax is
local [variable | -] . . .
Local is implemented as a builtin command.
When a variable is made local, it inherits the initial value and exported and readonly flags from the variable
with the same name in the surrounding scope, if there is one. Otherwise, the variable is initially unset. The
shell uses dynamic scoping, so that if you make the variable x local to function f, which then calls function g,
references to the variable x made inside g will refer to the variable x declared inside f, not to the global variable named x.
The only special parameter that can be made local is “-”. Making “-” local any shell options that are changed
via the set command inside the function to be restored to their original values when the function returns.
The syntax of the return command is
return [exitstatus]
It terminates the currently executing function. Return is implemented as a builtin command.
Variables and Parameters
The shell maintains a set of parameters. A parameter denoted by a name is called a variable. When starting
up, the shell turns all the environment variables into shell variables. New variables can be set using the form
name=value
Variables set by the user must have a name consisting solely of alphabetics, numerics, and underscores - the
first of which must not be numeric. A parameter can also be denoted by a number or a special character as
explained below.
Positional Parameters
A positional parameter is a parameter denoted by a number (n > 0). The shell sets these initially to the values of its command line arguments that follow the name of the shell script. The set builtin can also be used
to set or reset them.
Special Parameters
A special parameter is a parameter denoted by one of the following special characters. The value of the
parameter is listed next to its character.
BSD
∗
Expands to the positional parameters, starting from one. When the expansion occurs
within a double-quoted string it expands to a single field with the value of each parameter
separated by the first character of the IFS variable, or by a 〈space〉 if IFS is unset.
@
Expands to the positional parameters, starting from one. When the expansion occurs
within double-quotes, each positional parameter expands as a separate argument. If there
are no positional parameters, the expansion of @ generates zero arguments, even when @
is double-quoted. What this basically means, for example, is if $1 is “abc” and $2 is “def
ghi”, then "$@" expands to the two arguments:
January 19, 2003
78
DASH (1)
BSD General Commands Manual
DASH (1)
"abc" "def ghi"
#
Expands to the number of positional parameters.
?
Expands to the exit status of the most recent pipeline.
- (Hyphen.)
Expands to the current option flags (the single-letter option names concatenated into a
string) as specified on invocation, by the set builtin command, or implicitly by the shell.
$
Expands to the process ID of the invoked shell. A subshell retains the same value of $ as
its parent.
!
Expands to the process ID of the most recent background command executed from the current shell. For a pipeline, the process ID is that of the last command in the pipeline.
0 (Zero.)
Expands to the name of the shell or shell script.
Word Expansions
This clause describes the various expansions that are performed on words. Not all expansions are performed
on every word, as explained later.
Tilde expansions, parameter expansions, command substitutions, arithmetic expansions, and quote removals
that occur within a single word expand to a single field. It is only field splitting or pathname expansion that
can create multiple fields from a single word. The single exception to this rule is the expansion of the special
parameter @ within double-quotes, as was described above.
The order of word expansion is:
1.
Tilde Expansion, Parameter Expansion, Command Substitution, Arithmetic Expansion (these all occur
at the same time).
2.
Field Splitting is performed on fields generated by step (1) unless the IFS variable is null.
3.
Pathname Expansion (unless set −f is in effect).
4.
Quote Removal.
The $ character is used to introduce parameter expansion, command substitution, or arithmetic evaluation.
Tilde Expansion (substituting a user’s home directory)
A word beginning with an unquoted tilde character (˜) is subjected to tilde expansion. All the characters up
to a slash (/) or the end of the word are treated as a username and are replaced with the user’s home directory.
If the username is missing (as in ˜/foobar), the tilde is replaced with the value of the HOME variable (the
current user’s home directory).
Parameter Expansion
The format for parameter expansion is as follows:
${expression}
where expression consists of all characters until the matching “}”. Any “}” escaped by a backslash or within
a quoted string, and characters in embedded arithmetic expansions, command substitutions, and variable
expansions, are not examined in determining the matching “}”.
The simplest form for parameter expansion is:
${parameter}
The value, if any, of parameter is substituted.
79
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
The parameter name or symbol can be enclosed in braces, which are optional except for positional parameters with more than one digit or when parameter is followed by a character that could be interpreted as part of
the name. If a parameter expansion occurs inside double-quotes:
1.
Pathname expansion is not performed on the results of the expansion.
2.
Field splitting is not performed on the results of the expansion, with the exception of @.
In addition, a parameter expansion can be modified by using one of the following formats.
${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is
substituted; otherwise, the value of parameter is substituted.
${parameter:=word}
Assign Default Values. If parameter is unset or null, the expansion of word is
assigned to parameter. In all cases, the final value of parameter is substituted.
Only variables, not positional parameters or special parameters, can be
assigned in this way.
${parameter:?[word]}
Indicate Error if Null or Unset. If parameter is unset or null, the expansion of
word (or a message indicating it is unset if word is omitted) is written to standard error and the shell exits with a nonzero exit status. Otherwise, the value
of parameter is substituted. An interactive shell need not exit.
${parameter:+word}
Use Alternative Value. If parameter is unset or null, null is substituted; otherwise, the expansion of word is substituted.
In the parameter expansions shown previously, use of the colon in the format results in a test for a parameter
that is unset or null; omission of the colon results in a test for a parameter that is only unset.
${#parameter}
String Length. The length in characters of the value of parameter.
The following four varieties of parameter expansion provide for substring processing. In each case, pattern
matching notation (see Shell Patterns), rather than regular expression notation, is used to evaluate the patterns. If parameter is ∗ or @, the result of the expansion is unspecified. Enclosing the full parameter expansion string in double-quotes does not cause the following four varieties of pattern characters to be quoted,
whereas quoting characters within the braces has this effect.
${parameter%word}
Remove Smallest Suffix Pattern. The word is expanded to produce a pattern.
The parameter expansion then results in parameter, with the smallest portion
of the suffix matched by the pattern deleted.
${parameter%%word}
Remove Largest Suffix Pattern. The word is expanded to produce a pattern.
The parameter expansion then results in parameter, with the largest portion of
the suffix matched by the pattern deleted.
${parameter#word}
Remove Smallest Prefix Pattern. The word is expanded to produce a pattern.
The parameter expansion then results in parameter, with the smallest portion
of the prefix matched by the pattern deleted.
${parameter##word}
Remove Largest Prefix Pattern. The word is expanded to produce a pattern.
The parameter expansion then results in parameter, with the largest portion of
the prefix matched by the pattern deleted.
Command Substitution
Command substitution allows the output of a command to be substituted in place of the command name
itself. Command substitution occurs when the command is enclosed as follows:
$(command)
BSD
January 19, 2003
80
DASH (1)
BSD General Commands Manual
DASH (1)
or ( “backquoted” version ) :
‘command‘
The shell expands the command substitution by executing command in a subshell environment and replacing
the command substitution with the standard output of the command, removing sequences of one or more
〈newline〉s at the end of the substitution. (Embedded 〈newline〉s before the end of the output are not
removed; however, during field splitting, they may be translated into 〈space〉s, depending on the value of IFS
and quoting that is in effect.)
Arithmetic Expansion
Arithmetic expansion provides a mechanism for evaluating an arithmetic expression and substituting its
value. The format for arithmetic expansion is as follows:
$((expression))
The expression is treated as if it were in double-quotes, except that a double-quote inside the expression is
not treated specially. The shell expands all tokens in the expression for parameter expansion, command substitution, and quote removal.
Next, the shell treats this as an arithmetic expression and substitutes the value of the expression.
White Space Splitting (Field Splitting)
After parameter expansion, command substitution, and arithmetic expansion the shell scans the results of
expansions and substitutions that did not occur in double-quotes for field splitting and multiple fields can
result.
The shell treats each character of the IFS as a delimiter and uses the delimiters to split the results of parameter expansion and command substitution into fields.
Pathname Expansion (File Name Generation)
Unless the −f flag is set, file name generation is performed after word splitting is complete. Each word is
viewed as a series of patterns, separated by slashes. The process of expansion replaces the word with the
names of all existing files whose names can be formed by replacing each pattern with a string that matches
the specified pattern. There are two restrictions on this: first, a pattern cannot match a string containing a
slash, and second, a pattern cannot match a string starting with a period unless the first character of the pattern is a period. The next section describes the patterns used for both Pathname Expansion and the case
command.
Shell Patterns
A pattern consists of normal characters, which match themselves, and meta-characters. The meta-characters
are “!”, “∗”, “?”, and “[”. These characters lose their special meanings if they are quoted. When command
or variable substitution is performed and the dollar sign or back quotes are not double quoted, the value of
the variable or the output of the command is scanned for these characters and they are turned into meta-characters.
An asterisk ( “∗” ) matches any string of characters. A question mark matches any single character. A left
bracket ( “[” ) introduces a character class. The end of the character class is indicated by a ( “]” ) ; if the “]”
is missing then the “[” matches a “[” rather than introducing a character class. A character class matches any
of the characters between the square brackets. A range of characters may be specified using a minus sign.
The character class may be complemented by making an exclamation point the first character of the character
class.
To include a “]” in a character class, make it the first character listed (after the “!”, if any). To include a
minus sign, make it the first or last character listed.
81
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
Builtins
This section lists the builtin commands which are builtin because they need to perform some operation that
can’t be performed by a separate process. In addition to these, there are several other commands that may be
builtin for efficiency (e.g. printf(1), echo(1), test(1), etc).
:
true
A null command that returns a 0 (true) exit value.
. file
The commands in the specified file are read and executed by the shell.
alias [name[=string ...]]
If name=string is specified, the shell defines the alias name with value string. If just name is
specified, the value of the alias name is printed. With no arguments, the alias builtin prints the
names and values of all defined aliases (see unalias).
bg [job] . . .
Continue the specified jobs (or the current job if no jobs are given) in the background.
command [ −p] [ −v] [ −V] command [arg . . .]
Execute the specified command but ignore shell functions when searching for it. (This is useful when
you have a shell function with the same name as a builtin command.)
−p
search for command using a PATH that guarantees to find all the standard utilities.
−V
Do not execute the command but search for the command and print the resolution of the command search. This is the same as the type builtin.
−v
Do not execute the command but search for the command and print the absolute pathname of
utilities, the name for builtins or the expansion of aliases.
cd cd [ −LP] [directory]
Switch to the specified directory (default HOME). If an entry for CDPATH appears in the environment
of the cd command or the shell variable CDPATH is set and the directory name does not begin with a
slash, then the directories listed in CDPATH will be searched for the specified directory. The format
of CDPATH is the same as that of PATH. If a single dash is specified as the argument, it will be
replaced by the value of OLDPWD. The cd command will print out the name of the directory that it
actually switched to if this is different from the name that the user gave. These may be different
either because the CDPATH mechanism was used or because the argument is a single dash. The −P
option causes the physical directory structure to be used, that is, all symbolic links are resolved to
their respective values. The −L option turns off the effect of any preceding −P options.
echo [ −n] args...
Print the arguments on the standard output, separated by spaces. Unless the −n option is present, a
newline is output following the arguments.
If any of the following sequences of characters is encountered during output, the sequence is not output. Instead, the specified action is performed:
BSD
\b
A backspace character is output.
\c
Subsequent output is suppressed. This is normally used at the end of the last argument to
suppress the trailing newline that echo would otherwise output.
\f
Output a form feed.
January 19, 2003
82
DASH (1)
BSD General Commands Manual
\n
Output a newline character.
\r
Output a carriage return.
\t
Output a (horizontal) tab character.
\v
Output a vertical tab.
DASH (1)
\0digits
Output the character whose value is given by zero to three octal digits. If there are zero
digits, a nul character is output.
\\
Output a backslash.
All other backslash sequences elicit undefined behaviour.
eval string . . .
Concatenate all the arguments with spaces. Then re-parse and execute the command.
exec [command arg . . .]
Unless command is omitted, the shell process is replaced with the specified program (which must be
a real program, not a shell builtin or function). Any redirections on the exec command are marked
as permanent, so that they are not undone when the exec command finishes.
exit [exitstatus]
Terminate the shell process. If exitstatus is given it is used as the exit status of the shell; otherwise the exit status of the preceding command is used.
export name . . .
export −p
The specified names are exported so that they will appear in the environment of subsequent commands. The only way to un-export a variable is to unset it. The shell allows the value of a variable to
be set at the same time it is exported by writing
export name=value
With no arguments the export command lists the names of all exported variables. With the −p option
specified the output will be formatted suitably for non-interactive use.
fc [ −e editor] [first [last]]
fc −l [ −nr] [first [last]]
fc −s [old=new] [first]
The fc builtin lists, or edits and re-executes, commands previously entered to an interactive shell.
−e editor
Use the editor named by editor to edit the commands. The editor string is a command name,
subject to search via the PATH variable. The value in the FCEDIT variable is used as a
default when −e is not specified. If FCEDIT is null or unset, the value of the EDITOR variable is used. If EDITOR is null or unset, ed(1) is used as the editor.
−l (ell)
List the commands rather than invoking an editor on them. The commands are written in the
sequence indicated by the first and last operands, as affected by −r, with each command preceded by the command number.
−n
83
Suppress command numbers when listing with -l.
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
−r
Reverse the order of the commands listed (with −l) or edited (with neither −l nor −s).
−s
Re-execute the command without invoking an editor.
first
last
Select the commands to list or edit. The number of previous commands that can be accessed
are determined by the value of the HISTSIZE variable. The value of first or last or both are
one of the following:
[+]number
A positive number representing a command number; command numbers can be displayed with the −l option.
−number
A negative decimal number representing the command that was executed number of
commands previously. For example, −1 is the immediately previous command.
string A string indicating the most recently entered command that begins with that string. If the
old=new operand is not also specified with −s, the string form of the first operand cannot
contain an embedded equal sign.
The following environment variables affect the execution of fc:
FCEDIT
Name of the editor to use.
HISTSIZE The number of previous commands that are accessible.
fg [job]
Move the specified job or the current job to the foreground.
getopts optstring var
The POSIX getopts command, not to be confused with the Bell Labs -derived getopt(1).
The first argument should be a series of letters, each of which may be optionally followed by a colon
to indicate that the option requires an argument. The variable specified is set to the parsed option.
The getopts command deprecates the older getopt(1) utility due to its handling of arguments
containing whitespace.
The getopts builtin may be used to obtain options and their arguments from a list of parameters.
When invoked, getopts places the value of the next option from the option string in the list in the
shell variable specified by var and its index in the shell variable OPTIND. When the shell is invoked,
OPTIND is initialized to 1. For each option that requires an argument, the getopts builtin will
place it in the shell variable OPTARG. If an option is not allowed for in the optstring, then OPTARG
will be unset.
optstring is a string of recognized option letters (see getopt(3)). If a letter is followed by a colon,
the option is expected to have an argument which may or may not be separated from it by white
space. If an option character is not found where expected, getopts will set the variable var to a
“?”; getopts will then unset OPTARG and write output to standard error. By specifying a colon as
the first character of optstring all errors will be ignored.
A nonzero value is returned when the last option is reached. If there are no remaining arguments,
getopts will set var to the special option, “--”, otherwise, it will set var to “?”.
The following code fragment shows how one might process the arguments for a command that can
take the options [a] and [b], and the option [c], which requires an argument.
BSD
January 19, 2003
84
DASH (1)
BSD General Commands Manual
DASH (1)
while getopts abc: f
do
case $f in
a | b) flag=$f;;
c)
carg=$OPTARG;;
\?)
echo $USAGE; exit 1;;
esac
done
shift ‘expr $OPTIND - 1‘
This code will accept any of the following as equivalent:
cmd
cmd
cmd
cmd
−acarg file file
−a −c arg file file
−carg -a file file
−a −carg −− file file
hash −rv command . . .
The shell maintains a hash table which remembers the locations of commands. With no arguments
whatsoever, the hash command prints out the contents of this table. Entries which have not been
looked at since the last cd command are marked with an asterisk; it is possible for these entries to be
invalid.
With arguments, the hash command removes the specified commands from the hash table (unless
they are functions) and then locates them. With the −v option, hash prints the locations of the commands as it finds them. The −r option causes the hash command to delete all the entries in the hash
table except for functions.
pwd [ −LP]
builtin command remembers what the current directory is rather than recomputing it each time. This
makes it faster. However, if the current directory is renamed, the builtin version of pwd will continue
to print the old name for the directory. The −P option causes the physical value of the current working directory to be shown, that is, all symbolic links are resolved to their respective values. The −L
option turns off the effect of any preceding −P options.
read [ −p prompt] [ −r] variable [ . . .]
The prompt is printed if the −p option is specified and the standard input is a terminal. Then a line is
read from the standard input. The trailing newline is deleted from the line and the line is split as
described in the section on word splitting above, and the pieces are assigned to the variables in order.
At least one variable must be specified. If there are more pieces than variables, the remaining pieces
(along with the characters in IFS that separated them) are assigned to the last variable. If there are
more variables than pieces, the remaining variables are assigned the null string. The read builtin
will indicate success unless EOF is encountered on input, in which case failure is returned.
By default, unless the −r option is specified, the backslash “\” acts as an escape character, causing
the following character to be treated literally. If a backslash is followed by a newline, the backslash
and the newline will be deleted.
readonly name . . .
readonly −p
The specified names are marked as read only, so that they cannot be subsequently modified or unset.
The shell allows the value of a variable to be set at the same time it is marked read only by writing
readonly name=value
85
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
With no arguments the readonly command lists the names of all read only variables. With the −p
option specified the output will be formatted suitably for non-interactive use.
printf format [arguments . . .]
printf formats and prints its arguments, after the first, under control of the format. The format
is a character string which contains three types of objects: plain characters, which are simply copied
to standard output, character escape sequences which are converted and copied to the standard output,
and format specifications, each of which causes printing of the next successive argument.
The arguments after the first are treated as strings if the corresponding format is either b, c or s;
otherwise it is evaluated as a C constant, with the following extensions:
•
•
A leading plus or minus sign is allowed.
If the leading character is a single or double quote, the value is the ASCII code of the next
character.
The format string is reused as often as necessary to satisfy the arguments. Any extra format specifications are evaluated with zero or the null string.
Character escape sequences are in backslash notation as defined in ANSI X3.159-1989 (“ANSI C89”).
The characters and their meanings are as follows:
\a
Write a <bell> character.
\b
Write a <backspace> character.
\f
Write a <form-feed> character.
\n
Write a <new-line> character.
\r
Write a <carriage return> character.
\t
Write a <tab> character.
\v
Write a <vertical tab> character.
\\
Write a backslash character.
\num
Write an 8−bit character whose ASCII value is the 1−, 2−, or 3−digit octal number
num.
Each format specification is introduced by the percent character (‘‘%’’). The remainder of the format
specification includes, in the following order:
Zero or more of the following flags:
BSD
#
A ‘#’ character specifying that the value should be printed in an ‘‘alternative form’’.
For b, c, d, and s formats, this option has no effect. For the o format the precision
of the number is increased to force the first character of the output string to a zero.
For the x ( X ) format, a non-zero result has the string 0x ( 0X ) prepended to it.
For e, E, f, g, and G formats, the result will always contain a decimal point, even if
no digits follow the point (normally, a decimal point only appears in the results of
those formats if a digit follows the decimal point). For g and G formats, trailing
zeros are not removed from the result as they would otherwise be.
−
A minus sign ‘−’ which specifies left adjustment of the output in the indicated field;
+
A ‘+’ character specifying that there should always be a sign placed before the number when using signed formats.
January 19, 2003
86
DASH (1)
BSD General Commands Manual
DASH (1)
‘’
A space specifying that a blank should be left before a positive number for a signed
format. A ‘+’ overrides a space if both are used;
0
A zero ‘0’ character indicating that zero-padding should be used rather than blankpadding. A ‘−’ overrides a ‘0’ if both are used;
Field Width:
An optional digit string specifying a field width; if the output string has fewer characters than
the field width it will be blank-padded on the left (or right, if the left-adjustment indicator
has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision:
An optional period, ‘.’, followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string (b and s formats); if the digit string is
missing, the precision is treated as zero;
Format:
A character which indicates the type of format to use (one of diouxXfwEgGbcs).
A field width or precision may be ‘∗’ instead of a digit string. In this case an argument supplies
the field width or precision.
The format characters and their meanings are:
diouXx
The argument is printed as a signed decimal (d or i), unsigned octal, unsigned decimal, or unsigned hexadecimal (X or x), respectively.
f
The argument is printed in the style [−]ddd.ddd where the number of d’s after the
decimal point is equal to the precision specification for the argument. If the precision is
missing, 6 digits are given; if the precision is explicitly 0, no digits and no decimal
point are printed.
eE
The argument is printed in the style [−]d.ddde±dd where there is one digit before
the decimal point and the number after is equal to the precision specification for the
argument; when the precision is missing, 6 digits are produced. An upper-case E is
used for an ‘E’ format.
gG
The argument is printed in style f or in style e ( E ) whichever gives full precision in
minimum space.
b
Characters from the string argument are printed with backslash-escape sequences
expanded.
The following additional backslash-escape sequences are supported:
\c
Causes dash to ignore any remaining characters in the string operand containing it, any remaining string operands, and any additional characters in the format operand.
\0num Write an 8−bit character whose ASCII value is the 1−, 2−, or 3−digit octal
number num.
87
c
The first character of argument is printed.
s
Characters from the string argument are printed until the end is reached or until the
number of characters indicated by the precision specification is reached; if the precision
is omitted, all characters in the string are printed.
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
%
DASH (1)
Print a ‘%’; no argument is used.
In no case does a non-existent or small field width cause truncation of a field; padding takes place
only if the specified field width exceeds the actual width.
set [{ −options | +options | -- }] arg . . .
The set command performs three different functions.
With no arguments, it lists the values of all shell variables.
If options are given, it sets the specified option flags, or clears them as described in the section called
Argument List Processing. As a special case, if the option is -o or +o and no argument is supplied,
the shell prints the settings of all its options. If the option is -o, the settings are printed in a humanreadable format; if the option is +o, the settings are printed in a format suitable for reinput to the shell
to affect the same option settings.
The third use of the set command is to set the values of the shell’s positional parameters to the specified args. To change the positional parameters without changing any options, use “--” as the first
argument to set. If no args are present, the set command will clear all the positional parameters
(equivalent to executing “shift $#”.)
shift [n]
Shift the positional parameters n times. A shift sets the value of $1 to the value of $2, the value of
$2 to the value of $3, and so on, decreasing the value of $# by one. If n is greater than the number of
positional parameters, shift will issue an error message, and exit with return status 2.
test expression
[ expression ]
The test utility evaluates the expression and, if it evaluates to true, returns a zero (true) exit status;
otherwise it returns 1 (false). If there is no expression, test also returns 1 (false).
All operators and flags are separate arguments to the test utility.
The following primaries are used to construct expression:
−b file
True if file exists and is a block special file.
−c file
True if file exists and is a character special file.
−d file
True if file exists and is a directory.
−e file
True if file exists (regardless of type).
−f file
True if file exists and is a regular file.
−g file
True if file exists and its set group ID flag is set.
−h file
True if file exists and is a symbolic link.
−k file
True if file exists and its sticky bit is set.
−n string True if the length of string is nonzero.
−p file
True if file is a named pipe ( FIFO ) .
−r file
True if file exists and is readable.
−s file
True if file exists and has a size greater than zero.
−t file_descriptor
True if the file whose file descriptor number is file_descriptor is open and is
associated with a terminal.
BSD
January 19, 2003
88
DASH (1)
BSD General Commands Manual
DASH (1)
−u file
True if file exists and its set user ID flag is set.
−w file
True if file exists and is writable. True indicates only that the write flag is on. The
file is not writable on a read-only file system even if this test indicates true.
−x file
True if file exists and is executable. True indicates only that the execute flag is on.
If file is a directory, true indicates that file can be searched.
−z string True if the length of string is zero.
−L file
True if file exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use −h
instead.
−O file
True if file exists and its owner matches the effective user id of this process.
−G file
True if file exists and its group matches the effective group id of this process.
−S file
True if file exists and is a socket.
file1 −nt file2
True if file1 and file2 exist and file1 is newer than file2.
file1 −ot file2
True if file1 and file2 exist and file1 is older than file2.
file1 −ef file2
True if file1 and file2 exist and refer to the same file.
string
True if string is not the null string.
s1 = s2
True if the strings s1 and s2 are identical.
s1 != s2
True if the strings s1 and s2 are not identical.
s1 < s2
True if string s1 comes before s2 based on the ASCII value of their characters.
s1 > s2
True if string s1 comes after s2 based on the ASCII value of their characters.
n1 −eq n2 True if the integers n1 and n2 are algebraically equal.
n1 −ne n2 True if the integers n1 and n2 are not algebraically equal.
n1 −gt n2 True if the integer n1 is algebraically greater than the integer n2.
n1 −ge n2 True if the integer n1 is algebraically greater than or equal to the integer n2.
n1 −lt n2 True if the integer n1 is algebraically less than the integer n2.
n1 −le n2 True if the integer n1 is algebraically less than or equal to the integer n2.
These primaries can be combined with the following operators:
! expression
True if expression is false.
expression1 −a expression2
True if both expression1 and expression2 are true.
expression1 −o expression2
True if either expression1 or expression2 are true.
(expression)
True if expression is true.
89
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
The −a operator has higher precedence than the −o operator.
times Print the accumulated user and system times for the shell and for processes run from the shell. The
return status is 0.
trap [action signal . . .]
Cause the shell to parse and execute action when any of the specified signals are received. The signals are specified by signal number or as the name of the signal. If signal is 0, the action is
executed when the shell exits. action may be null, which cause the specified signals to be ignored.
With action omitted or set to ‘-’ the specified signals are set to their default action. When the shell
forks off a subshell, it resets trapped (but not ignored) signals to the default action. The trap command has no effect on signals that were ignored on entry to the shell. trap without any arguments
cause it to write a list of signals and their associated action to the standard output in a format that is
suitable as an input to the shell that achieves the same trapping results.
Examples:
trap
List trapped signals and their corresponding action
trap ’’ INT QUIT tstp 30
Ignore signals INT QUIT TSTP USR1
trap date INT
Print date upon receiving signal INT
type [name . . .]
Interpret each name as a command and print the resolution of the command search. Possible resolutions are: shell keyword, alias, shell builtin, command, tracked alias and not found. For aliases the
alias expansion is printed; for commands and tracked aliases the complete pathname of the command
is printed.
ulimit [ −H | −S] [ −a | −tfdscmlpn [value]]
Inquire about or set the hard or soft limits on processes or set new limits. The choice between hard
limit (which no process is allowed to violate, and which may not be raised once it has been lowered)
and soft limit (which causes processes to be signaled but not necessarily killed, and which may be
raised) is made with these flags:
−H
set or inquire about hard limits
−S
set or inquire about soft limits. If neither −H nor −S is specified, the soft limit is displayed or both limits are set. If both are specified, the last one wins.
The limit to be interrogated or set, then, is chosen by specifying any one of these flags:
BSD
−a
show all the current limits
−t
show or set the limit on CPU time (in seconds)
−f
show or set the limit on the largest file that can be created (in 512-byte blocks)
−d
show or set the limit on the data segment size of a process (in kilobytes)
−s
show or set the limit on the stack size of a process (in kilobytes)
−c
show or set the limit on the largest core dump size that can be produced (in 512-byte
blocks)
January 19, 2003
90
DASH (1)
BSD General Commands Manual
DASH (1)
−m
show or set the limit on the total physical memory that can be in use by a process (in
kilobytes)
−l
show or set the limit on how much memory a process can lock with mlock(2) (in kilobytes)
−p
show or set the limit on the number of processes this user can have at one time
−n
show or set the limit on the number files a process can have open at once
If none of these is specified, it is the limit on file size that is shown or set. If value is specified, the
limit is set to that number; otherwise the current limit is displayed.
Limits of an arbitrary process can be displayed or set using the sysctl(8) utility.
umask [mask]
Set the value of umask (see umask(2)) to the specified octal value. If the argument is omitted, the
umask value is printed.
unalias [ −a] [name]
If name is specified, the shell removes that alias. If −a is specified, all aliases are removed.
unset [ −fv] name . . .
The specified variables and functions are unset and unexported. If −f or −v is specified, the corresponding function or variable is unset, respectively. If a given name corresponds to both a variable
and a function, and no options are given, only the variable is unset.
wait [job]
Wait for the specified job to complete and return the exit status of the last process in the job. If the
argument is omitted, wait for all jobs to complete and the return an exit status of zero.
Command Line Editing
When dash is being used interactively from a terminal, the current command and the command history (see
fc in Builtins) can be edited using vi-mode command-line editing. This mode uses commands, described
below, similar to a subset of those described in the vi man page. The command set -o vi enables vimode editing and place sh into vi insert mode. With vi-mode enabled, sh can be switched between insert
mode and command mode. The editor is not described in full here, but will be in a later document. It’s similar to vi: typing 〈ESC〉 will throw you into command VI command mode. Hitting 〈return〉 while in command
mode will pass the line to the shell.
EXIT STATUS
Errors that are detected by the shell, such as a syntax error, will cause the shell to exit with a non-zero exit
status. If the shell is not an interactive shell, the execution of the shell file will be aborted. Otherwise the
shell will return the exit status of the last command executed, or if the exit builtin is used with a numeric
argument, it will return the argument.
ENVIRONMENT
HOME
91
Set automatically by login(1) from the user’s login directory in the password file
( passwd(4) ) . This environment variable also functions as the default argument for the cd
builtin.
PATH
The default search path for executables. See the above section Path Search.
CDPATH
The search path used with the cd builtin.
MAIL
The name of a mail file, that will be checked for the arrival of new mail. Overridden by
MAILPATH.
January 19, 2003
BSD
DASH (1)
BSD General Commands Manual
DASH (1)
MAILCHECK The frequency in seconds that the shell checks for the arrival of mail in the files specified by
the MAILPATH or the MAIL file. If set to 0, the check will occur at each prompt.
MAILPATH
A colon “:” separated list of file names, for the shell to check for incoming mail. This environment setting overrides the MAIL setting. There is a maximum of 10 mailboxes that can be
monitored at once.
PS1
The primary prompt string, which defaults to “$ ”, unless you are the superuser, in which case
it defaults to “# ”.
PS2
The secondary prompt string, which defaults to “> ”.
PS4
Output before each line when execution trace (set -x) is enabled, defaults to “+ ”.
IFS
Input Field Separators. This is normally set to 〈space〉, 〈tab〉, and 〈newline〉. See the White
Space Splitting section for more details.
TERM
The default terminal setting for the shell. This is inherited by children of the shell, and is used
in the history editing modes.
HISTSIZE
The number of lines in the history buffer for the shell.
PWD
The logical value of the current working directory. This is set by the cd command.
OLDPWD
The previous logical value of the current working directory. This is set by the cd command.
PPID
The process ID of the parent process of the shell.
FILES
$HOME/.profile
/etc/profile
SEE ALSO
csh(1), echo(1), getopt(1), ksh(1), login(1), printf(1), test(1), getopt(3), passwd(5),
environ(7), sysctl(8)
HISTORY
dash is a POSIX-compliant implementation of /bin/sh that aims to be as small as possible. dash is a direct
descendant of the NetBSD version of ash (the Almquist SHell), ported to Linux in early 1997. It was
renamed to dash in 2002.
BUGS
Setuid shell scripts should be avoided at all costs, as they are a significant security risk.
PS1, PS2, and PS4 should be subject to parameter expansion before being displayed.
92
ED(1)
ED(1)
NAME
ed, red − text editor
SYNOPSIS
ed [-] [-Gs] [-p string] [file]
red [-] [-Gs] [-p string] [file]
DESCRIPTION
ed is a line-oriented text editor. It is used to create, display, modify and otherwise manipulate text files.
red is a restricted ed: it can only edit files in the current directory and cannot execute shell commands.
If invoked with a file argument, then a copy of file is read into the editor’s buffer. Changes are made to this
copy and not directly to file itself. Upon quitting ed, any changes not explicitly saved with a ‘w’ command
are lost.
Editing is done in two distinct modes: command and input. When first invoked, ed is in command mode.
In this mode commands are read from the standard input and executed to manipulate the contents of the
editor buffer. A typical command might look like:
,s/old/new/g
which replaces all occurences of the string old with new.
When an input command, such as ‘a’ (append), ‘i’ (insert) or ‘c’ (change), is given, ed enters input mode.
This is the primary means of adding text to a file. In this mode, no commands are available; instead, the
standard input is written directly to the editor buffer. Lines consist of text up to and including a newline
character. Input mode is terminated by entering a single period (.) on a line.
All ed commands operate on whole lines or ranges of lines; e.g., the ‘d’ command deletes lines; the ‘m’
command moves lines, and so on. It is possible to modify only a portion of a line by means of replacement,
as in the example above. However even here, the ‘s’ command is applied to whole lines at a time.
In general, ed commands consist of zero or more line addresses, followed by a single character command
and possibly additional parameters; i.e., commands have the structure:
[address [,address]]command[parameters]
The address(es) indicate the line or range of lines to be affected by the command. If fewer addresses are
given than the command accepts, then default addresses are supplied.
OPTIONS
-G
-s
Forces backwards compatibility. Affects the commands ‘G’, ‘V’, ‘f ’, ‘l’, ‘m’, ‘t’, and ‘!!’.
Suppresses diagnostics. This should be used if ed’s standard input is from a script.
−p string
Specifies a command prompt. This may be toggled on and off with the ‘P’ command.
file
Specifies the name of a file to read. If file is prefixed with a bang (!), then it is interpreted as a
shell command. In this case, what is read is the standard output of file executed via sh(1). To
read a file whose name begins with a bang, prefix the name with a backslash (\). The default filename is set to file only if it is not prefixed with a bang.
10 November 1994
93
ED(1)
ED(1)
LINE ADDRESSING
An address represents the number of a line in the buffer. ed maintains a current address which is typically
supplied to commands as the default address when none is specified. When a file is first read, the current
address is set to the last line of the file. In general, the current address is set to the last line affected by a
command.
A line address is constructed from one of the bases in the list below, optionally followed by a numeric offset. The offset may include any combination of digits, operators (i.e., +, - and ˆ ) and whitespace.
Addresses are read from left to right, and their values are computed relative to the current address.
One exception to the rule that addresses represent line numbers is the address 0 (zero). This means "before
the first line," and is legal wherever it makes sense.
An address range is two addresses separated either by a comma or semicolon. The value of the first address
in a range cannot exceed the value of the the second. If only one address is given in a range, then the second address is set to the given address. If an n-tuple of addresses is given where n > 2, then the corresponding range is determined by the last two addresses in the n-tuple. If only one address is expected, then
the last address is used.
Each address in a comma-delimited range is interpreted relative to the current address. In a semicolondelimited range, the first address is used to set the current address, and the second address is interpreted relative to the first.
The following address symbols are recognized.
.
The current line (address) in the buffer.
$
The last line in the buffer.
n
The nth, line in the buffer where n is a number in the range [0,$].
ˆ
The previous line. This is equivalent to -1 and may be repeated with cumulative effect.
-n
ˆn
The nth previous line, where n is a non-negative number.
+
The next line. This is equivalent to +1 and may be repeated with cumulative effect.
+n
whitespace n
The nth next line, where n is a non-negative number. Whitespace followed by a number n is
interpreted as +n.
,
%
94
The first through last lines in the buffer. This is equivalent to the address range 1,$.
10 November 1994
ED(1)
ED(1)
;
The current through last lines in the buffer. This is equivalent to the address range .,$.
/re/
The next line containing the regular expression re. The search wraps to the beginning of the buffer and continues down to the current line, if necessary. // repeats the last search.
?re?
The previous line containing the regular expression re. The search wraps to the end of the buffer
and continues up to the current line, if necessary. ?? repeats the last search.
´lc
The line previously marked by a ‘k’ (mark) command, where lc is a lower case letter.
REGULAR EXPRESSIONS
Regular expressions are patterns used in selecting text. For example, the ed command
g/string/
prints all lines containing string. Regular expressions are also used by the ‘s’ command for selecting old
text to be replaced with new.
In addition to a specifying string literals, regular expressions can represent classes of strings. Strings thus
represented are said to be matched by the corresponding regular expression. If it is possible for a regular
expression to match several strings in a line, then the left-most longest match is the one selected.
The following symbols are used in constructing regular expressions:
c
Any character c not listed below, including ‘{’, ’}’, ‘(’, ‘)’, ‘<’ and ‘>’, matches itself.
\c
A backslash-escaped character c other than ‘{’, ’}’, ‘(’, ‘)’, ‘<’, ‘>’, ‘b’, ’B’, ‘w’, ‘W’, ‘+’, and
‘?’ matches itself.
.
Matches any single character.
[char-class]
Matches any single character in char-class. To include a ‘]’ in char-class, it must be the first
character. A range of characters may be specified by separating the end characters of the range
with a ‘-’, e.g., ‘a-z’ specifies the lower case characters. The following literal expressions can
also be used in char-class to specify sets of characters:
[:alnum:] [:cntrl:] [:lower:] [:space:]
[:blank:] [:graph:] [:punct:] [:xdigit:]
[:alpha:] [:digit:] [:print:] [:upper:]
If ‘-’ appears as the first or last character of char-class, then it matches itself. All other characters
in char-class match themselves.
Patterns in char-class of the form:
[.col-elm.] or, [=col-elm=]
where col-elm is a collating element are interpreted according to locale(5) (not currently supported). See regex(3) for an explanation of these constructs.
10 November 1994
95
ED(1)
ED(1)
[ˆchar-class]
Matches any single character, other than newline, not in char-class. char-class is defined as
above.
ˆ
If ‘ˆ’ is the first character of a regular expression, then it anchors the regular expression to the
beginning of a line. Otherwise, it matches itself.
$
If ‘$’ is the last character of a regular expression, it anchors the regular expression to the end of a
line. Otherwise, it matches itself.
\(re\)
Defines a (possibly null) subexpression re. Subexpressions may be nested. A subsequent backreference of the form ‘\n’, where n is a number in the range [1,9], expands to the text matched by
the nth subexpression. For example, the regular expression ‘\(a.c\)\1’ matches the string
‘abcabc’, but not ‘abcadc’. Subexpressions are ordered relative to their left delimiter.
∗
Matches the single character regular expression or subexpression immediately preceding it zero
or more times. If ’∗’ is the first character of a regular expression or subexpression, then it
matches itself. The ‘∗’ operator sometimes yields unexpected results. For example, the regular
expression ‘b∗’ matches the beginning of the string ‘abbb’, as opposed to the substring ‘bbb’,
since a null match is the only left-most match.
\{n,m\}
\{n,\}
\{n\}
\<
\>
Matches the single character regular expression or subexpression immediately preceding it at
least n and at most m times. If m is omitted, then it matches at least n times. If the comma is
also omitted, then it matches exactly n times. If any of these forms occurs first in a regular
expression or subexpression, then it is interpreted literally (i.e., the regular expression ‘\{2\}’
matches the string ‘{2}’, and so on).
Anchors the single character regular expression or subexpression immediately following it to the
beginning (\<) or ending (\>) of a word, i.e., in ASCII, a maximal string of alphanumeric characters, including the underscore (_).
The following extended operators are preceded by a backslash (\) to distinguish them from traditional ed
syntax.
\‘
\’
96
Unconditionally matches the beginning (\‘) or ending (\’) of a line.
\?
Optionally matches the single character regular expression or subexpression immediately preceding it. For example, the regular expression ‘a[bd]\?c’ matches the strings ‘abc’, ‘adc’ and ‘ac’. If
\? occurs at the beginning of a regular expressions or subexpression, then it matches a literal ‘?’.
\+
Matches the single character regular expression or subexpression immediately preceding it one or
more times. So the regular expression ‘a+’ is shorthand for ‘aa∗’. If \+ occurs at the beginning
of a regular expression or subexpression, then it matches a literal ‘+’.
\b
Matches the beginning or ending (null string) of a word. Thus the regular expression ‘\bhello\b’
is equivalent to ‘\<hello\>’. However, ‘\b\b’ is a valid regular expression whereas ‘\<\>’ is not.
10 November 1994
ED(1)
ED(1)
\B
Matches (a null string) inside a word.
\w
Matches any character in a word.
\W
Matches any character not in a word.
COMMANDS
All ed commands are single characters, though some require additonal parameters. If a command’s parameters extend over several lines, then each line except for the last must be terminated with a backslash (\).
In general, at most one command is allowed per line. However, most commands accept a print suffix,
which is any of ‘p’ (print), ‘l’ (list) , or ‘n’ (enumerate), to print the last line affected by the command.
An interrupt (typically ˆC) has the effect of aborting the current command and returning the editor to command mode.
ed recognizes the following commands. The commands are shown together with the default address or
address range supplied if none is specified (in parenthesis).
(.)a
Appends text to the buffer after the addressed line, which may be the address 0 (zero). Text is
entered in input mode. The current address is set to last line entered.
(.,.)c
Changes lines in the buffer. The addressed lines are deleted from the buffer, and text is appended
in their place. Text is entered in input mode. The current address is set to last line entered.
(.,.)d
Deletes the addressed lines from the buffer. If there is a line after the deleted range, then the current address is set to this line. Otherwise the current address is set to the line before the deleted
range.
e file
Edits file, and sets the default filename. If file is not specified, then the default filename is used.
Any lines in the buffer are deleted before the new file is read. The current address is set to the
last line read.
e !command
Edits the standard output of ‘!command’, (see !command below). The default filename is
unchanged. Any lines in the buffer are deleted before the output of command is read. The current address is set to the last line read.
E file
Edits file unconditionally. This is similar to the e command, except that unwritten changes are
discarded without warning. The current address is set to the last line read.
f file
Sets the default filename to file. If file is not specified, then the default unescaped filename is
printed.
(1,$)g /re/command-list
Applies command-list to each of the addressed lines matching a regular expression re. The current address is set to the line currently matched before command-list is executed. At the end of
the ‘g’ command, the current address is set to the last line affected by command-list.
Each command in command-list must be on a separate line, and every line except for the last
must be terminated by a backslash (\). Any commands are allowed, except for ‘g’, ‘G’, ‘v’, and
‘V’. A newline alone in command-list is equivalent to a ‘p’ command.
10 November 1994
97
ED(1)
ED(1)
(1,$)G /re/
Interactively edits the addressed lines matching a regular expression re. For each matching line,
the line is printed, the current address is set, and the user is prompted to enter a command-list. At
the end of the ‘G’ command, the current address is set to the last line affected by (the last) command-list.
The format of command-list is the same as that of the ‘g’ command. A newline alone acts as a
null command list. A single ‘&’ repeats the last non-null command list.
H
Toggles the printing of error explanations. By default, explanations are not printed. It is recommended that ed scripts begin with this command to aid in debugging.
h
Prints an explanation of the last error.
(.)i
Inserts text in the buffer before the current line. Text is entered in input mode. The current
address is set to the last line entered.
(.,.+1)j
Joins the addressed lines. The addressed lines are deleted from the buffer and replaced by a single line containing their joined text. The current address is set to the resultant line.
(.)klc
Marks a line with a lower case letter lc. The line can then be addressed as ’lc (i.e., a single quote
followed by lc ) in subsequent commands. The mark is not cleared until the line is deleted or otherwise modified.
(.,.)l
Prints the addressed lines unambiguously. If invoked from a terminal, ed pauses at the end of
each page until a newline is entered. The current address is set to the last line printed.
(.,.)m(.) Moves lines in the buffer. The addressed lines are moved to after the right-hand destination
address, which may be the address 0 (zero). The current address is set to the last line moved.
(.,.)n
Prints the addressed lines along with their line numbers. The current address is set to the last line
printed.
(.,.)p
Prints the addressed lines. If invoked from a terminal, ed pauses at the end of each page until a
newline is entered. The current address is set to the last line printed.
P
Toggles the command prompt on and off. Unless a prompt was specified by with command-line
option -p string, the command prompt is by default turned off.
q
Quits ed.
Q
Quits ed unconditionally. This is similar to the q command, except that unwritten changes are
discarded without warning.
($)r file
Reads file to after the addressed line. If file is not specified, then the default filename is used. If
there was no default filename prior to the command, then the default filename is set to file. Otherwise, the default filename is unchanged. The current address is set to the last line read.
($)r !command
Reads to after the addressed line the standard output of ‘!command’, (see the !command below).
The default filename is unchanged. The current address is set to the last line read.
(.,.)s /re/replacement/
98
10 November 1994
ED(1)
ED(1)
(.,.)s /re/replacement/g
(.,.)s /re/replacement/n
Replaces text in the addressed lines matching a regular expression re with replacement. By
default, only the first match in each line is replaced. If the ‘g’ (global) suffix is given, then every
match to be replaced. The ‘n’ suffix, where n is a postive number, causes only the nth match to
be replaced. It is an error if no substitutions are performed on any of the addressed lines. The
current address is set the last line affected.
re and replacement may be delimited by any character other than space and newline (see the ‘s’
command below). If one or two of the last delimiters is omitted, then the last line affected is
printed as though the print suffix ‘p’ were specified.
An unescaped ‘&’ in replacement is replaced by the currently matched text. The character
sequence ‘\m’, where m is a number in the range [1,9], is replaced by the mth backreference
expression of the matched text. If replacement consists of a single ‘%’, then replacement from
the last substitution is used. Newlines may be embedded in replacement if they are escaped with
a backslash (\).
(.,.)s
Repeats the last substitution. This form of the ‘s’ command accepts a count suffix ‘n’, or any
combination of the characters ‘r’, ‘g’, and ‘p’. If a count suffix ‘n’ is given, then only the nth
match is replaced. The ‘r’ suffix causes the regular expression of the last search to be used
instead of the that of the last substitution. The ‘g’ suffix toggles the global suffix of the last substitution. The ‘p’ suffix toggles the print suffix of the last substitution The current address is set to
the last line affected.
(.,.)t(.)
Copies (i.e., transfers) the addressed lines to after the right-hand destination address, which may
be the address 0 (zero). The current address is set to the last line copied.
u
Undoes the last command and restores the current address to what it was before the command.
The global commands ‘g’, ‘G’, ‘v’, and ‘V’. are treated as a single command by undo. ‘u’ is its
own inverse.
(1,$)v /re/command-list
Applies command-list to each of the addressed lines not matching a regular expression re. This is
similar to the ‘g’ command.
(1,$)V /re/
Interactively edits the addressed lines not matching a regular expression re. This is similar to the
‘G’ command.
(1,$)w file
Writes the addressed lines to file. Any previous contents of file is lost without warning. If there
is no default filename, then the default filename is set to file, otherwise it is unchanged. If no filename is specified, then the default filename is used. The current address is unchanged.
(1,$)wq file
Writes the addressed lines to file, and then executes a ‘q’ command.
(1,$)w !command
Writes the addressed lines to the standard input of ‘!command’, (see the !command below). The
default filename and current address are unchanged.
10 November 1994
99
ED(1)
ED(1)
(1,$)W file
Appends the addressed lines to the end of file. This is similar to the ‘w’ command, expect that the
previous contents of file is not clobbered. The current address is unchanged.
(.)x
Copies (puts) the contents of the cut buffer to after the addressed line. The current address is set
to the last line copied.
(.,.)y
Copies (yanks) the addressed lines to the cut buffer. The cut buffer is overwritten by subsequent
‘y’, ‘s’, ‘j’, ‘d’, or ‘c’ commands. The current address is unchanged.
(.+1)zn
Scrolls n lines at a time starting at addressed line. If n is not specified, then the current window
size is used. The current address is set to the last line printed.
!command
Executes command via sh(1). If the first character of command is ‘!’, then it is replaced by text
of the previous ‘!command’. ed does not process command for backslash (\) escapes. However,
an unescaped ‘%’ is replaced by the default filename. When the shell returns from execution, a
‘!’ is printed to the standard output. The current line is unchanged.
(.,.)#
Begins a comment; the rest of the line, up to a newline, is ignored. If a line address followed by
a semicolon is given, then the current address is set to that address. Otherwise, the current
address is unchanged.
($)=
Prints the line number of the addressed line.
(.+1)newline
Prints the addressed line, and sets the current address to that line.
FILES
/tmp/ed.∗
ed.hup
Buffer file
The file to which ed attempts to write the buffer if the terminal hangs up.
SEE ALSO
vi(1), sed(1), regex(3), sh(1).
USD:12-13
B. W. Kernighan and P. J. Plauger, Software Tools in Pascal , Addison-Wesley, 1981.
LIMITATIONS
ed processes file arguments for backslash escapes, i.e., in a filename, any characters preceded by a backslash (\) are interpreted literally.
If a text (non-binary) file is not terminated by a newline character, then ed appends one on reading/writing
it. In the case of a binary file, ed does not append a newline on reading/writing.
per line overhead: 4 ints
DIAGNOSTICS
When an error occurs, if ed’s input is from a regular file or here document, then it exits, otherwise it prints a
‘?’ and returns to command mode. An explanation of the last error can be printed with the ‘h’ (help) command.
Attempting to quit ed or edit another file before writing a modified buffer results in an error. If the
100
10 November 1994
ED(1)
ED(1)
command is entered a second time, it succeeds, but any changes to the buffer are lost.
ed exits with 0 if no errors occurred; otherwise >0.
10 November 1994
101
GAWK(1)
Utility Commands
GAWK(1)
NAME
gawk − pattern scanning and processing language
SYNOPSIS
gawk [ POSIX or GNU style options ] −f program-file [ −− ] file ...
gawk [ POSIX or GNU style options ] [ −− ] program-text file ...
DESCRIPTION
Gawk is the GNU Project’s implementation of the AWK programming language. It conforms to the definition of the language in the POSIX 1003.2 Command Language And Utilities Standard. This version in turn
is based on the description in The AWK Programming Language, by Aho, Kernighan, and Weinberger, with
the additional features found in the System V Release 4 version of UNIX awk. Gawk also provides more
recent Bell Labs awk extensions, and some GNU-specific extensions.
The command line consists of options to gawk itself, the AWK program text (if not supplied via the −f or
−−file options), and values to be made available in the ARGC and ARGV pre-defined AWK variables.
OPTION FORMAT
Gawk options may be either the traditional POSIX one letter options, or the GNU style long options. POSIX
options start with a single ‘‘−’’, while long options start with ‘‘− −’’. Long options are provided for both
GNU-specific features and for POSIX mandated features.
Following the POSIX standard, gawk-specific options are supplied via arguments to the −W option. Multiple −W options may be supplied Each −W option has a corresponding long option, as detailed below.
Arguments to long options are either joined with the option by an = sign, with no intervening spaces, or
they may be provided in the next command line argument. Long options may be abbreviated, as long as the
abbreviation remains unique.
OPTIONS
Gawk accepts the following options.
−F fs
−−field-separator fs
Use fs for the input field separator (the value of the FS predefined variable).
−v var=val
−−assign var=val
Assign the value val, to the variable var, before execution of the program begins. Such variable
values are available to the BEGIN block of an AWK program.
−f program-file
−−file program-file
Read the AWK program source from the file program-file, instead of from the first command line
argument. Multiple −f (or −−file) options may be used.
−mf NNN
−mr NNN
Set various memory limits to the value NNN . The f flag sets the maximum number of fields, and
the r flag sets the maximum record size. These two flags and the −m option are from the Bell
Labs research version of UNIX awk. They are ignored by gawk, since gawk has no pre-defined
limits.
−W traditional
−W compat
−−traditional
−−compat
Run in compatibility mode. In compatibility mode, gawk behaves identically to UNIX awk; none
of the GNU-specific extensions are recognized. The use of −−traditional is preferred over the
other forms of this option. See GNU EXTENSIONS, below, for more information.
102
Apr 28 1999
Free Software Foundation
GAWK(1)
Utility Commands
GAWK(1)
−W copyleft
−W copyright
−−copyleft
−−copyright
Print the short version of the GNU copyright information message on the standard output, and
exits successfully.
−W help
−W usage
−−help
−−usage
Print a relatively short summary of the available options on the standard output. (Per the GNU
Coding Standards, these options cause an immediate, successful exit.)
−W lint
−−lint Provide warnings about constructs that are dubious or non-portable to other AWK implementations.
−W lint−old
−−lint−old
Provide warnings about constructs that are not portable to the original version of Unix awk.
−W posix
−−posix
This turns on compatibility mode, with the following additional restrictions:
• \x escape sequences are not recognized.
• Only space and tab act as field separators when FS is set to a single space, newline does not.
• The synonym func for the keyword function is not recognized.
• The operators ∗∗ and ∗∗= cannot be used in place of ˆ and ˆ=.
• The fflush() function is not available.
−W re−interval
−−re−interval
Enable the use of interval expressions in regular expression matching (see Regular Expressions,
below). Interval expressions were not traditionally available in the AWK language. The POSIX
standard added them, to make awk and egrep consistent with each other. However, their use is
likely to break old AWK programs, so gawk only provides them if they are requested with this
option, or when −−posix is specified.
−W source program-text
−−source program-text
Use program-text as AWK program source code. This option allows the easy intermixing of
library functions (used via the −f and −−file options) with source code entered on the command
line. It is intended primarily for medium to large AWK programs used in shell scripts.
−W version
−−version
Print version information for this particular copy of gawk on the standard output. This is useful
mainly for knowing if the current copy of gawk on your system is up to date with respect to whatever the Free Software Foundation is distributing. This is also useful when reporting bugs. (Per
the GNU Coding Standards, these options cause an immediate, successful exit.)
−−
Signal the end of options. This is useful to allow further arguments to the AWK program itself to
start with a ‘‘−’’. This is mainly for consistency with the argument parsing convention used by
most other POSIX programs.
In compatibility mode, any other options are flagged as illegal, but are otherwise ignored. In normal operation, as long as program text has been supplied, unknown options are passed on to the AWK program in the
Free Software Foundation
Apr 28 1999
103
GAWK(1)
Utility Commands
GAWK(1)
ARGV array for processing. This is particularly useful for running AWK programs via the ‘‘#!’’
executable interpreter mechanism.
AWK PROGRAM EXECUTION
An AWK program consists of a sequence of pattern-action statements and optional function definitions.
pattern { action statements }
function name(parameter list) { statements }
Gawk first reads the program source from the program-file(s) if specified, from arguments to −−source, or
from the first non-option argument on the command line. The −f and −−source options may be used multiple times on the command line. Gawk will read the program text as if all the program-files and command
line source texts had been concatenated together. This is useful for building libraries of AWK functions,
without having to include them in each new AWK program that uses them. It also provides the ability to
mix library functions with command line programs.
The environment variable AWKPATH specifies a search path to use when finding source files named with
the −f option. If this variable does not exist, the default path is ".:/usr/local/share/awk". (The actual
directory may vary, depending upon how gawk was built and installed.) If a file name given to the −f
option contains a ‘‘/’’ character, no path search is performed.
Gawk executes AWK programs in the following order. First, all variable assignments specified via the −v
option are performed. Next, gawk compiles the program into an internal form. Then, gawk executes the
code in the BEGIN block(s) (if any), and then proceeds to read each file named in the ARGV array. If
there are no files named on the command line, gawk reads the standard input.
If a filename on the command line has the form var=val it is treated as a variable assignment. The variable
var will be assigned the value val. (This happens after any BEGIN block(s) have been run.) Command
line variable assignment is most useful for dynamically assigning values to the variables AWK uses to control how input is broken into fields and records. It is also useful for controlling state if multiple passes are
needed over a single data file.
If the value of a particular element of ARGV is empty (""), gawk skips over it.
For each record in the input, gawk tests to see if it matches any pattern in the AWK program. For each
pattern that the record matches, the associated action is executed. The patterns are tested in the order they
occur in the program.
Finally, after all the input is exhausted, gawk executes the code in the END block(s) (if any).
VARIABLES, RECORDS AND FIELDS
AWK variables are dynamic; they come into existence when they are first used. Their values are either
floating-point numbers or strings, or both, depending upon how they are used. AWK also has one dimensional arrays; arrays with multiple dimensions may be simulated. Several pre-defined variables are set as a
program runs; these will be described as needed and summarized below.
Records
Normally, records are separated by newline characters. You can control how records are separated by
assigning values to the built-in variable RS. If RS is any single character, that character separates records.
Otherwise, RS is a regular expression. Text in the input that matches this regular expression will separate
the record. However, in compatibility mode, only the first character of its string value is used for separating
records. If RS is set to the null string, then records are separated by blank lines. When RS is set to the null
string, the newline character always acts as a field separator, in addition to whatever value FS may have.
Fields
As each input record is read, gawk splits the record into fields, using the value of the FS variable as the
field separator. If FS is a single character, fields are separated by that character. If FS is the null string,
then each individual character becomes a separate field. Otherwise, FS is expected to be a full regular
expression. In the special case that FS is a single space, fields are separated by runs of spaces and/or tabs
and/or newlines. (But see the discussion of −−posix, below). Note that the value of IGNORECASE (see
below) will also affect how fields are split when FS is a regular expression, and how records are separated
when RS is a regular expression.
104
Apr 28 1999
Free Software Foundation
GAWK(1)
Utility Commands
GAWK(1)
If the FIELDWIDTHS variable is set to a space separated list of numbers, each field is expected to have
fixed width, and gawk will split up the record using the specified widths. The value of FS is ignored.
Assigning a new value to FS overrides the use of FIELDWIDTHS, and restores the default behavior.
Each field in the input record may be referenced by its position, $1, $2, and so on. $0 is the whole record.
The value of a field may be assigned to as well. Fields need not be referenced by constants:
n=5
print $n
prints the fifth field in the input record. The variable NF is set to the total number of fields in the input
record.
References to non-existent fields (i.e. fields after $NF) produce the null-string. However, assigning to a
non-existent field (e.g., $(NF+2) = 5) will increase the value of NF, create any intervening fields with the
null string as their value, and cause the value of $0 to be recomputed, with the fields being separated by the
value of OFS. References to negative numbered fields cause a fatal error. Decrementing NF causes the
values of fields past the new value to be lost, and the value of $0 to be recomputed, with the fields being
separated by the value of OFS.
Built-in Variables
Gawk’s built-in variables are:
ARGC
The number of command line arguments (does not include options to gawk, or the program source).
ARGIND
The index in ARGV of the current file being processed.
ARGV
Array of command line arguments. The array is indexed from 0 to ARGC − 1. Dynamically changing the contents of ARGV can control the files used for data.
CONVFMT
The conversion format for numbers, "%.6g", by default.
ENVIRON
An array containing the values of the current environment. The array is indexed by the
environment variables, each element being the value of that variable (e.g., ENVIRON["HOME"] might be /home/arnold). Changing this array does not affect the
environment seen by programs which gawk spawns via redirection or the system() function. (This may change in a future version of gawk.)
ERRNO
If a system error occurs either doing a redirection for getline, during a read for getline,
or during a close(), then ERRNO will contain a string describing the error.
FIELDWIDTHS A white-space separated list of fieldwidths. When set, gawk parses the input into fields
of fixed width, instead of using the value of the FS variable as the field separator. The
fixed field width facility is still experimental; the semantics may change as gawk evolves
over time.
FILENAME
The name of the current input file. If no files are specified on the command line, the
value of FILENAME is ‘‘−’’. However, FILENAME is undefined inside the BEGIN
block.
FNR
The input record number in the current input file.
FS
The input field separator, a space by default. See Fields, above.
IGNORECASE Controls the case-sensitivity of all regular expression and string operations. If
IGNORECASE has a non-zero value, then string comparisons and pattern matching in
rules, field splitting with FS, record separating with RS, regular expression matching
with ˜ and !˜, and the gensub(), gsub(), index(), match(), split(), and sub() pre-defined
functions will all ignore case when doing regular expression operations. Thus, if
IGNORECASE is not equal to zero, /aB/ matches all of the strings "ab", "aB", "Ab",
and "AB". As with all AWK variables, the initial value of IGNORECASE is zero, so
all regular expression and string operations are normally case-sensitive. Under Unix, the
full ISO 8859-1 Latin-1 character set is used when ignoring case. NOTE: In versions of
Free Software Foundation
Apr 28 1999
105
GAWK(1)
Utility Commands
GAWK(1)
gawk prior to 3.0, IGNORECASE only affected regular expression operations. It now
affects string comparisons as well.
NF
The number of fields in the current input record.
NR
The total number of input records seen so far.
OFMT
The output format for numbers, "%.6g", by default.
OFS
The output field separator, a space by default.
ORS
The output record separator, by default a newline.
RS
The input record separator, by default a newline.
RT
The record terminator. Gawk sets RT to the input text that matched the character or regular expression specified by RS.
RSTART
The index of the first character matched by match(); 0 if no match.
RLENGTH
The length of the string matched by match(); −1 if no match.
SUBSEP
The character used to separate multiple subscripts in array elements, by default "\034".
Arrays
Arrays are subscripted with an expression between square brackets ([ and ]). If the expression is an expression list (expr, expr ...) then the array subscript is a string consisting of the concatenation of the (string)
value of each expression, separated by the value of the SUBSEP variable. This facility is used to simulate
multiply dimensioned arrays. For example:
i = "A"; j = "B"; k = "C"
x[i, j, k] = "hello, world\n"
assigns the string "hello, world\n" to the element of the array x which is indexed by the string
"A\034B\034C". All arrays in AWK are associative, i.e. indexed by string values.
The special operator in may be used in an if or while statement to see if an array has an index consisting of
a particular value.
if (val in array)
print array[val]
If the array has multiple subscripts, use (i, j) in array.
The in construct may also be used in a for loop to iterate over all the elements of an array.
An element may be deleted from an array using the delete statement. The delete statement may also be
used to delete the entire contents of an array, just by specifying the array name without a subscript.
Variable Typing And Conversion
Variables and fields may be (floating point) numbers, or strings, or both. How the value of a variable is
interpreted depends upon its context. If used in a numeric expression, it will be treated as a number, if used
as a string it will be treated as a string.
To force a variable to be treated as a number, add 0 to it; to force it to be treated as a string, concatenate it
with the null string.
When a string must be converted to a number, the conversion is accomplished using atof (3). A number is
converted to a string by using the value of CONVFMT as a format string for sprintf (3), with the numeric
value of the variable as the argument. However, even though all numbers in AWK are floating-point, integral values are always converted as integers. Thus, given
CONVFMT = "%2.2f"
a = 12
b = a ""
the variable b has a string value of "12" and not "12.00".
Gawk performs comparisons as follows: If two variables are numeric, they are compared numerically. If
106
Apr 28 1999
Free Software Foundation
GAWK(1)
Utility Commands
GAWK(1)
one value is numeric and the other has a string value that is a ‘‘numeric string,’’ then comparisons are also
done numerically. Otherwise, the numeric value is converted to a string and a string comparison is performed. Two strings are compared, of course, as strings. According to the POSIX standard, even if two
strings are numeric strings, a numeric comparison is performed. However, this is clearly incorrect, and
gawk does not do this.
Note that string constants, such as "57", are not numeric strings, they are string constants. The idea of
‘‘numeric string’’ only applies to fields, getline input, FILENAME, ARGV elements, ENVIRON elements and the elements of an array created by split() that are numeric strings. The basic idea is that user
input, and only user input, that looks numeric, should be treated that way.
Uninitialized variables have the numeric value 0 and the string value "" (the null, or empty, string).
PATTERNS AND ACTIONS
AWK is a line oriented language. The pattern comes first, and then the action. Action statements are
enclosed in { and }. Either the pattern may be missing, or the action may be missing, but, of course, not
both. If the pattern is missing, the action will be executed for every single record of input. A missing action
is equivalent to
{ print }
which prints the entire record.
Comments begin with the ‘‘#’’ character, and continue until the end of the line. Blank lines may be used to
separate statements. Normally, a statement ends with a newline, however, this is not the case for lines ending in a ‘‘,’’, {, ?, :, &&, or ||. Lines ending in do or else also have their statements automatically continued
on the following line. In other cases, a line can be continued by ending it with a ‘‘\’’, in which case the
newline will be ignored.
Multiple statements may be put on one line by separating them with a ‘‘;’’. This applies to both the statements within the action part of a pattern-action pair (the usual case), and to the pattern-action statements
themselves.
Patterns
AWK patterns may be one of the following:
BEGIN
END
/regular expression/
relational expression
pattern && pattern
pattern || pattern
pattern ? pattern : pattern
( pattern)
! pattern
pattern1, pattern2
BEGIN and END are two special kinds of patterns which are not tested against the input. The action parts
of all BEGIN patterns are merged as if all the statements had been written in a single BEGIN block. They
are executed before any of the input is read. Similarly, all the END blocks are merged, and executed when
all the input is exhausted (or when an exit statement is executed). BEGIN and END patterns cannot be
combined with other patterns in pattern expressions. BEGIN and END patterns cannot have missing action
parts.
For /regular expression/ patterns, the associated statement is executed for each input record that matches
the regular expression. Regular expressions are the same as those in egrep(1), and are summarized below.
A relational expression may use any of the operators defined below in the section on actions. These generally test whether certain fields match certain regular expressions.
The &&, ||, and ! operators are logical AND, logical OR, and logical NOT, respectively, as in C. They do
short-circuit evaluation, also as in C, and are used for combining more primitive pattern expressions. As in
Free Software Foundation
Apr 28 1999
107
GAWK(1)
Utility Commands
GAWK(1)
most languages, parentheses may be used to change the order of evaluation.
The ?: operator is like the same operator in C. If the first pattern is true then the pattern used for testing is
the second pattern, otherwise it is the third. Only one of the second and third patterns is evaluated.
The pattern1, pattern2 form of an expression is called a range pattern. It matches all input records starting
with a record that matches pattern1, and continuing until a record that matches pattern2, inclusive. It does
not combine with any other sort of pattern expression.
Regular Expressions
Regular expressions are the extended kind found in egrep. They are composed of characters as follows:
c
matches the non-metacharacter c.
\c
matches the literal character c.
.
matches any character including newline.
ˆ
matches the beginning of a string.
$
matches the end of a string.
[abc...]
character list, matches any of the characters abc....
[ˆabc...] negated character list, matches any character except abc....
r1|r2
alternation: matches either r1 or r2.
r1r2
concatenation: matches r1, and then r2.
r+
matches one or more r’s.
r∗
matches zero or more r’s.
r?
matches zero or one r’s.
(r)
grouping: matches r.
r{n}
r{n,}
r{n,m}
One or two numbers inside braces denote an interval expression. If there is one number in the
braces, the preceding regexp r is repeated n times. If there are two numbers separated by a
comma, r is repeated n to m times. If there is one number followed by a comma, then r is
repeated at least n times.
Interval expressions are only available if either −−posix or −−re−interval is specified on the
command line.
\y
matches the empty string at either the beginning or the end of a word.
\B
matches the empty string within a word.
\<
matches the empty string at the beginning of a word.
\>
matches the empty string at the end of a word.
\w
matches any word-constituent character (letter, digit, or underscore).
\W
matches any character that is not word-constituent.
\‘
matches the empty string at the beginning of a buffer (string).
\’
matches the empty string at the end of a buffer.
The escape sequences that are valid in string constants (see below) are also legal in regular expressions.
Character classes are a new feature introduced in the POSIX standard. A character class is a special notation for describing lists of characters that have a specific attribute, but where the actual characters themselves can vary from country to country and/or from character set to character set. For example, the notion
of what is an alphabetic character differs in the USA and in France.
A character class is only valid in a regexp inside the brackets of a character list. Character classes consist
108
Apr 28 1999
Free Software Foundation
GAWK(1)
Utility Commands
GAWK(1)
of [:, a keyword denoting the class, and :]. Here are the character classes defined by the POSIX standard.
[:alnum:]
Alphanumeric characters.
[:alpha:]
Alphabetic characters.
[:blank:]
Space or tab characters.
[:cntrl:]
Control characters.
[:digit:]
Numeric characters.
[:graph:]
Characters that are both printable and visible. (A space is printable, but not visible, while an a is
both.)
[:lower:]
Lower-case alphabetic characters.
[:print:]
Printable characters (characters that are not control characters.)
[:punct:]
Punctuation characters (characters that are not letter, digits, control characters, or space characters).
[:space:]
Space characters (such as space, tab, and formfeed, to name a few).
[:upper:]
Upper-case alphabetic characters.
[:xdigit:]
Characters that are hexadecimal digits.
For example, before the POSIX standard, to match alphanumeric characters, you would have had to write
/[A−Za−z0−9]/. If your character set had other alphabetic characters in it, this would not match them.
With the POSIX character classes, you can write /[[:alnum:]]/, and this will match all the alphabetic and
numeric characters in your character set.
Two additional special sequences can appear in character lists. These apply to non-ASCII character sets,
which can have single symbols (called collating elements) that are represented with more than one character, as well as several characters that are equivalent for collating, or sorting, purposes. (E.g., in French, a
plain ‘‘e’’ and a grave-accented e` are equivalent.)
Collating Symbols
A collating symbols is a multi-character collating element enclosed in [. and .]. For example, if
ch is a collating element, then [[.ch.]] is a regexp that matches this collating element, while [ch] is
a regexp that matches either c or h.
Equivalence Classes
An equivalence class is a locale-specific name for a list of characters that are equivalent. The name
is enclosed in [= and =]. For example, the name e might be used to represent all of ‘‘e,’’ ‘‘e`,’’ and
‘‘e`.’’ In this case, [[=e]] is a regexp that matches any of
.BR e ,
.BR e´ , or
.BR e` .
These features are very valuable in non-English speaking locales. The library functions that gawk uses for
regular expression matching currently only recognize POSIX character classes; they do not recognize
Free Software Foundation
Apr 28 1999
109
GAWK(1)
Utility Commands
GAWK(1)
collating symbols or equivalence classes.
The \y, \B, \<, \>, \w, \W, \‘, and \’ operators are specific to gawk; they are extensions based on facilities in
the GNU regexp libraries.
The various command line options control how gawk interprets characters in regexps.
No options
In the default case, gawk provide all the facilities of POSIX regexps and the GNU regexp operators described above. However, interval expressions are not supported.
−−posix
Only POSIX regexps are supported, the GNU operators are not special. (E.g., \w matches a literal
w). Interval expressions are allowed.
−−traditional
Traditional Unix awk regexps are matched. The GNU operators are not special, interval expressions are not available, and neither are the POSIX character classes ([[:alnum:]] and so on). Characters described by octal and hexadecimal escape sequences are treated literally, even if they represent regexp metacharacters.
−−re−interval
Allow interval expressions in regexps, even if −−traditional has been provided.
Actions
Action statements are enclosed in braces, { and }. Action statements consist of the usual assignment, conditional, and looping statements found in most languages. The operators, control statements, and input/output
statements available are patterned after those in C.
Operators
The operators in AWK, in order of decreasing precedence, are
110
(...)
Grouping
$
Field reference.
++ −−
Increment and decrement, both prefix and postfix.
ˆ
Exponentiation (∗∗ may also be used, and ∗∗= for the assignment operator).
+−!
Unary plus, unary minus, and logical negation.
∗/%
Multiplication, division, and modulus.
+−
Addition and subtraction.
space
String concatenation.
<>
<= >=
!= ==
The regular relational operators.
˜ !˜
Regular expression match, negated match. NOTE: Do not use a constant regular expression
(/foo/) on the left-hand side of a ˜ or !˜. Only use one on the right-hand side. The expression
/foo/ ˜ exp has the same meaning as (($0 ˜ /foo/) ˜ exp). This is usually not what was
intended.
in
Array membership.
&&
Logical AND.
||
Logical OR.
?:
The C conditional expression. This has the form expr1 ? expr2 : expr3. If expr1 is true, the
value of the expression is expr2, otherwise it is expr3. Only one of expr2 and expr3 is evaluated.
Apr 28 1999
Free Software Foundation
GAWK(1)
Utility Commands
GAWK(1)
= += −=
∗= /= %= ˆ= Assignment. Both absolute assignment (var = value) and operator-assignment (the other
forms) are supported.
Control Statements
The control statements are as follows:
if (condition) statement [ else statement ]
while (condition) statement
do statement while (condition)
for (expr1; expr2; expr3) statement
for (var in array) statement
break
continue
delete array[index]
delete array
exit [ expression ]
{ statements }
I/O Statements
The input/output statements are as follows:
close( file)
Close file (or pipe, see below).
getline
Set $0 from next input record; set NF, NR, FNR.
getline < file
Set $0 from next record of file; set NF.
getline var
Set var from next input record; set NR, FNR.
getline var < file
Set var from next record of file.
next
Stop processing the current input record. The next input record is read and processing
starts over with the first pattern in the AWK program. If the end of the input data is
reached, the END block(s), if any, are executed.
nextfile
Stop processing the current input file. The next input record read comes from the next
input file. FILENAME and ARGIND are updated, FNR is reset to 1, and processing
starts over with the first pattern in the AWK program. If the end of the input data is
reached, the END block(s), if any, are executed. NOTE: Earlier versions of gawk
used next file, as two words. While this usage is still recognized, it generates a warning message and will eventually be removed.
print
Prints the current record. The output record is terminated with the value of the ORS
variable.
print expr-list
Prints expressions. Each expression is separated by the value of the OFS variable.
The output record is terminated with the value of the ORS variable.
print expr-list > file
Prints expressions on file. Each expression is separated by the value of the OFS variable. The output record is terminated with the value of the ORS variable.
printf fmt, expr-list Format and print.
printf fmt, expr-list > file
Format and print on file.
system(cmd-line)
Execute the command cmd-line, and return the exit status. (This may not be available
on non-POSIX systems.)
fflush([file])
Flush any buffers associated with the open output file or pipe file. If file is missing,
then standard output is flushed. If file is the null string, then all open output files and
pipes have their buffers flushed.
Free Software Foundation
Apr 28 1999
111
GAWK(1)
Utility Commands
GAWK(1)
Other input/output redirections are also allowed. For print and printf, >> file appends output to the file,
while | command writes on a pipe. In a similar fashion, command | getline pipes into getline. The getline
command will return 0 on end of file, and −1 on an error.
The printf Statement
The AWK versions of the printf statement and sprintf() function (see below) accept the following conversion specification formats:
%c
An ASCII character. If the argument used for %c is numeric, it is treated as a character and
printed. Otherwise, the argument is assumed to be a string, and the only first character of that
string is printed.
%d
%i
A decimal number (the integer part).
%e
%E
A floating point number of the form [−]d.dddddde[+ −]dd. The %E format uses E instead of e.
%f
A floating point number of the form [−]ddd.dddddd.
%g
%G
Use %e or %f conversion, whichever is shorter, with nonsignificant zeros suppressed. The %G
format uses %E instead of %e.
%o
An unsigned octal number (again, an integer).
%s
A character string.
%x
%X
An unsigned hexadecimal number (an integer). %X format uses ABCDEF instead of abcdef.
%%
A single % character; no argument is converted.
There are optional, additional parameters that may lie between the % and the control letter:
−
The expression should be left-justified within its field.
space
For numeric conversions, prefix positive values with a space, and negative values with a minus
sign.
+
The plus sign, used before the width modifier (see below), says to always supply a sign for
numeric conversions, even if the data to be formatted is positive. The + overrides the space modifier.
#
Use an ‘‘alternate form’’ for certain control letters. For %o, supply a leading zero. For %x, and
%X, supply a leading 0x or 0X for a nonzero result. For %e, %E, and %f, the result will always
contain a decimal point. For %g, and %G, trailing zeros are not removed from the result.
0
A leading 0 (zero) acts as a flag, that indicates output should be padded with zeroes instead of spaces. This applies even to non-numeric output formats. This flag only has an effect when the field
width is wider than the value to be printed.
width
The field should be padded to this width. The field is normally padded with spaces. If the 0 flag
has been used, it is padded with zeroes.
. prec
A number that specifies the precision to use when printing. For the %e, %E, and %f formats, this
specifies the number of digits you want printed to the right of the decimal point. For the %g, and
%G formats, it specifies the maximum number of significant digits. For the %d, %o, %i, %u,
%x, and %X formats, it specifies the minimum number of digits to print. For a string, it specifies
the maximum number of characters from the string that should be printed.
The dynamic width and prec capabilities of the ANSI C printf() routines are supported. A ∗ in place of
either the width or prec specifications will cause their values to be taken from the argument list to printf or
sprintf().
112
Apr 28 1999
Free Software Foundation
GAWK(1)
Utility Commands
GAWK(1)
Special File Names
When doing I/O redirection from either print or printf into a file, or via getline from a file, gawk recognizes certain special filenames internally. These filenames allow access to open file descriptors inherited
from gawk’s parent process (usually the shell). Other special filenames provide access to information about
the running gawk process. The filenames are:
/dev/pid
Reading this file returns the process ID of the current process, in decimal, terminated with a
newline.
/dev/ppid
Reading this file returns the parent process ID of the current process, in decimal, terminated
with a newline.
/dev/pgrpid
Reading this file returns the process group ID of the current process, in decimal, terminated
with a newline.
/dev/user
Reading this file returns a single record terminated with a newline. The fields are separated
with spaces. $1 is the value of the getuid(2) system call, $2 is the value of the geteuid(2) system call, $3 is the value of the getgid(2) system call, and $4 is the value of the getegid(2) system call. If there are any additional fields, they are the group IDs returned by getgroups(2).
Multiple groups may not be supported on all systems.
/dev/stdin
The standard input.
/dev/stdout The standard output.
/dev/stderr The standard error output.
/dev/fd/ n
The file associated with the open file descriptor n.
These are particularly useful for error messages. For example:
print "You blew it!" > "/dev/stderr"
whereas you would otherwise have to use
print "You blew it!" | "cat 1>&2"
These file names may also be used on the command line to name data files.
Numeric Functions
AWK has the following pre-defined arithmetic functions:
atan2(y, x)
returns the arctangent of y/x in radians.
cos(expr)
returns the cosine of expr, which is in radians.
exp(expr)
the exponential function.
int(expr)
truncates to integer.
log(expr)
the natural logarithm function.
rand()
returns a random number between 0 and 1.
sin(expr)
returns the sine of expr, which is in radians.
sqrt(expr)
the square root function.
srand([expr]) uses expr as a new seed for the random number generator. If no expr is provided, the time of
day will be used. The return value is the previous seed for the random number generator.
String Functions
Gawk has the following pre-defined string functions:
gensub(r, s, h [, t])
Free Software Foundation
search the target string t for matches of the regular expression r. If h is a string
beginning with g or G, then replace all matches of r with s. Otherwise, h is a number indicating which match of r to replace. If no t is supplied, $0 is used instead.
Within the replacement text s, the sequence \n, where n is a digit from 1 to 9, may
Apr 28 1999
113
GAWK(1)
Utility Commands
GAWK(1)
be used to indicate just the text that matched the n’th parenthesized subexpression.
The sequence \0 represents the entire matched text, as does the character &. Unlike
sub() and gsub(), the modified string is returned as the result of the function, and
the original target string is not changed.
gsub(r, s [, t])
for each substring matching the regular expression r in the string t, substitute the
string s, and return the number of substitutions. If t is not supplied, use $0. An &
in the replacement text is replaced with the text that was actually matched. Use \&
to get a literal &. See AWK Language Programming for a fuller discussion of the
rules for &’s and backslashes in the replacement text of sub(), gsub(), and gensub().
index(s, t)
returns the index of the string t in the string s, or 0 if t is not present.
length([s])
returns the length of the string s, or the length of $0 if s is not supplied.
match(s, r)
returns the position in s where the regular expression r occurs, or 0 if r is not
present, and sets the values of RSTART and RLENGTH.
split(s, a [, r])
splits the string s into the array a on the regular expression r, and returns the number of fields. If r is omitted, FS is used instead. The array a is cleared first. Splitting behaves identically to field splitting, described above.
sprintf( fmt, expr-list)
prints expr-list according to fmt, and returns the resulting string.
sub(r, s [, t])
just like gsub(), but only the first matching substring is replaced.
substr(s, i [, n])
returns the at most n-character substring of s starting at i. If n is omitted, the rest of
s is used.
tolower(str)
returns a copy of the string str, with all the upper-case characters in str translated to
their corresponding lower-case counterparts. Non-alphabetic characters are left
unchanged.
toupper(str)
returns a copy of the string str, with all the lower-case characters in str translated to
their corresponding upper-case counterparts. Non-alphabetic characters are left
unchanged.
Time Functions
Since one of the primary uses of AWK programs is processing log files that contain time stamp information, gawk provides the following two functions for obtaining time stamps and formatting them.
systime() returns the current time of day as the number of seconds since the Epoch (Midnight UTC, January 1, 1970 on POSIX systems).
strftime([format [, timestamp]])
formats timestamp according to the specification in format. The timestamp should be of the
same form as returned by systime(). If timestamp is missing, the current time of day is used. If
format is missing, a default format equivalent to the output of date(1) will be used. See the
specification for the strftime() function in ANSI C for the format conversions that are guaranteed
to be available. A public-domain version of strftime(3) and a man page for it come with gawk; if
that version was used to build gawk, then all of the conversions described in that man page are
available to gawk.
String Constants
String constants in AWK are sequences of characters enclosed between double quotes ("). Within strings,
certain escape sequences are recognized, as in C. These are:
114
\\
A literal backslash.
\a
The ‘‘alert’’ character; usually the ASCII BEL character.
\b
backspace.
Apr 28 1999
Free Software Foundation
GAWK(1)
Utility Commands
\f
form-feed.
\n
newline.
\r
carriage return.
\t
horizontal tab.
\v
vertical tab.
GAWK(1)
\xhex digits
The character represented by the string of hexadecimal digits following the \x. As in ANSI C, all following hexadecimal digits are considered part of the escape sequence. (This feature should tell us
something about language design by committee.) E.g., "\x1B" is the ASCII ESC (escape) character.
\ddd The character represented by the 1-, 2-, or 3-digit sequence of octal digits. E.g. "\033" is the ASCII
ESC (escape) character.
\c
The literal character c.
The escape sequences may also be used inside constant regular expressions (e.g., /[ \t\f\n\r\v]/ matches
whitespace characters).
In compatibility mode, the characters represented by octal and hexadecimal escape sequences are treated
literally when used in regexp constants. Thus, /a\52b/ is equivalent to /a\∗b/.
FUNCTIONS
Functions in AWK are defined as follows:
function name(parameter list) { statements }
Functions are executed when they are called from within expressions in either patterns or actions. Actual
parameters supplied in the function call are used to instantiate the formal parameters declared in the function. Arrays are passed by reference, other variables are passed by value.
Since functions were not originally part of the AWK language, the provision for local variables is rather
clumsy: They are declared as extra parameters in the parameter list. The convention is to separate local
variables from real parameters by extra spaces in the parameter list. For example:
function f(p, q,
{
.....
}
/abc/
a, b)
# a & b are local
{ ... ; f(1, 2) ; ... }
The left parenthesis in a function call is required to immediately follow the function name, without any
intervening white space. This is to avoid a syntactic ambiguity with the concatenation operator. This
restriction does not apply to the built-in functions listed above.
Functions may call each other and may be recursive. Function parameters used as local variables are initialized to the null string and the number zero upon function invocation.
Use return expr to return a value from a function. The return value is undefined if no value is provided, or
if the function returns by ‘‘falling off’’ the end.
If −−lint has been provided, gawk will warn about calls to undefined functions at parse time, instead of at
run time. Calling an undefined function at run time is a fatal error.
The word func may be used in place of function.
EXAMPLES
Print and sort the login names of all users:
BEGIN { FS = ":" }
{ print $1 | "sort" }
Free Software Foundation
Apr 28 1999
115
GAWK(1)
Utility Commands
GAWK(1)
Count lines in a file:
END
{ nlines++ }
{ print nlines }
Precede each line by its number in the file:
{ print FNR, $0 }
Concatenate and line number (a variation on a theme):
{ print NR, $0 }
SEE ALSO
egrep(1), getpid(2), getppid(2), getpgrp(2), getuid(2), geteuid(2), getgid(2), getegid(2), getgroups(2)
The AWK Programming Language, Alfred V. Aho, Brian W. Kernighan, Peter J. Weinberger, Addison-Wesley, 1988. ISBN 0-201-07981-X.
AWK Language Programming, Edition 1.0, published by the Free Software Foundation, 1995.
POSIX COMPATIBILITY
A primary goal for gawk is compatibility with the POSIX standard, as well as with the latest version of
UNIX awk. To this end, gawk incorporates the following user visible features which are not described in
the AWK book, but are part of the Bell Labs version of awk, and are in the POSIX standard.
The −v option for assigning variables before program execution starts is new. The book indicates that command line variable assignment happens when awk would otherwise open the argument as a file, which is
after the BEGIN block is executed. However, in earlier implementations, when such an assignment
appeared before any file names, the assignment would happen before the BEGIN block was run. Applications came to depend on this ‘‘feature.’’ When awk was changed to match its documentation, this option
was added to accommodate applications that depended upon the old behavior. (This feature was agreed
upon by both the AT&T and GNU developers.)
The −W option for implementation specific features is from the POSIX standard.
When processing arguments, gawk uses the special option ‘‘−−’’ to signal the end of arguments. In compatibility mode, it will warn about, but otherwise ignore, undefined options. In normal operation, such
arguments are passed on to the AWK program for it to process.
The AWK book does not define the return value of srand(). The POSIX standard has it return the seed it
was using, to allow keeping track of random number sequences. Therefore srand() in gawk also returns its
current seed.
Other new features are: The use of multiple −f options (from MKS awk); the ENVIRON array; the \a, and
\v escape sequences (done originally in gawk and fed back into AT&T’s); the tolower() and toupper()
built-in functions (from AT&T); and the ANSI C conversion specifications in printf (done first in AT&T’s
version).
GNU EXTENSIONS
Gawk has a number of extensions to POSIX awk. They are described in this section. All the extensions
described here can be disabled by invoking gawk with the −−traditional option.
The following features of gawk are not available in POSIX awk.
• The \x escape sequence. (Disabled with −−posix.)
• The fflush() function. (Disabled with −−posix.)
• The systime(), strftime(), and gensub() functions.
• The special file names available for I/O redirection are not recognized.
116
Apr 28 1999
Free Software Foundation
GAWK(1)
Utility Commands
GAWK(1)
• The ARGIND, ERRNO, and RT variables are not special.
• The IGNORECASE variable and its side-effects are not available.
• The FIELDWIDTHS variable and fixed-width field splitting.
• The use of RS as a regular expression.
• The ability to split out individual characters using the null string as the value of FS, and as the
third argument to split().
• No path search is performed for files named via the −f option. Therefore the AWKPATH environment variable is not special.
• The use of nextfile to abandon processing of the current input file.
• The use of delete array to delete the entire contents of an array.
The AWK book does not define the return value of the close() function. Gawk’s close() returns the value
from fclose(3), or pclose(3), when closing a file or pipe, respectively.
When gawk is invoked with the −−traditional option, if the fs argument to the −F option is ‘‘t’’, then FS
will be set to the tab character. Note that typing gawk −F\t ... simply causes the shell to quote the ‘‘t,’’,
and does not pass ‘‘\t’’ to the −F option. Since this is a rather ugly special case, it is not the default behavior. This behavior also does not occur if −−posix has been specified. To really get a tab character as the
field separator, it is best to use quotes: gawk −F’\t’ ....
HISTORICAL FEATURES
There are two features of historical AWK implementations that gawk supports. First, it is possible to call
the length() built-in function not only with no argument, but even without parentheses! Thus,
a = length
# Holy Algol 60, Batman!
is the same as either of
a = length()
a = length($0)
This feature is marked as ‘‘deprecated’’ in the POSIX standard, and gawk will issue a warning about its use
if −−lint is specified on the command line.
The other feature is the use of either the continue or the break statements outside the body of a while, for,
or do loop. Traditional AWK implementations have treated such usage as equivalent to the next statement.
Gawk will support this usage if −−traditional has been specified.
ENVIRONMENT VARIABLES
If POSIXLY_CORRECT exists in the environment, then gawk behaves exactly as if −−posix had been
specified on the command line. If −−lint has been specified, gawk will issue a warning message to this
effect.
The AWKPATH environment variable can be used to provide a list of directories that gawk will search
when looking for files named via the −f and −−file options.
BUGS
The −F option is not necessary given the command line variable assignment feature; it remains only for
backwards compatibility.
If your system actually has support for /dev/fd and the associated /dev/stdin, /dev/stdout, and /dev/stderr
files, you may get different output from gawk than you would get on a system without those files. When
gawk interprets these files internally, it synchronizes output to the standard output with output to /dev/stdout, while on a system with those files, the output is actually to different open files. Caveat Emptor.
Syntactically invalid single character programs tend to overflow the parse stack, generating a rather unhelpful message. Such programs are surprisingly difficult to diagnose in the completely general case, and the
effort to do so really is not worth it.
Free Software Foundation
Apr 28 1999
117
GAWK(1)
Utility Commands
GAWK(1)
VERSION INFORMATION
This man page documents gawk, version 3.0.4.
AUTHORS
The original version of UNIX awk was designed and implemented by Alfred Aho, Peter Weinberger, and
Brian Kernighan of AT&T Bell Labs. Brian Kernighan continues to maintain and enhance it.
Paul Rubin and Jay Fenlason, of the Free Software Foundation, wrote gawk, to be compatible with the original version of awk distributed in Seventh Edition UNIX. John Woods contributed a number of bug fixes.
David Trueman, with contributions from Arnold Robbins, made gawk compatible with the new version of
UNIX awk. Arnold Robbins is the current maintainer.
The initial DOS port was done by Conrad Kwok and Scott Garfinkle. Scott Deifik is the current DOS
maintainer. Pat Rankin did the port to VMS, and Michal Jaegermann did the port to the Atari ST. The port
to OS/2 was done by Kai Uwe Rommel, with contributions and help from Darrel Hankerson. Fred Fish
supplied support for the Amiga.
BUG REPORTS
If you find a bug in gawk, please send electronic mail to [email protected], with a carbon copy to
[email protected]. Please include your operating system and its revision, the version of gawk, what C compiler you used to compile it, and a test program and data that are as small as possible for reproducing the
problem.
Before sending a bug report, please do two things. First, verify that you have the latest version of gawk.
Many bugs (usually subtle ones) are fixed at each release, and if yours is out of date, the problem may
already have been solved. Second, please read this man page and the reference manual carefully to be sure
that what you think is a bug really is, instead of just a quirk in the language.
Whatever you do, do NOT post a bug report in comp.lang.awk. While the gawk developers occasionally
read this newsgroup, posting bug reports there is an unreliable way to report bugs. Instead, please use the
electronic mail addresses given above.
ACKNOWLEDGEMENTS
Brian Kernighan of Bell Labs provided valuable assistance during testing and debugging. We thank him.
COPYING PERMISSIONS
Copyright ©) 1996,97,98,99 Free Software Foundation, Inc.
Permission is granted to make and distribute verbatim copies of this manual page provided the copyright
notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual page under the conditions for
verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual page into another language, under
the above conditions for modified versions, except that this permission notice may be stated in a translation
approved by the Foundation.
118
Apr 28 1999
Free Software Foundation
JOIN(1)
Manuel de l’utilisateur Linux
JOIN(1)
NOM
join − Fusionner les lignes de deux fichiers ayant un champ commun.
SYNOPSIS
join [−a 1|2] [−v 1|2] [−e chaîne] [−o liste_champs...] [−t caractère] [−j[1|2] champ] [−1 champ] [−2
champ] fichier_1 fichier_2
join {−−help,−−version}
DESCRIPTION
Cette page de manuel documente la version GNU de join.
join affiche sur la sortie standard une ligne pour chaque paire de lignes d’entrée, l’une provenant de
fichier_1 et l’autre de fichier_2, qui disposent de champs de fusion identiques.
N’importe lequel des deux fichiers (mais pas les deux en même temps) peut être ‘−’ ce qui représente
l’entrée standard.
fichier_1 et fichier_2 doivent être préalablement triés en ordre croissant (pas nécéssairement numérique)
sur leur champ utilisé pour la fusion. Si l’option −t n’est pas précisée, les fichiers doivent être triés en ignorant les blancs en début de ligne, comme sort(1) le fait avec l’option −b.
Les éléments par défaut sont les suivants : Le champ de fusion est le premier champ sur chaque ligne. Les
champs en entrée sont séparés par un ou plusieurs blancs, les blancs en début de ligne étant ignorés. Les
champs en sortie sont séparés par un espace. Chaque ligne de sortie commence par le champ de fusion,
puis les champs restants de fichier_1, enfin, ceux restants de fichier_2.
OPTIONS
−a numéro
Afficher en plus sur la sortie standard une ligne pour chaque ligne du fichier numéro (1 ou 2), qui
ne peut pas être appariée.
−e chaîne
Remplacer les champs de sortie vides (ceux qui manquent dans les entrées) par la chaîne.
−1, −j1 champ
Effectuer la fusion sur le champ (un entier positif) du fichier 1.
−2, −j2 champ
Effectuer la fusion sur le champ (un entier positif) du fichier 2.
−j champ
Equivalent à −1 champ −2 champ.
−o liste_des_champs...
Construire les lignes de sortie en utilisant le format indiqué dans la liste_des_champs. Chaque
élément de la liste_des_champs. consiste en un numéro de fichier (1 ou 2), un point-virgule, et un
numéro de champ (un entier positif). Les éléments de la liste sont séparés par des virgules ou des
espaces. Plusieurs arguments de la liste_de_champs peuvent être fournis en une seule option −o.
Les arguments de toutes les listes indiquées par les options −o sont mises bout a bout.
−t caractère
Utiliser le caractère indiqué comme séparateur de champs, tant en entrée qu’en sortie.
−v numéro
Afficher sur la sortie standard, à la place du résultat habituel, une ligne pour chaque ligne du
fichier numéro (1 ou 2), qui ne peut pas être appariée.
De plus, quand la version GNU de join est invoquée avec un seul argument, les options suivantes sont
reconnues :
−−help Afficher un message d’aide sur la sortie standard et terminer normalement.
FSF
12 Janvier 1997
119
JOIN(1)
Manuel de l’utilisateur Linux
JOIN(1)
−−version
Afficher un numéro de version sur la sortie standard et terminer normalement.
TRADUCTION
Christophe Blaess, 1997.
120
12 Janvier 1997
FSF
SED(1)
SED(1)
NAME
sed − a Stream EDitor
SYNOPSIS
sed [-n] [-V] [--quiet] [--silent] [--version] [--help]
[-e script] [--expression=script]
[-f script-file] [--file=script-file]
[script-if-no-other-script]
[file...]
DESCRIPTION
Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a
file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as
ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed’s
ability to filter text in a pipeline which particularly distinguishes it from other types of editors.
OPTIONS
Sed may be invoked with the following command-line options:
-V
--version
Print out the version of sed that is being run and a copyright notice, then exit.
-h
--help
Print a usage message briefly summarizing these command-line options and the bug-reporting
address, then exit.
-n
--quiet
--silent By default, sed will print out the pattern space at the end of each cycle through the script. These
options disable this automatic printing, and sed will only produce output when explicitly told to
via the p command.
-e script
--expression=script
Add the commands in script to the set of commands to be run while processing the input.
-f script-file
--file=script-file
Add the commands contained in the file script-file to the set of commands to be run while processing the input.
If no -e,-f,--expression, or --file options are given on the command-line, then the first non-option argument
on the command line is taken to be the script to be executed.
If any command-line parameters remain after processing the above, these parameters are interpreted as the
names of input files to be processed. A file name of - refers to the standard input stream. The standard
input will processed if no file names are specified.
Command Synopsis
This is just a brief synopsis of sed commands to serve as a reminder to those who already know sed; other
documentation (such as the texinfo document) must be consulted for fuller descriptions.
Zero-address ‘‘commands’’
: label Label for b and t commands.
GNU Project
1998-05-07
121
SED(1)
SED(1)
#comment
The comment extends until the next newline (or the end of a -e script fragment).
}
The closing bracket of a { } block.
Zero- or One- address commands
=
Print the current line number.
a\
text
Append text, which has each embedded newline preceeded by a backslash.
i\
text
Insert text, which has each embedded newline preceeded by a backslash.
q
Immediately quit the sed script without processing any more input, except that if auto-print is not
diabled the current pattern space will be printed.
r filename
Append text read from filename.
Commands which accept address ranges
{
Begin a block of commands (end with a }).
b label Branch to label; if label is omitted, branch to end of script.
t label
If a s/// has done a successful substitution since the last input line was read and since the last t
command, then branch to label; if label is omitted, branch to end of script.
c\
text
Replace the selected lines with text, which has each embedded newline preceeded by a backslash.
d
Delete pattern space. Start next cycle.
D
Delete up to the first embedded newline in the pattern space. Start next cycle, but skip reading
from the input if there is still data in the pattern space.
hH
Copy/append pattern space to hold space.
gG
Copy/append hold space to pattern space.
x
Exchange the contents of the hold and pattern spaces.
l
List out the current line in a ‘‘visually unambiguous’’ form.
nN
Read/append the next line of input into the pattern space.
p
Print the current pattern space.
P
Print up to the first embedded newline of the current pattern space.
s/regexp/replacement/
Attempt to match regexp against the pattern space. If successful, replace that portion matched
with replacement. The replacement may contain the special character & to refer to that portion of
the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp.
w
filename Write the current pattern space to filename.
y/source/dest/
Transliterate the characters in the pattern space which appear in source to the corresponding character in dest.
Addresses
Sed commands can be given with no addresses, in which case the command will be executed for all input
lines; with one address, in which case the command will only be executed for input lines which match that
address; or with two addresses, in which case the command will be executed for all input lines which match
the inclusive range of lines starting from the first address and continuing to the second address. Three
122
1998-05-07
GNU Project
SED(1)
SED(1)
things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a
comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if
addr2 is a regexp, it will not be tested against the line that addr1 matched.
After the address (or address-range), and before the command, a ! may be inserted, which specifies that the
command shall only be executed if the address (or address-range) does not match.
The following address types are supported:
number
Match only the specified line number.
first˜step
Match every step’th line starting with line first. For example, ‘‘sed -n 1˜2p’’ will print all the oddnumbered lines in the input stream, and the address 2˜5 will match every fifth line, starting with
the second. (This is a GNU extension.)
$
Match the last line.
/regexp/
Match lines matching the regular expression regexp.
\cregexpc
Match lines matching the regular expression regexp. The c may be any character.
Regular expressions
POSIX.2 BREs should be supported, but they aren’t completely yet. The \n sequence in a regular expression matches the newline character. There are also some GNU extensions. [XXX FIXME: more needs to
be said. At the very least, a reference to another document which describes what is supported should be
given.]
Miscellaneous notes
This version of sed supports a \<newline> sequence in all regular expressions, the replacement part of a
substitute (s) command, and in the source and dest parts of a transliterate (y) command. The \ is stripped,
and the newline is kept.
SEE ALSO
awk(1), ed(1), expr(1), emacs(1), perl(1), tr(1), vi(1), regex(5) [well, one ought to be written... XXX],
sed.info, any of various books on sed, the sed FAQ (http://www.wollery.demon.co.uk/sedtut10.txt,
http://www.ptug.org/sed/sedfaq.htm).
BUGS
E-mail bug reports to [email protected]. Be sure to include the word ‘‘sed’’ somewhere in the
‘‘Subject:’’ field.
GNU Project
1998-05-07
123
SORT(1)
Manuel de l’utilisateur Linux
SORT(1)
NOM
sort − Trier les lignes d’un fichier texte.
SYNOPSIS
sort [−cmus] [−t séparateur] [−o fichier_de_sortie] [−T répertoire_temporaire] [−bdfiMnr] [+POS1
[−POS2]] [−k POS1[,POS2]] [fichier...]
sort {−−help,−−version}
DESCRIPTION
Cette page de manuel documente la version GNU de sort.
sort trie, regroupe ou compare toutes les lignes des fichiers indiqués. Si aucun fichier n’est fourni, ou si le
nom ‘−’ est mentionné, la lecture se fera depuis l’entrée standard.
Par défaut, sort écrit ses résultats sur la sortie standard.
sort peut opérer suivant trois modes : tri (par défaut), regroupement, et vérification de l’ordre. Les options
suivantes modifient le mode opératoire :
−c
([NDT] c = check - vérifier) Vérifie si les fichiers fournis sont déjà triés : s’ils ne le sont pas,
afficher un message d’erreur, et terminer avec un code de retour valant 1.
−m
([NDT] m = merge - melanger) Regrouper les fichiers indiqués en les triant. Chaque fichier
d’entrée doit déjà être trié individuellement. Il est toujours possible de trier plutôt que de réunir, le
regroupement est fourni parce qu’il est plus rapide dans les cas où il fonctionne.
La comparaison de deux lignes se fait ainsi : Si un champ clé a été indiqué, sort compare chaque paire de
champs, dans l’ordre précisé sur la ligne de commande, jusqu’à ce qu’une différence soit trouvée, ou qu’il
ne reste plus de champs.
Si l’une des options globales Mbdfinr est utilisée, et si aucun champ clé n’est indiqué, sort compare les
lignes entières en fonction des options globales.
Finalement, si toutes les clés sont égales, en dernier ressort sort compare les lignes octet par octet suivant
l’ordre défini sur la machine. Cette dernière comparaison accepte l’option globale -r. L’option −s (stable)
inhibe cette comparaison en dernier recours afin que les lignes considérées comme égales restent à leurs
positions relatives. Si aucun champ clé, et aucune option ne sont fournis, −s est sans effet.
La version GNU de sort n’a pas de limitation concernant la longueur des lignes d’entrée ou les caractères
autorisés. De plus, si le dernier octet d’une ligne d’entrée n’est pas un saut de ligne (NewLine), la version
GNU de sort en ajoute un automatiquement.
Si la variable d’environnement TMPDIR est configurée, sort utilise ce répertoire pour stocker les fichiers
temporaires à la place du répertoire par défaut /tmp. L’option −T répertoire_temporaire permet également
de sélectionner un répertoire pour placer les fichiers temporaires, elle a priorité sur la variable d’environnement.
Les options suivantes affectent l’ordre des lignes de sortie. Elles peuvent être mentionnées globalement, ou
appliquées à un champ clé spécifique. Si aucun champ clé n’est indiqué, les options globales s’appliquent
aux comparaisons des lignes entières, sinon elles sont transmises aux champs clés n’ayant pas d’option
spécifique.
124
−b
Ignorer les blancs en début de ligne pendant la recherche de la clé de tri sur chaque ligne.
−d
Trier dans l’ordre des répertoires téléphoniques : ignorer pour le tri tous les caractères autres que
les lettres, les chiffres et les blancs.
−f
Considérer les minuscules comme leur équivalent en majuscule pendant le tri. Ainsi ‘b’ est trie de
manière équivalente a ‘B’. ([NDT] Bien entendu cela ne fonctionne pas avec les minuscules
accentuées...)
−i
Ignorer pour le tri les caractères en dehors de l’intervalle ASCII octal 040-0176 (bornes comprises).
14 Janvier 1997
FSF
SORT(1)
Manuel de l’utilisateur Linux
SORT(1)
−M
Une chaîne initiale, consistant en un nombre quelconque de blancs, suivi de trois lettres correspondant à une abreviation de mois est convertie en majuscules avant d’être comparée dans l’ordre
‘JAN’ < ‘FEB’ < ... < ‘DEC.’ Les noms invalides sont considéres comme inférieurs aux noms
valides. ([NDT] Qu’en-est-il vis à vis de la localisation ?)
−n
Comparer suivant la valeur arithmétique d’une chaîne numérique initiale composée d’espaces
éventuels, suivis optionnellement du signe −, et de zéro ou plusieurs chiffres, éventuellement suivi
d’un point décimal et de zéro ou plusieurs chiffres.
−r
Inverser l’ordre de tri, afin que les lignes avec la plus grande valeur de clé apparaissent en premier.
Les autres options sont :
−o fichier_de_sortie
Ecrire dans le fichier_de_sortie plutôt que sur la sortie standard. Si fichier_de_sortie est également un fichier d’entrée, sort copie les données dans un fichier temporaire avant le tri pour pouvoir écrire correctement ses résultats dans le fichier_de_sortie.
−t caractère_séparateur
Utiliser le caractère_séparateur afin de distinguer les champs pour rechercher la clé de tri sur
chaque ligne. Par défaut le séparateur de champs est une chaîne blanche entre chaînes nonblanches. Ceci signifie qu’avec l’entrée ‘ foo bar’, sort distingue deux champs ‘ foo’ et ‘ bar’. Le
séparateur n’appartient ni au champ précédent, ni au champ suivant.
−u
Pour l’action par défaut, ou pour l’action −m, n’afficher que la première séquence de lignes considérées comme égales. Pour l’action −c, vérifier qu’aucune lignes consécutives ne soient égales.
+POS1 [−POS2]
Indiquer un champ à utiliser comme clé de tri pour chaque ligne. Le champ consiste en une portion de de ligne débutant à la position POS1, et s’étendant jusqu’à POS2 non-inclue (ou jusqu’à la
fin de la ligne si POS2 n’est pas mentionnée). Les positions des champs et des caractères sont
numérotées à partir de 0.
−k POS1[,POS2]
Une autre syntaxe possible pour indiquer les clés de tri. Les positions des champs et des caractères sont numérotées à partir de 1.
Une position est de la forme f.c, où f est le numéro du champ à utiliser, et c le numéro du premier caractère
depuis le début du champ (avec +pos) ou depuis la fin du champ précédent (avec −pos). La partie .c de la
position peut être omise, auquel cas le caractère considéré est le premier du champ. Si l’option −b est
choisie, la partie .c d’une spécification de champ est comptée à partir du premier caractère non-blanc du
champ (pour +pos) ou à partir du premier caractère non-blanc suivant le champ précédent (pour −pos).
Un argument +pos ou -pos peut également avoir un préfixe constitué d’une des lettres d’option Mbdfinr
auquel cas les options globales ne s’appliquent pas à ce champ. l’option −b peut être attachée indépendament aux parties +pos ou −pos d’une spécification de champ. Si elle est héritée d’une option globale, elle
s’appliquera aux deux parties. Si une option −n ou −M est utilisée, ceci implique que l’option −b
s’applique aux deux spécifications +pos et −pos. Les clés peuvent s’étendre sur plusieurs champs.
De plus quand la version GNU de sort est invoquée avec un seul argument, les options suivantes sont
reconnues :
−−help Afficher un message d’aide sur la sortie standard et terminer normalement.
−−version
Afficher un numéro de version sur la sortie standard et terminer normalement.
COMPATIBILITE
Les implémentations historiques (BSD et System V) de sort diffèrent dans leurs interprétations de certaines
options, notamment −b, −f , et −n. La version GNU suit le comportement POSIX, qui est généralement
(mais pas toujours) celui de la version System V. Suivant POSIX −n n’implique plus obligatoirement −b.
Pour assurer l’homogénéïte, −M a été modifiée de la même manière. Dans certains cas, assez obscurs, ceci
peut affecter la signification des positions de caractères dans les spécifications de champs. Si ceci vous
FSF
14 Janvier 1997
125
SORT(1)
Manuel de l’utilisateur Linux
SORT(1)
perturbe, vous pouvez ajouter explicitement un −b.
BUGS
Les différentes significations des numéros de champs en fonction de l’utilisation ou non de l’option -k
induit une confusion certaine. C’est la faute à POSIX !
TRADUCTION
Christophe Blaess, 1997.
126
14 Janvier 1997
FSF
ASCII(7)
Manuel de l’administrateur Linux
ASCII(7)
NOM
ascii − Le jeu de caractères ASCII en octal, décimal, et hexadécimal.
DESCRIPTION
ASCII est l’acronyme de American Standard Code for Information Interchange. Il s’agit d’un code sur 7
bits. De nombreux codes sur 8 bits (tels que l’ISO 8859-1n le jeu de caractères par défaut de Linux) contiennent l’ASCII dans leur première moitié. L’équivalent international de l’ASCII est connu sous le nom de
ISO 646.
La table suivante contient les 128 caracteres ASCII.
Les séquences d’échappement ’\X’ pour les programmes C sont mentionnées.
Oct
000
001
002
003
004
005
006
007
010
011
012
013
014
015
016
017
020
021
022
023
024
025
026
027
030
031
032
033
034
035
036
037
040
041
042
043
044
045
046
047
Linux
Dec
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Hex
00
01
02
03
04
05
06
07
08
09
0A
0B
0C
0D
0E
0F
10
11
12
13
14
15
16
17
18
19
1A
1B
1C
1D
1E
1F
20
21
22
23
24
25
26
27
Car
NUL ’\0’
SOH
STX
ETX
EOT
ENQ
ACK
BEL ’\a’
BS ’\b’
HT ’\t’
LF ’\n’
VT ’\v’
FF ’\f’
CR ’\r’
SO
SI
DLE
DC1
DC2
DC3
DC4
NAK
SYN
ETB
CAN
EM
SUB
ESC
FS
GS
RS
US
SPACE
!
"
#
$
%
&
’
Oct
100
101
102
103
104
105
106
107
110
111
112
113
114
115
116
117
120
121
122
123
124
125
126
127
130
131
132
133
134
135
136
137
140
141
142
143
144
145
146
147
25 Janvier 1997
Dec
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
Hex
40
41
42
43
44
45
46
47
48
49
4A
4B
4C
4D
4E
4F
50
51
52
53
54
55
56
57
58
59
5A
5B
5C
5D
5E
5F
60
61
62
63
64
65
66
67
Car
@
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
[
\
’\\’
]
ˆ
_
‘
a
b
c
d
e
f
g
127
ASCII(7)
Manuel de l’administrateur Linux
050
051
052
053
054
055
056
057
060
061
062
063
064
065
066
067
070
071
072
073
074
075
076
077
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
28
29
2A
2B
2C
2D
2E
2F
30
31
32
33
34
35
36
37
38
39
3A
3B
3C
3D
3E
3F
(
)
∗
+
,
−
.
/
0
1
2
3
4
5
6
7
8
9
:
;
<
=
>
?
150
151
152
153
154
155
156
157
160
161
162
163
164
165
166
167
170
171
172
173
174
175
176
177
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
ASCII(7)
68
69
6A
6B
6C
6D
6E
6F
70
71
72
73
74
75
76
77
78
79
7A
7B
7C
7D
7E
7F
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
{
|
}
˜
DEL
HISTORIQUE
Une page de manuel ascii est apparue dans AT&T UNIX VERSION 7.
Sur les terminaux anciens, le code de soulignement (underscore) est affiché sous forme de flèche vers la
gauche (backarrow), l’accent circonflexe (caret) est affiché sous forme de flèche vers le haut, et la barre verticale est interrompue en son centre.
Le standard ASCII a été publié par l’USASI (United States of America Standards Institute) en 1968.
VOIR AUSSI
iso_8859_1(7)
TRADUCTION
Christophe Blaess, 1997.
128
25 Janvier 1997
Linux
ISO_8859-15(7)
Linux Programmer’s Manual
ISO_8859-15(7)
NAME
iso_8859-15 − the ISO 8859-15 character set encoded in octal, decimal, and hexadecimal
DESCRIPTION
The ISO 8859 standard includes several 8-bit extensions to the ASCII character set (also known as ISO
646-IRV). Especially important is ISO 8859-1, the "Latin Alphabet No. 1", which has become widely
implemented and may already be seen as the de-facto standard ASCII replacement. However, it lacks the
EURO symbol and does not fully cover Finnish and French. ISO 8859-15 is a modification of ISO 8859-1
that covers these needs.
ISO 8859-15 supports the following languages: Albanian, Basque, Breton, Catalan, Danish, Dutch, English,
Estonian, Faroese, Finnish, French, Frisian, Galician, German, Greenlandic, Icelandic, Irish Gaelic, Italian,
Latin, Luxemburgish, Norwegian, Portuguese, Rhaeto-Romanic, Scottish Gaelic, Spanish, and Swedish.
ISO 8859 Alphabets
The full set of ISO 8859 alphabets includes:
ISO 8859-1
ISO 8859-2
ISO 8859-3
ISO 8859-4
ISO 8859-5
ISO 8859-6
ISO 8859-7
ISO 8859-8
ISO 8859-9
ISO 8859-10
ISO 8859-11
ISO 8859-13
ISO 8859-14
ISO 8859-15
ISO 8859-16
West European languages (Latin-1)
Central and East European languages (Latin-2)
Southeast European and miscellaneous languages (Latin-3)
Scandinavian/Baltic languages (Latin-4)
Latin/Cyrillic
Latin/Arabic
Latin/Greek
Latin/Hebrew
Latin-1 modification for Turkish (Latin-5)
Lappish/Nordic/Eskimo languages (Latin-6)
Latin/Thai
Baltic Rim languages (Latin-7)
Celtic (Latin-8)
West European languages (Latin-9)
Romanian (Latin-10)
ISO 8859-15 Characters
The following table displays the characters in ISO 8859-15 (Latin-9), which are printable and unlisted in
the ascii(7) manual page. The fourth column will only show the proper glyphs in an environment
configured for ISO 8859-15.
Oct
240
241
242
243
244
245
246
247
250
251
252
253
254
255
256
257
260
261
Linux
Dec
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
Hex
A0
A1
A2
A3
A4
A5
A6
A7
A8
A9
AA
AB
AC
AD
AE
AF
B0
B1
Char
¡
¢
£
¤
¥
¦
§
¨
©
ª
«
¬
®
¯
°
±
Description
NO-BREAK SPACE
INVERTED EXCLAMATION MARK
CENT SIGN
POUND SIGN
EURO SIGN
YEN SIGN
LATIN CAPITAL LETTER S WITH CARON
SECTION SIGN
LATIN SMALL LETTER S WITH CARON
COPYRIGHT SIGN
FEMININE ORDINAL INDICATOR
LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
NOT SIGN
SOFT HYPHEN
REGISTERED SIGN
MACRON
DEGREE SIGN
PLUS-MINUS SIGN
1999-05-31
129
ISO_8859-15(7)
262
263
264
265
266
267
270
271
272
273
274
275
276
277
300
301
302
303
304
305
306
307
310
311
312
313
314
315
316
317
320
321
322
323
324
325
326
327
330
331
332
333
334
335
336
337
340
341
342
343
344
345
346
130
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
Linux Programmer’s Manual
B2
B3
B4
B5
B6
B7
B8
B9
BA
BB
BC
BD
BE
BF
C0
C1
C2
C3
C4
C5
C6
C7
C8
C9
CA
CB
CC
CD
CE
CF
D0
D1
D2
D3
D4
D5
D6
D7
D8
D9
DA
DB
DC
DD
DE
DF
E0
E1
E2
E3
E4
E5
E6
²
³
´
µ
¶
·
¸
¹
º
»
¼
½
¾
¿
À
Á
Â
Ã
Ä
Å
Æ
Ç
È
É
Ê
Ë
Ì
Í
Î
Ï
Ð
Ñ
Ò
Ó
Ô
Õ
Ö
×
Ø
Ù
Ú
Û
Ü
Ý
Þ
ß
à
á
â
ã
ä
å
æ
ISO_8859-15(7)
SUPERSCRIPT TWO
SUPERSCRIPT THREE
LATIN CAPITAL LETTER Z WITH CARON
MICRO SIGN
PILCROW SIGN
MIDDLE DOT
LATIN SMALL LETTER Z WITH CARON
SUPERSCRIPT ONE
MASCULINE ORDINAL INDICATOR
RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
LATIN CAPITAL LIGATURE OE
LATIN SMALL LIGATURE OE
LATIN CAPITAL LETTER Y WITH DIAERESIS
INVERTED QUESTION MARK
LATIN CAPITAL LETTER A WITH GRAVE
LATIN CAPITAL LETTER A WITH ACUTE
LATIN CAPITAL LETTER A WITH CIRCUMFLEX
LATIN CAPITAL LETTER A WITH TILDE
LATIN CAPITAL LETTER A WITH DIAERESIS
LATIN CAPITAL LETTER A WITH RING ABOVE
LATIN CAPITAL LETTER AE
LATIN CAPITAL LETTER C WITH CEDILLA
LATIN CAPITAL LETTER E WITH GRAVE
LATIN CAPITAL LETTER E WITH ACUTE
LATIN CAPITAL LETTER E WITH CIRCUMFLEX
LATIN CAPITAL LETTER E WITH DIAERESIS
LATIN CAPITAL LETTER I WITH GRAVE
LATIN CAPITAL LETTER I WITH ACUTE
LATIN CAPITAL LETTER I WITH CIRCUMFLEX
LATIN CAPITAL LETTER I WITH DIAERESIS
LATIN CAPITAL LETTER ETH
LATIN CAPITAL LETTER N WITH TILDE
LATIN CAPITAL LETTER O WITH GRAVE
LATIN CAPITAL LETTER O WITH ACUTE
LATIN CAPITAL LETTER O WITH CIRCUMFLEX
LATIN CAPITAL LETTER O WITH TILDE
LATIN CAPITAL LETTER O WITH DIAERESIS
MULTIPLICATION SIGN
LATIN CAPITAL LETTER O WITH STROKE
LATIN CAPITAL LETTER U WITH GRAVE
LATIN CAPITAL LETTER U WITH ACUTE
LATIN CAPITAL LETTER U WITH CIRCUMFLEX
LATIN CAPITAL LETTER U WITH DIAERESIS
LATIN CAPITAL LETTER Y WITH ACUTE
LATIN CAPITAL LETTER THORN
LATIN SMALL LETTER SHARP S
LATIN SMALL LETTER A WITH GRAVE
LATIN SMALL LETTER A WITH ACUTE
LATIN SMALL LETTER A WITH CIRCUMFLEX
LATIN SMALL LETTER A WITH TILDE
LATIN SMALL LETTER A WITH DIAERESIS
LATIN SMALL LETTER A WITH RING ABOVE
LATIN SMALL LETTER AE
1999-05-31
Linux
ISO_8859-15(7)
347
350
351
352
353
354
355
356
357
360
361
362
363
364
365
366
367
370
371
372
373
374
375
376
377
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
Linux Programmer’s Manual
E7
E8
E9
EA
EB
EC
ED
EE
EF
F0
F1
F2
F3
F4
F5
F6
F7
F8
F9
FA
FB
FC
FD
FE
FF
ç
è
é
ê
ë
ì
í
î
ï
ð
ñ
ò
ó
ô
õ
ö
÷
ø
ù
ú
û
ü
ý
þ
ÿ
ISO_8859-15(7)
LATIN SMALL LETTER C WITH CEDILLA
LATIN SMALL LETTER E WITH GRAVE
LATIN SMALL LETTER E WITH ACUTE
LATIN SMALL LETTER E WITH CIRCUMFLEX
LATIN SMALL LETTER E WITH DIAERESIS
LATIN SMALL LETTER I WITH GRAVE
LATIN SMALL LETTER I WITH ACUTE
LATIN SMALL LETTER I WITH CIRCUMFLEX
LATIN SMALL LETTER I WITH DIAERESIS
LATIN SMALL LETTER ETH
LATIN SMALL LETTER N WITH TILDE
LATIN SMALL LETTER O WITH GRAVE
LATIN SMALL LETTER O WITH ACUTE
LATIN SMALL LETTER O WITH CIRCUMFLEX
LATIN SMALL LETTER O WITH TILDE
LATIN SMALL LETTER O WITH DIAERESIS
DIVISION SIGN
LATIN SMALL LETTER O WITH STROKE
LATIN SMALL LETTER U WITH GRAVE
LATIN SMALL LETTER U WITH ACUTE
LATIN SMALL LETTER U WITH CIRCUMFLEX
LATIN SMALL LETTER U WITH DIAERESIS
LATIN SMALL LETTER Y WITH ACUTE
LATIN SMALL LETTER THORN
LATIN SMALL LETTER Y WITH DIAERESIS
SEE ALSO
ascii(7), iso_8859-1(7)
COLOPHON
This page is part of release 3.21 of the Linux man-pages project. A description of the project, and
information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/.
Linux
1999-05-31
131
UNICODE(7)
Linux Programmer’s Manual
UNICODE(7)
NAME
Unicode − the Universal Character Set
DESCRIPTION
The international standard ISO 10646 defines the Universal Character Set (UCS). UCS contains all
characters of all other character set standards. It also guarantees round-trip compatibility, i.e., conversion
tables can be built such that no information is lost when a string is converted from any other encoding to
UCS and back.
UCS contains the characters required to represent practically all known languages. This includes not only
the Latin, Greek, Cyrillic, Hebrew, Arabic, Armenian, and Georgian scripts, but also Chinese, Japanese and
Korean Han ideographs as well as scripts such as Hiragana, Katakana, Hangul, Devanagari, Bengali,
Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam, Thai, Lao, Khmer, Bopomofo, Tibetan,
Runic, Ethiopic, Canadian Syllabics, Cherokee, Mongolian, Ogham, Myanmar, Sinhala, Thaana, Yi, and
others. For scripts not yet covered, research on how to best encode them for computer usage is still going
on and they will be added eventually. This might eventually include not only Hieroglyphs and various
historic Indo-European languages, but even some selected artistic scripts such as Tengwar, Cirth, and
Klingon. UCS also covers a large number of graphical, typographical, mathematical and scientific
symbols, including those provided by TeX, Postscript, APL, MS-DOS, MS-Windows, Macintosh, OCR
fonts, as well as many word processing and publishing systems, and more are being added.
The UCS standard (ISO 10646) describes a 31-bit character set architecture consisting of 128 24-bit
groups, each divided into 256 16-bit planes made up of 256 8-bit rows with 256 column positions, one for
each character. Part 1 of the standard (ISO 10646-1) defines the first 65534 code positions (0x0000 to
0xfffd), which form the Basic Multilingual Plane (BMP), that is plane 0 in group 0. Part 2 of the standard
(ISO 10646-2) adds characters to group 0 outside the BMP in several supplementary planes in the range
0x10000 to 0x10ffff. There are no plans to add characters beyond 0x10ffff to the standard, therefore of the
entire code space, only a small fraction of group 0 will ever be actually used in the foreseeable future. The
BMP contains all characters found in the commonly used other character sets. The supplemental planes
added by ISO 10646-2 cover only more exotic characters for special scientific, dictionary printing,
publishing industry, higher-level protocol and enthusiast needs.
The representation of each UCS character as a 2-byte word is referred to as the UCS-2 form (only for BMP
characters), whereas UCS-4 is the representation of each character by a 4-byte word. In addition, there
exist two encoding forms UTF-8 for backwards compatibility with ASCII processing software and UTF-16
for the backwards compatible handling of non-BMP characters up to 0x10ffff by UCS-2 software.
The UCS characters 0x0000 to 0x007f are identical to those of the classic US-ASCII character set and the
characters in the range 0x0000 to 0x00ff are identical to those in ISO 8859-1 Latin-1.
Combining Characters
Some code points in UCS have been assigned to combining characters. These are similar to the nonspacing accent keys on a typewriter. A combining character just adds an accent to the previous character.
The most important accented characters have codes of their own in UCS, however, the combining character
mechanism allows us to add accents and other diacritical marks to any character. The combining characters
always follow the character which they modify. For example, the German character Umlaut-A ("Latin
capital letter A with diaeresis") can either be represented by the precomposed UCS code 0x00c4, or
alternatively as the combination of a normal "Latin capital letter A" followed by a "combining diaeresis":
0x0041 0x0308.
Combining characters are essential for instance for encoding the Thai script or for mathematical typesetting
and users of the International Phonetic Alphabet.
Implementation Levels
As not all systems are expected to support advanced mechanisms like combining characters, ISO 10646-1
specifies the following three implementation levels of UCS:
Level 1
132
Combining characters and Hangul Jamo (a variant encoding of the Korean script, where a
Hangul syllable glyph is coded as a triplet or pair of vovel/consonant codes) are not
2001-05-11
GNU
UNICODE(7)
Linux Programmer’s Manual
UNICODE(7)
supported.
Level 2
In addition to level 1, combining characters are now allowed for some languages where
they are essential (e.g., Thai, Lao, Hebrew, Arabic, Devanagari, Malayalam, etc.).
Level 3
All UCS characters are supported.
The Unicode 3.0 Standard published by the Unicode Consortium contains exactly the UCS Basic
Multilingual Plane at implementation level 3, as described in ISO 10646-1:2000. Unicode 3.1 added the
supplemental planes of ISO 10646-2. The Unicode standard and technical reports published by the
Unicode Consortium provide much additional information on the semantics and recommended usages of
various characters. They provide guidelines and algorithms for editing, sorting, comparing, normalizing,
converting and displaying Unicode strings.
Unicode Under Linux
Under GNU/Linux, the C type wchar_t is a signed 32-bit integer type. Its values are always interpreted by
the C library as UCS code values (in all locales), a convention that is signaled by the GNU C library to
applications by defining the constant __STDC_ISO_10646__ as specified in the ISO C99 standard.
UCS/Unicode can be used just like ASCII in input/output streams, terminal communication, plaintext files,
filenames, and environment variables in the ASCII compatible UTF-8 multi-byte encoding. To signal the
use of UTF-8 as the character encoding to all applications, a suitable locale has to be selected via
environment variables (e.g., "LANG=en_GB.UTF-8").
The nl_langinfo(CODESET) function returns the name of the selected encoding. Library functions such
as wctomb(3) and mbsrtowcs(3) can be used to transform the internal wchar_t characters and strings into
the system character encoding and back and wcwidth(3) tells, how many positions (0–2) the cursor is
advanced by the output of a character.
Under Linux, in general only the BMP at implementation level 1 should be used at the moment. Up to two
combining characters per base character for certain scripts (in particular Thai) are also supported by some
UTF-8 terminal emulators and ISO 10646 fonts (level 2), but in general precomposed characters should be
preferred where available (Unicode calls this Normalization Form C).
Private Area
In the BMP, the range 0xe000 to 0xf8ff will never be assigned to any characters by the standard and is
reserved for private usage. For the Linux community, this private area has been subdivided further into the
range 0xe000 to 0xefff which can be used individually by any end-user and the Linux zone in the range
0xf000 to 0xf8ff where extensions are coordinated among all Linux users. The registry of the characters
assigned to the Linux zone is currently maintained by H. Peter Anvin <[email protected]>.
Literature
∗ Information technology — Universal Multiple-Octet Coded Character Set (UCS) — Part 1:
Architecture and Basic Multilingual Plane. International Standard ISO/IEC 10646-1, International
Organization for Standardization, Geneva, 2000.
This is the official specification of UCS. Available as a PDF file on CD-ROM from http://www.iso.ch/.
∗ The Unicode Standard, Version 3.0. The Unicode Consortium, Addison-Wesley, Reading, MA, 2000,
ISBN 0-201-61633-5.
∗ S. Harbison, G. Steele. C: A Reference Manual. Fourth edition, Prentice Hall, Englewood Cliffs, 1995,
ISBN 0-13-326224-3.
A good reference book about the C programming language. The fourth edition covers the 1994
Amendment 1 to the ISO C90 standard, which adds a large number of new C library functions for
handling wide and multi-byte character encodings, but it does not yet cover ISO C99, which improved
wide and multi-byte character support even further.
∗ Unicode Technical Reports.
http://www.unicode.org/unicode/reports/
GNU
2001-05-11
133
UNICODE(7)
Linux Programmer’s Manual
UNICODE(7)
∗ Markus Kuhn: UTF-8 and Unicode FAQ for Unix/Linux.
http://www.cl.cam.ac.uk/˜mgk25/unicode.html
Provides subscription information for the linux-utf8 mailing list, which is the best place to look for
advice on using Unicode under Linux.
∗ Bruno Haible: Unicode HOWTO.
ftp://ftp.ilog.fr/pub/Users/haible/utf8/Unicode-HOWTO.html
BUGS
When this man page was last revised, the GNU C Library support for UTF-8 locales was mature and
XFree86 support was in an advanced state, but work on making applications (most notably editors) suitable
for use in UTF-8 locales was still fully in progress. Current general UCS support under Linux usually
provides for CJK double-width characters and sometimes even simple overstriking combining characters,
but usually does not include support for scripts with right-to-left writing direction or ligature substitution
requirements such as Hebrew, Arabic, or the Indic scripts. These scripts are currently only supported in
certain GUI applications (HTML viewers, word processors) with sophisticated text rendering engines.
SEE ALSO
setlocale(3), charsets(7), utf-8(7)
COLOPHON
This page is part of release 3.21 of the Linux man-pages project. A description of the project, and
information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/.
134
2001-05-11
GNU
UTF-8(7)
Linux Programmer’s Manual
UTF-8(7)
NAME
UTF-8 − an ASCII compatible multi-byte Unicode encoding
DESCRIPTION
The Unicode 3.0 character set occupies a 16-bit code space. The most obvious Unicode encoding (known
as UCS-2) consists of a sequence of 16-bit words. Such strings can contain as parts of many 16-bit
characters bytes like '\0' or '/' which have a special meaning in filenames and other C library function
arguments. In addition, the majority of Unix tools expects ASCII files and can’t read 16-bit words as
characters without major modifications. For these reasons, UCS-2 is not a suitable external encoding of
Unicode in filenames, text files, environment variables, etc. The ISO 10646 Universal Character Set
(UCS), a superset of Unicode, occupies even a 31-bit code space and the obvious UCS-4 encoding for it (a
sequence of 32-bit words) has the same problems.
The UTF-8 encoding of Unicode and UCS does not have these problems and is the common way in which
Unicode is used on Unix-style operating systems.
Properties
The UTF-8 encoding has the following nice properties:
∗ UCS characters 0x00000000 to 0x0000007f (the classic US-ASCII characters) are encoded simply as
bytes 0x00 to 0x7f (ASCII compatibility). This means that files and strings which contain only 7-bit
ASCII characters have the same encoding under both ASCII and UTF-8.
∗ All UCS characters greater than 0x7f are encoded as a multi-byte sequence consisting only of bytes in
the range 0x80 to 0xfd, so no ASCII byte can appear as part of another character and there are no
problems with, for example, '\0' or '/'.
∗ The lexicographic sorting order of UCS-4 strings is preserved.
∗ All possible 2ˆ31 UCS codes can be encoded using UTF-8.
∗ The bytes 0xfe and 0xff are never used in the UTF-8 encoding.
∗ The first byte of a multi-byte sequence which represents a single non-ASCII UCS character is always in
the range 0xc0 to 0xfd and indicates how long this multi-byte sequence is. All further bytes in a multibyte sequence are in the range 0x80 to 0xbf. This allows easy resynchronization and makes the
encoding stateless and robust against missing bytes.
∗ UTF-8 encoded UCS characters may be up to six bytes long, however the Unicode standard specifies
no characters above 0x10ffff, so Unicode characters can only be up to four bytes long in UTF-8.
Encoding
The following byte sequences are used to represent a character. The sequence to be used depends on the
UCS code number of the character:
0x00000000 − 0x0000007F:
0xxxxxxx
0x00000080 − 0x000007FF:
110xxxxx 10xxxxxx
0x00000800 − 0x0000FFFF:
1110xxxx 10xxxxxx 10xxxxxx
0x00010000 − 0x001FFFFF:
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
0x00200000 − 0x03FFFFFF:
111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
0x04000000 − 0x7FFFFFFF:
1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
The xxx bit positions are filled with the bits of the character code number in binary representation. Only
the shortest possible multi-byte sequence which can represent the code number of the character can be
GNU
2001-05-11
135
UTF-8(7)
Linux Programmer’s Manual
UTF-8(7)
used.
The UCS code values 0xd800–0xdfff (UTF-16 surrogates) as well as 0xfffe and 0xffff (UCS noncharacters) should not appear in conforming UTF-8 streams.
Example
The Unicode character 0xa9 = 1010 1001 (the copyright sign) is encoded in UTF-8 as
11000010 10101001 = 0xc2 0xa9
and character 0x2260 = 0010 0010 0110 0000 (the "not equal" symbol) is encoded as:
11100010 10001001 10100000 = 0xe2 0x89 0xa0
Application Notes
Users have to select a UTF-8 locale, for example with
export LANG=en_GB.UTF-8
in order to activate the UTF-8 support in applications.
Application software that has to be aware of the used character encoding should always set the locale with
for example
setlocale(LC_CTYPE, "")
and programmers can then test the expression
strcmp(nl_langinfo(CODESET), "UTF-8") == 0
to determine whether a UTF-8 locale has been selected and whether therefore all plaintext standard input
and output, terminal communication, plaintext file content, filenames and environment variables are
encoded in UTF-8.
Programmers accustomed to single-byte encodings such as US-ASCII or ISO 8859 have to be aware that
two assumptions made so far are no longer valid in UTF-8 locales. Firstly, a single byte does not
necessarily correspond any more to a single character. Secondly, since modern terminal emulators in
UTF-8 mode also support Chinese, Japanese, and Korean double-width characters as well as non-spacing
combining characters, outputting a single character does not necessarily advance the cursor by one
position as it did in ASCII. Library functions such as mbsrtowcs(3) and wcswidth(3) should be used
today to count characters and cursor positions.
The official ESC sequence to switch from an ISO 2022 encoding scheme (as used for instance by VT100
terminals) to UTF-8 is ESC % G ("\x1b%G"). The corresponding return sequence from UTF-8 to ISO
2022 is ESC % @ ("\x1b%@"). Other ISO 2022 sequences (such as for switching the G0 and G1 sets) are
not applicable in UTF-8 mode.
It can be hoped that in the foreseeable future, UTF-8 will replace ASCII and ISO 8859 at all levels as the
common character encoding on POSIX systems, leading to a significantly richer environment for handling
plain text.
Security
The Unicode and UCS standards require that producers of UTF-8 shall use the shortest form possible, for
example, producing a two-byte sequence with first byte 0xc0 is non-conforming. Unicode 3.1 has added
the requirement that conforming programs must not accept non-shortest forms in their input. This is for
security reasons: if user input is checked for possible security violations, a program might check only for
the ASCII version of "/../" or ";" or NUL and overlook that there are many non-ASCII ways to represent
these things in a non-shortest UTF-8 encoding.
Standards
ISO/IEC 10646-1:2000, Unicode 3.1, RFC 2279, Plan 9.
SEE ALSO
nl_langinfo(3), setlocale(3), charsets(7), unicode(7)
136
2001-05-11
GNU
UTF-8(7)
Linux Programmer’s Manual
UTF-8(7)
COLOPHON
This page is part of release 3.21 of the Linux man-pages project. A description of the project, and
information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/.
GNU
2001-05-11
137
INTRODUCTION()
138
INTRODUCTION()
Petit manuel Unix 2002
INDEX
a2ps − anything to PostScript − n’importe quoi en PostScript ............................................. 12
ar − archive − archive ............................................................................................................ 12
arch − architecture − architecture ......................................................................................... 54
basename − base name − nom de base ................................................................................. 12
bc − basic calculator − calculette basique ............................................................................. 47
bzip2 bunzip2 − compress − compresse ............................................................................... 13
cal − calendar − calendrier .................................................................................................... 47
cat − catenate − concaténer ................................................................................................... 13
cc − C compiler − compilateur C .......................................................................................... 27
cd − change working Directory − change le répertoire de travail ......................................... 11
chgrp − change group − changer le groupe ........................................................................... 22
chmod − change mode − changer le mode ........................................................................... 22
chown − change owner − changer le propriétaire ................................................................. 22
cl − common lisp − lisp commun .......................................................................................... 27
comm − common − commun ................................................................................................ 13
compress uncompress zcat − compress − compresse ........................................................... 14
convert − convert image format − convertir des formats d’images ....................................... 14
cp − copy − copier ................................................................................................................ 14
cplus-dem − C++ demangler − “démangleur” C++ .............................................................. 31
cpp − C language preprocessor − pré-processeur de langage C ........................................... 30
cut − cut − couper ................................................................................................................. 15
date − date − date .................................................................................................................. 41
df − disk space on filesystems − espace disque des systèmes de fichiers ............................. 24
diff − differences − différences ............................................................................................. 15
doxygen − documentatin generator − générateur de documentation .................................... 31
du − disk usage − usage disque ............................................................................................. 24
echo − echo − écho ............................................................................................................... 38
eclipse − extensible tool platform and Java IDE − EDI Java ................................................ 31
emacs - emacs - emacs .......................................................................................................... 58
expand − expand − expanser ................................................................................................. 15
expr − expression − expression ............................................................................................ 48
f77 − fortan 77 − fortran 77 .................................................................................................. 28
file − file − fichier .................................................................................................................. 41
find − find − trouver .............................................................................................................. 24
free − free memory − mémoire libre ..................................................................................... 54
ftp − file transfer program − programme de transfert de fichier ........................................... 53
fuser - file or socket used - fichiers utilisés ........................................................................... 54
gdb − gnu debugger − débogueur de gnu .............................................................................. 31
gprof − graph profile − profileur graphique .......................................................................... 32
grep − global regexp print − imprime un expresion régulière .............................................. 33
groff - groff - groff ................................................................................................................ 64
gzip gunzip zcat − compress − compresse ............................................................................ 16
head − head − tête ................................................................................................................. 16
host − host − hôte .................................................................................................................. 55
hugs − hugs − hugs ............................................................................................................... 28
iconv − input convert − conversion ....................................................................................... 16
id − identifier − identifiant .................................................................................................... 41
indent − indent − indenter ..................................................................................................... 33
javac − java compiler − compilateur de java ......................................................................... 28
javadoc − java documentatin − documentation java ............................................................. 33
killall − kill all − tuer les tous ............................................................................................... 39
kill − kill − tuer ..................................................................................................................... 38
latex − latex − latex ............................................................................................................... 66
ldd − shared libraries dependencies − dépendances par rapport aux bibliothèques partagées 34
Petit manuel Unix 2001
139
INDEX
ld − link editor − éditeur de liens ..........................................................................................
lint − C program checker − vérificateur de sources C ..........................................................
ln − link − lier .......................................................................................................................
locate − locate − localiser .....................................................................................................
login − login − connexion .....................................................................................................
lp − off line printer − impression en différé ..........................................................................
ls − list − lister ......................................................................................................................
lsof − list open files − liste des fichiers ouverts ....................................................................
mail − mail − courrier ...........................................................................................................
make − make − fabriquer ......................................................................................................
man − manuel − manuel ........................................................................................................
mesg − message − message ..................................................................................................
mkdir − make directory − création de répertoire ..................................................................
more − more and more − de plus en plus ..............................................................................
mv − move − déplacer ...........................................................................................................
nano - Nano’s ANOther editor - NAno un NOuvel éditeur ..................................................
netbeans − Java IDE − EDI Java ...........................................................................................
netstat − net statistics − statistiques réseau ...........................................................................
nice − nice − mignon ............................................................................................................
nmap − network map − carte réseau .....................................................................................
nm − name − nom .................................................................................................................
nohup − no hangup − ne pas raccrocher ...............................................................................
od − octal dump − impression en octal .................................................................................
passwd − password − mot de passe ......................................................................................
paste − paste − coller ............................................................................................................
patch − patch − rustine ..........................................................................................................
pc − pascal compiler − compilateur pascal ...........................................................................
perfmeter − performance meter − mesure de performance ...................................................
perl − practical extraction and report language − perle ........................................................
php − php − php ....................................................................................................................
prof − profile − profil ............................................................................................................
pr − print − imprimer ............................................................................................................
ps − process status − statut des processus .............................................................................
pwd − print working directory − imprime le répertoire de travail ........................................
python − python − python .....................................................................................................
ranlib − make a random library − fabriquer une bibliothèque ..............................................
recode − recode text file − recoder des fichiers texte ............................................................
rmdir − remove directory − destruction de répertoire ...........................................................
rm − remove − enlever ..........................................................................................................
rsync − remote file synchronisation − synchronisation de fichiers à distance ......................
rup − remote time up − temps de marche distant ..................................................................
rusers − remote users − utilisateurs distants .........................................................................
scp − secure copy − copie sûre .............................................................................................
script − script − script ...........................................................................................................
sftp − secure file transfer program − programme de transfert sécurisé de fichier ................
size − size − taille ..................................................................................................................
sleep − sleep − dormir ...........................................................................................................
sox − sound exchange − conversion de fichiers son .............................................................
split − split − découper un fichier .........................................................................................
sshfs − ssh file system − système de fichiers sur ssh ............................................................
ssh − OpenSSH secure shell client − shell de sécurité à distance .........................................
strace − system call trace − trace des appels systèmes .........................................................
strip − strip − enlever ............................................................................................................
stty − set terminal type − positionner des options de terminal .............................................
140
33
34
22
25
5
16
41
55
51
34
49
51
11
17
23
61
35
55
39
35
35
39
36
6
18
36
28
56
28
28
36
18
42
45
29
36
18
11
23
7
56
45
10
39
53
37
39
19
19
10
8
37
37
5
Petit manuel Unix 2001
INDEX
tail − tail − queue ..................................................................................................................
talk − talk − parler .................................................................................................................
tar − tape archive − archive sur bande ..................................................................................
tee − tee − té ..........................................................................................................................
test − test − tester ..................................................................................................................
time − time − temps ..............................................................................................................
top − top − dessus .................................................................................................................
touch − touch − touche ..........................................................................................................
tr − translate − remplace .......................................................................................................
tty − terminal − terminal .......................................................................................................
uname − name of current system − nom du système ...........................................................
uniq − unique − unique .........................................................................................................
uptime − time up − temps de marche ....................................................................................
users − users − utilisateurs ....................................................................................................
vi - visual editor - éditeur visuel ...........................................................................................
vmstat − virtual memory statistics − statistique de la mémoire virtuelle .............................
wc − word count − compte de mots ......................................................................................
web-browsers − − navigateurs web ....................................................................................
whereis − where is − où est-ce ..............................................................................................
which − which − lequel .........................................................................................................
who − who − qui ...................................................................................................................
write − write − écrire ............................................................................................................
w − who and what − qui et quoi ............................................................................................
19
51
19
20
49
37
56
23
20
45
56
21
57
45
63
57
21
53
26
26
46
52
45
En fin de document se trouvent les documentations des commandes suivantes extraites du manuel
GNU/Linux :
dash − command interpreter (shell) − interprète de ligne de commande
ed − editor − éditeur
gawk − la version GNU du langage d’Aho, Weinberger et Kernighan
join − join − joindre
sed − stream editor − éditeur de flot
sort − sort − trier
ascii − the ASCII character set − le jeu de caractère ASCII
iso_8859_15 − the ISO 8859-15 character set − le jeu de caractère iso_8859_15
unicode − the Universal Character Set − le jeu universel de caractère
utf-8 − an ASCII compatible multi-byte Unicode encoding − codage Unicode compatible avec l’ASCII
Petit manuel Unix 2001
141