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() INTRODUCTION()

2Petit 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 aveclefranç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.Avecles 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 (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 diffexpand gzip head iconvlpmore 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 javacpcperl php python OUTILS DE DÉVELOPPEMENT cpp cplus-dem doxygen eclipse gdb gprof grep indent javadoc ld ldd lint makenetbeans nm nmap od patch prof ranlib size strace strip time EXÉCUTION DE PROGRAMMES echo kill killall nice nohup 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 grofflatex OUTILS GRAPHIQUES

4Petit 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’utilisa- teur 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 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_pro- file » 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 « ˆ»,lavaleur 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 » av ec -echo. echok envoie (n’envoie pas avec -echok)uncaractè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 car- actè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 avecn’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éservelecaractère de tabulation (« ˆI »). Av ec -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 majus- cules. 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,etbien sûr pour ˆC et on ne peut plus arrêter l’exécution en envo yant un sig- nal à 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 enfait changer le mot de passe valable sur toutes les stations du réseau.

6Petit 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 per- met d’économiser de la bande passante pour réaliser sauveg ardes 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 com- mande 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 sauveg arde 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 -, --owner préservelepropriétaire (pour le super-utilisateur seulement) -g, --group préservelegroupe propriétaire (pour le super-utilisateur seulement) -t, --time préserveladate de dernière modification -D préserveles 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 duré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éserveles 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 com- mandes 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 [-] [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 ;eneffet 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 aune session ouverte sur flupke et veux en ouvrir une à distance sur quick av ecégalement l’identité jacques.Comme la machine flupke ne connait pas la machine quick elle demande à l’utilisateur d’ajouter son empreinte (Ke y 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 al’avantage de permettre l’utilisation des protocoles RSA (aveclaversion 1 de ssh) ou DSA (avecla 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.Enutilisant la ligne de commande ssh-keygen -t dsa,laclé 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

8Petit 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.Ilest 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 main- tenant avecRSA : 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 avecla clé publique de l’utilisateur et l’envoie au client qui doit la décoder aveclaclé privée (que l’on obtient avec le contenu de ˜/.ssh/id_dsa et la « passphrase ») pour la renvo yer pour comparaison au serveur ; il n’y aainsi 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.Sivous 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 gravessont 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 avecuncontrô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,enutilisant ce canal comme un tunnel (tunelling). Ceci est réalisé en posi- tionnant la variable d’environnement DISPLAY à machinedistante:10.0,10correspond à 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 sauveg arde 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 av ecl’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 − makedirectory − 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 (avecgv) 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 vaimprimer 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.Unfichier archive per- met, entre autre, de regrouper les différents modules d’un programme (cf ranlib). clé est un caractère parmi d, r,toux,é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.Siaucun fichier n’est précisé, tous les com- posants de l’archive sont copiés dans le catalogue de travail. v option « verbeuse » : ar affiche tout ce qu’il fait. Parexemple, pour créer une archive utilisable par ld faire : $arruv 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éfixeseterminant par ’/’ et le suffixes’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’avecgzip 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 tabula- tion sont visualisés « ˆI ». Av ec -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 pro- duit 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.Letaux 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écom- pressé. 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-Zivqui 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 princi- paux formats connus avecleurs 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), CompuServeGraphics Interchange For- mat (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] fichiersré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 des- tination n’existe pas ou si l’option -p est précisée, les attributs du fichier source sont repris. Tout ceci sous réservededroits d’accès corrects. Dans la seconde forme d’appel, les fichiers sont copiés dans le répertoire aveclemê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.Lesé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 suc- cessivement. L’option -c donne trois lignes de contexte. Si on précise l’option -e,lasortie 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 $rmf.old ${cat f.diff; echo ’1,$p’ } | ed - f.new *** affichage ducontenu de f.old *** Note : l’option « - »delacommande 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 successivestrouvé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’aveccompress. 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 mega- octets.

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 − offline 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’impres- sion 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 ». Av ec -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 :idproprié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’avezpas supprimé le fichier durant l’impression. En dernier recours, appelez l’administrateur système. Un dernier conseil :visualisez toujours votre impression avant de l’envo yer 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 com- mandes 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 conven- tion ‘-’ pour l’entrée standard.

NOM pr − print − imprimer SYNTAXE pr [options] fichiers DESCRIPTION pr imprime un fichier sur la sortie standard avecsur 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 par- allè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. Avecles imprimantes PostScript, on peut lui préférer des commandes donnant directement du Post- Script 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 avecdes entités comme dans é, 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 ()est utile pour le format html ou latexcar 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 for- mat étant donné par l’extension. sox connait entre autres les formats suivants (avecleur extension) : .au pour le fichier AUdeSUN 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) avecdes 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 ar- chive (.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é. « nom- bre » 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 -nom- bre unités comptées en partant de la fin. Avecl’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 archivesdans 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 aveccomme 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 avecl’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 : (cddir_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 aveccompress (extension .tar.Z) ou de gzip (exten- sion .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 avezlachance 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 avecbzip2.

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 fichier- vide.

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 cor- respondant dans ensemble2.Uncaractère peut aussi être spécifié par son code octal précédé de \.Onpeut 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 av ecl’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. Avecl’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’argu- ment -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)etles 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 syntaxesuivante : [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 (position- ner : «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 pro- prié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.Unmême fichier (avecson 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,iln’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.Unlien symbolique est en fait une indirection vers un autre fichier.Celien 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] fichiersrépertoire DESCRIPTION mv déplace (renomme) fichier1 en fichier2.Enfait, 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éper- toire. 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 sup- prime 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 avecl’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 avecladate 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 valister 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égaoctets.

L’option -i affiche les informations de tailles relativesaux 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égaoctet 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,nefait 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 naviga- teurs.

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’expres- sion. 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 signifi- cation spéciale pour shell doivent être précédées de \). 2) La négation d’un terme primaire avecl’opérateur !. 3) La concaténation :lajuxtaposition 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 exacte- ment 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 car- actè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 av ecGNU). -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 gigaoctects ! Parcontre, 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 vari- able PATH. On peut lui préférer la commande type intégrée (builtin)aushell.

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.Ilutilise 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, pro- duisant pour chaque source un fichier objet de même nom de base suffixé par .o.Sioncompile un seul pro- gramme, le fichier .o est détruit car cc enchaîne avecl’é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,etsont 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 avecd’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 corre- spondants suffixés par .s. -E lance uniquement le pré-processeur (cpp)avecsortie 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−javacompiler − 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 avecTurbo Pascal 7.0 et supportant certaines exten- sions 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 quel- conques 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.Ilexiste des traducteurs de sed et awk en perl qui sont a2p et s2p.Ilaé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 cer- tains préfèrent à perl pour la programmation de CGI Web.Ilexiste 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 égale- ment l’invoquer avecl’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 argu- ments 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 <>,iln’y a pas de recherche dans le répertoire de « entrée ». Toute directive cpp commence aveclecaractè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, avecladé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). Avecla 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 detest (#if, #ifdef ou #ifndef). Obligatoire après chaque directive detest. #ifdef name jusqu’au premier #endif ou #else rencontré, les lignes suivantes seront présentes dans le pro- gramme 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 pro- gramme 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.Unopérateur unaire supplémentaire peut être utilisé. La syntaxeest 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 detest 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)nesait 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 av ecdes 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.Onpeut examiner une exécution post-mortem en donnant le fichier core ou déboguer un pro- gramme qui tourne en donnant le numéro du processus exécutant ce programme. Les principales comman- des 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 avecles 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. infobreak 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 nou- veau 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 ;ilsuffit de l’appeler aveclacommande 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 aveclacommande C- xespace.

NOM gprof − graph profile − profileur graphique SYNTAXE gprof [-a][fichier] DESCRIPTION gprof interprète le fichier gmon.out produit par le monitor.Cedernier fichier est produit automatiquement pour toute exécution d’un programme compilé avecl’option -pg. gprof donne en plus d’une sortie compa- rable à celle de gprof,legraphe d’appel des fonctions avecles 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 cor- respondent à 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 avecdes parenthèses, et l’étoile (*) ne peut s’appliquer qu’à une expression régulière s’exp- rimant 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 unpeu comme doxygen fait av ecdes 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 bib- liothè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éutilis- able 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 bib- liothè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 trouvelefichier «.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.Ildé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 avecunnombre 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 avecleCANSI 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’) con- stituent 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_makesuivant spécifie que ’turlututu’ dépend des deux fichiers ’toto.o’ et ’titi.o’ con- struits à 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_makeune 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.Ilsupporte le développement de projets en Java,mais aussi avecd’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 - tialisées) et T un nom défini dans la section texte de programme. Avecl’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 administra- teurs 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 àunouplusieurs fichiers. Les modifications sont faites en place ; on peut demander une copie de sauveg arde des fichiers avant modification avec l’option -b. patch détecte automatiquement si les différences sont contextuelles (produites avecl’option -c)ouauformat 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.Cedernier fichier est produit automatiquement pour toute exécution d’un programme compilé avecl’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. Av ecl’option -a,tous les symboles sont utilisés et non seulement les symboles externes. Avecl’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 − makearandom 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’indexdes 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 avecleurs 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 avecl’option -e sous GNU, echo comprend également quelques séquences d’échappement du langage C: \b « » \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 envo yé. On peut spécifier le signal par son numéro ou par son nom (sans SIG). kill -l rappelle la liste des sig- naux. Avecbash 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 tou- jours le processus identifié par nnn. Parconvention, 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’envo yer le signal à chaque processus.

NOM nice − nice − mignon SYNTAXE nice [-nombre] commande DESCRIPTION nice exécute la commande avecune 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 car- actè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. Pardé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,. . .) àlaplace de la date de dernière modification du fichier pour le tri (-t)oul’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 « » (/) 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,legroupe du créateur,les autres), le nombre de liens, le nom du créateur,lataille 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)oupour l’affichage (-l). Notons enfin l’option h non standard bien pratique avecl’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 ter- minal 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 ». Av ecl’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 avecles 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 (l) flag associé au processus. 0: « swappé », 1: enmémoire, 2 :processus système, 4 :en

42 Petit manuel Unix 2002 DEMANDES D’ÉTATS

attente, 10 :encours de « swapping ».

S (l) état du processus. 0 :non existant, S :endormi, W :enattente, R :enexécution, I : intermédiaire, Z :terminé, T :arrêté, X :encroissance.

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é av ecune 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 avecleur identifiant PID, le terminal de contrôle TT,letemps total unité centrale utilisé TIME, l’état du processus STATEetlenom de la com- mande COMMAND. L’état est donné avec4lettres, exemple « RWNA ». La première lettre indique si le processus est éligible ou non : Réligible Tprocessus stoppé Penattente d’une page Dattente non interruptible Sendormi 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. Wswappé >leprocessus 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 Nlapriorité du processus est réduite

Petit manuel Unix 2002 43 DEMANDES D’ÉTATS

%CPU pourcentage de temps CPU utilisé (moyenne sur la dernière minute).

NI modification de la priorité (cf nice).

SZ

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.

PA GEIN 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.

44 Petit manuel Unix 2002 DEMANDES D’ÉTATS

CP utilisation CPU à court terme utilisé pour l’ordonnancement.

PRI priorité du processus (valeur négative encas 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é :lenom 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 enpré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éfini- tion 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 ) pour la racine carrée length(expression ) pour le nombredechiffres significatifs scale(expression ) pour le nombredechiffres après la virgule l( expression, expression, ...) pour un appel de fonction Opérateurs +-*/%ˆ %pour le reste,ˆpour la puissance ++ -- pré et post incrémentation == <= >= != < > opérateursrelationnels =+=-=*=/=%=ˆ= 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){ le nom est sur une lettrel auto l, ...,l définition de variables locales instruction; ... instruction return(expression ) } 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 argu- ment 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 syntaxeplus 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 : 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.Nemarche pas si a vaut seulement /, car expr le

48 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 trouveetaffiche 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,ilfaut faire précéder le numéro de l’option -s.Lavariable d’environnement MANPATH précise quels sont les répertoires dans lesquels on peut trouver des chapitres du manuel. Av ecl’option -k man affiche les noms des commandes dont le nom ou la description brèvecontiennent 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 trouvedans /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) décrit la commande man, alors que man(7) décrit le paquetage de macros de formatage du manuel : $man man $man 7 man $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 avecledroit r. -w fichier vrai si le fichier existe avecledroit w. -x fichier vrai si le fichier existe avecledroit 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 avecune 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é avecunterminal. -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 avecles 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 aune 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 ;lavôtre est : n°[email protected] Vous avezlapossibilité de créer des alias du style : [email protected] Vosenseignants 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.Sielle contient des messages, mail affiche leur nombre et le nombre d’entre eux que vous n’avezjamais 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 aveclasimple commande mail.Vous pouvez le lire par l’interface web ou à l’aide de programmes clients dont les principaux sont : thunderbird, claws-mail, kmail,ouenfin avecles 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)ounon (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) avecl’usager.Cedernier 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 com- mandes sont : cd répertoire pwd dir put nom-local [ nom-distant ] get nom-distant [ nom-local ] On peut préférer utiliser un programme avecinterface 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 trans- port. 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 avezlapossibilité de créer votre page personnelle qui sera accessible par l’URL : http://votre_login.perso.info.unicaen.fr/ Les directivespour activervotre 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 unaffichage périodique tous les délaissecondes à 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 av ecunslash 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 : crépertoire courant eexécutable chargé ffichier ouvert Ffichier ouvert en écriture rrépertoire racine mfichier mappé en mémoire ou bibliothèque partagée Av ec -k,unsignal est envo yéàchaque processus. Par défaut SIGKILL est envo yé, 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’envo yer 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 (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. Avecles 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 vnppermettent 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 dis- tante.

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 --ver- sion). -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élaissec- ondes.

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 [,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 simul- tanément la touche Méta (parfois Alt aveccertains claviers) et le caractère. Attention les touches contrôle et méta sont des modificateurs qu’il faut enfoncer simultanément avecune autre touche (comme pour les majuscules), alors que est un caractère ASCII. emacs possède des modes lui permettant, en particulier,defaire 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 aveccomme nom le nom du fichier plus un tilde (˜). En cours de travail, emacs sauveg arde 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-f Files->Open File find-file charge un fichier C-x C-v find-alternate-file remplace un fichier C-x i Files->Insert File insert-file insère un fichier sous le curseur C-x C-s Files->Save Buffer save-buffer enregistre le fichier C-x C-w Files->Save Buffer As write-filed enregistre sous ... C-x C-c Files->Exit Emacs save-buffers-kill-emacs sort d’Emacs C-x b Buffers->tampon switch-to-buffer affiche le buffer choisi C-x C-b Buffers->list All Buffers list-buffers affiche la liste des tampons Déplacement, édition, suppression, régions et recouvrement

Séquence Commande Action

C-a beginning-of-line début de la ligne C-b backward-char caractère précédent C-e end-of-line fin de ligne C-f forward-char caractère suivant C-n next-line ligne suivante C-o open-line ouvre la ligne C-p previous-line ligne précédente C-t transpose-chars échange deux caractères C-v scroll-up défilement vers le haut

C-d ou Suppr delete-char suppr.ducar.sous le curseur M-d kill-word suppr.dumot suivant M-DEL backward-kill-word suppr.dumot précédent C-k kill-line suppr.dureste de la ligne

58 Petit manuel Unix 2002 ÉDITEURS DE TEXTES

C-w kill-region suppr.delarégion marquée M-w kill-ring-save copie la région C-y yank Recopie la dernière suppression C-@ ou C-espace set-mark-command Marque la fin ou le début d’une région C- undo annuler Recherche et substitution

Séquence Suppression

C-s Lance une recherche incrémentale C-r Recherche incrémentale arrière RETURN Sortie de la recherche en cours C-g Annule la recherche en cours DEL Efface un caractère de la chaîne de recherche C-s RETURN Recherche non incrémentale C-r RETURN Recherche arrière non incrémentale M- Substitution interactive espace ou y Affectue la substitution et reprend la recherche DEL ou n 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 RETURN Termine la fonction Les fenêtres et les cadres

Séquence Suppression

C-x 2 Découpe la fenêtre en deux C-x o Passe à la fenêtre suivante C-x 0 Supprime la fenêtre courante C-x 1 Supprime toutes les fenêtres sauf la courante C-x Augmente la hauteur M-C-v Fait défiler la fenêtre suivante C-x 4 f Ouvre un fichier dans la fenêtre suivante.

C-x 5 o Active lecadre suivant C-x 5 0 Supprime le cadre courant C-x 5 2 Crée un nouveau cadre contenant le tampon courant C-x 5 C-f Créé un nouveau cadre avecunnouveau fichier C-x 5 b Créé un nouveau cadre contenant un autre tampon La souris

Séquence Commande Action

C-down-mouse-3 mouse-major-mode-menu menu du mode majeur S-down-mouse-1 mouse-set-font choix de la fonte C-down-mouse-1 mouse-buffer-menu menu tampon mouse-3 mouse-save-then-kill copie et efface mouse-2 mouse-yank-at-click colle mouse-1 mouse-set-point place le curseur double-mouse-1 mouse-set-point sélectionne le mot triple-mouse-1 mouse-set-point sélectionne la ligne

Petit manuel Unix 2002 59 ÉDITEURS DE TEXTES

Toutes les commandes (Emacs Wall Chart)

Clé Commande Clé Commande

C-@ set-mark-command C-r isearch-backward C-a beginning-of-line C-s isearch-forward C-b backward-char C-t transpose-chars C-d delete-char C-u universal-argument C-e end-of-line C-v scroll-up C-f forward-char C-w kill-region C-g keyboard-quit C-x Control-X-prefix C-h help-command C-y hilit-yank TAB indent-for-tab-command C-z shell C-k kill-line ESC ESC-prefix C-l hilit-recenter C-\ toggle-input-method RET newline C-] abort-recursive-edit C-n next-line C-_ undo C-o open-line DEL delete-backward-char C-p previous-line

C-h h view-hello-file C-h C-f Info-goto-emacs-command-node C-h C describe-coding-system C-h 4 Prefix Command C-h I describe-input-method C-h i info C-h C-\ describe-input-method C-h F view-emacs-FAQ C-h L describe-language-environment C-h f describe-function C-h C-l describe-language-environment C-h d describe-funct C-h q help-quit C-h k describe-key C-h v describe-variable C-h c describe-key-briefly C-h w where-is C-h b describe-bindings C-h t help-with-tutorial C-h a apropos-command C-h s describe-syntax C-h C-p describe-project C-h p finder-by-keyword C-h C-w describe-no-warranty C-h n view-emacs-news C-h C-d describe-distribution C-h C-n view-emacs-news C-h C-c describe-copying C-h m describe-mode C-h ? help-for-help C-h l view-lossage C-h f1 help-for-help C-h TAB info-lookup-symbol C-h help help-for-help C-h C-k Info-goto-emacs-key-command-node C-h C-h help-for-help

C-x RET l set-language-environment C-x RET p set-buffer-process-coding-system C-x RET c universal-coding-system-argument C-x RET k set-keyboard-coding-system C-x RET C-\ set-input-method C-x RET t set-terminal-coding-system C-x RET X set-next-selection-coding-system C-x RET f set-buffer-file-coding-system C-x RET x set-selection-coding-system

S-C-l hilit-repaint-command deletechar delete-char delete delete-char deleteline kill-line C-down-mouse-3 mouse-major-mode-menu S-insert hilit-yank S-down-mouse-1 mouse-set-font C-insert kill-ring-save C-down-mouse-1 mouse-buffer-menu insert overwrite-mode mouse-3 mouse-save-then-kill M-begin beginning-of-buffer-other-window mouse-2 mouse-yank-at-click begin beginning-of-buffer triple-mouse-1 mouse-set-point M-end end-of-buffer-other-window

60 Petit manuel Unix 2002 ÉDITEURS DE TEXTES

double-mouse-1 mouse-set-point end end-of-buffer drag-mouse-1 mouse-set-region M-prior scroll-other-window-down mouse-1 mouse-set-point M-next scroll-other-window down-mouse-1 mouse-drag-region C-next scroll-left M-mouse-2 mouse-yank-secondary C-prior scroll-right M-mouse-3 mouse-secondary-save-then-kill C-down forward-paragraph M-down-mouse-1 mouse-drag-secondary C-up backward-paragraph M-drag-mouse-1 mouse-set-secondary next scroll-up M-mouse-1 mouse-start-secondary prior scroll-down C-down-mouse-2 facemenu-menu down next-line S-delete kill-region right forward-char C-delete backward-kill-word up previous-line C-left backward-word left backward-char C-right forward-word M-home beginning-of-buffer-other-window M-left backward-word home beginning-of-buffer M-right forward-word C-SPC set-mark-command mouse-movement ignore C-/ C-_ undo

C-x 4 0 kill-buffer-and-window C-x 4 b switch-to-buffer-other-window C-x 4 . find-tag-other-window C-x 4 C-f find-file-other-window C-x 4 d dired-other-window C-x 4 r find-file-read-only-other-window C-x 4 a add-change-log-entry-other-window C-x 4 f find-file-other-window C-x 4 C-o display-buffer C-x 4 m compose-mail-other-window

C-x 5 o other-frame C-x 5 r find-file-read-only-other-frame C-x 5 0 delete-frame C-x 5 C-f find-file-other-frame C-x 5 2 make-frame-command C-x 5 f find-file-other-frame C-x 5 . find-tag-other-frame C-x 5 b switch-to-buffer-other-frame C-x 5 d dired-other-frame C-x 5 m compose-mail-other-frame

C-x C-b list-buffers C-x 6 2C-command C-x C-c save-buffers-kill-emacs C-x 8 8859-1-map C-x C-d list-directory C-x ; set-comment-column C-x C-e eval-last-sexp C-x < scroll-left C-x C-f find-file C-x = what-cursor-position C-x TAB indent-rigidly C-x > scroll-right C-x C-k edit-kbd-macro C-x [ backward-page C-x C-l downcase-region C-x ] forward-page C-x C-n set-goal-column C-x ˆ enlarge-window C-x C-o delete-blank-lines C-x ‘ next-error C-x C-p mark-page C-x a Prefix Command C-x C-q vc-toggle-read-only C-x b switch-to-buffer C-x C-r find-file-read-only C-x d dired C-x C-s save-buffer C-x e call-last-kbd-macro C-x C-t transpose-lines C-x f set-fill-column C-x C-u upcase-region C-x g insert-register-compatibility-binding C-x C-v find-alternate-file C-x h mark-whole-buffer C-x C-w write-file C-x i insert-file C-x C-x exchange-point-and-mark C-x j jump-to-register-compatibility-binding C-x C-z iconify-or-deiconify-frame C-x k kill-this-buffer C-x ESC Prefix Command C-x l count-lines-page C-x $ set-selective-display C-x m compose-mail C-x ’ expand-abbrev C-x n Prefix Command

Petit manuel Unix 2002 61 ÉDITEURS DE TEXTES

C-x ( start-kbd-macro C-x o other-window C-x ) end-kbd-macro C-x q kbd-macro-query C-x + balance-windows C-x r Prefix Command C-x - shrink-window-if-larger-than-buffer C-x s save-some-buffers C-x . set-fill-prefix C-x u advertised-undo C-x / point-to-register-compatibility-binding C-x v Prefix Command C-x 0 delete-window C-x x copy-to-register-compatibility-binding C-x 1 delete-other-windows C-x z repeat C-x 2 split-window-vertically C-x { shrink-window-horizontally C-x 3 split-window-horizontally C-x } enlarge-window-horizontally C-x 4 ctl-x-4-prefix C-x DEL backward-kill-sentence C-x 5 ctl-x-5-prefix C-x C-SPC pop-global-mark

C-x a n expand-jump-to-next-slot C-x a i Prefix Command C-x a p expand-jump-to-previous-slot C-x a + add-mode-abbrev C-x a ’ expand-abbrev C-x a g add-global-abbrev C-x a e expand-abbrev C-x a C-a add-mode-abbrev C-x a - inverse-add-global-abbrev C-x a l add-mode-abbrev

C-x n p narrow-to-page C-x n w widen C-x n d narrow-to-defun C-x n n narrow-to-region

ESC C-@ mark-sexp ESC < beginning-of-buffer ESC C-a beginning-of-defun ESC = count-lines-region ESC C-b backward-sexp ESC > end-of-buffer ESC C-c exit-recursive-edit ESC @ mark-word ESC C-d down-list ESC delete-horizontal-space ESC C-e end-of-defun ESC ˆ delete-indentation ESC C-f forward-sexp ESC ‘ tmm-menubar ESC C-h mark-defun ESC a backward-sentence ESC TAB complete-symbol ESC b backward-word ESC C-j indent-new-comment-line ESC c capitalize-word ESC C-k kill-sexp ESC d kill-word ESC C-l reposition-window ESC e forward-sentence ESC C-n forward-list ESC f forward-word ESC C-o split-line ESC g goto-line ESC C-p backward-list ESC h mark-paragraph ESC C-q fill-region ESC i tab-to-tab-stop ESC C-r isearch-backward-regexp ESC j indent-new-comment-line ESC C-s isearch-forward-regexp ESC k kill-sentence ESC C-t transpose-sexps ESC l downcase-word ESC C-u backward-up-list ESC m compile ESC C-v scroll-other-window ESC q fill-paragraph ESC C-w append-next-kill ESC r move-to-window-line ESC ESC Prefix Command ESC t transpose-words ESC C-\ indent-region ESC u upcase-word ESC SPC just-one-space ESC v scroll-down ESC ! shell-command ESC w kill-ring-save ESC # calc-dispatch ESC x execute-extended-command ESC $ ispell-word ESC y hilit-yank-pop ESC % query-replace ESC z zap-to-char ESC ’ abbrev-prefix-mark ESC { shrink-window ESC ( backward-list ESC | shell-command-on-region

62 Petit manuel Unix 2002 ÉDITEURS DE TEXTES

ESC ) forward-list ESC } enlarge-window ESC * pop-tag-mark ESC ˜ not-modified ESC , tags-loop-continue ESC DEL backward-kill-word ESC - negative-argument ESC C-% query-replace-regexp ESC . find-tag ESC C-. find-tag-regexp ESC / dabbrev-expand ESC C-/ dabbrev-completion ESC 0 .. ESC 9 digit-argument ESC S-C-v scroll-other-window-down ESC : eval-expression ESC C-SPC mark-sexp ESC ; indent-for-comment ESC C-- negative-argument

C-x r l bookmark-bmenu-list C-x v ˜ vc-version-other-window C-x r m bookmark-set C-x v = vc-diff C-x r b bookmark-jump C-x v v vc-next-action C-x r f frame-configuration-to-register C-x v u vc-revert-buffer C-x r w window-configuration-to-register C-x v s vc-create-snapshot C-x r t string-rectangle C-x v r vc-retrieve-snapshot C-x r o open-rectangle C-x v m vc-merge C-x r y yank-rectangle C-x v l vc-print-log C-x r d delete-rectangle C-x v i vc-register C-x r k kill-rectangle C-x v h vc-insert-headers C-x r c clear-rectangle C-x v g vc-annotate C-x r + increment-register C-x v d vc-directory C-x r n number-to-register C-x v c vc-cancel-version C-x r r copy-rectangle-to-register C-x v a vc-update-change-log C-x r g insert-register C-x r i insert-register C-x r x copy-to-register C-x r s copy-to-register C-x r j jump-to-register C-x r SPC point-to-register C-x r C-SPC point-to-register C-x r C-@ point-to-register Si vous êtres fatigués essayer les commandes M-Xhanoi ou M-Xdoctor.Pour finir,voici deux significations possibles d’emacs comme acronyme : Escape-Meta-Alt-Control-Shift Emacs Makes All Computing Simple

NOM nano - Nano’sANOther editor - NAno un NOuvel éditeur SYNTAXE nano [ fichier ] DESCRIPTION nano est un petit éditeur plein écran qui peut fonctionner avecdes modes d’éditions (comme vi)ousans (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 sig- nifie 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’- versité de Washington. Il comporte quatre sections principales :laligne du haut affiche la version du pro- gramme, le fichier actuellement en cours d’édition et s’il a été modifié ou non. En dessous se trouvela 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 rac- courcis 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 succes- sivement 2fois 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 prin- cipale de l’éditeur.Les combinaisons pouvant être utilisées comme alternativessont affichées entre par- enthèses :

C-G (F1) Affiche de message C-X (F2) Fermer l’espace en cours / Quitter nano C-O (F3) Écrire le fichier en cours sur le disque C-J (F4) Justifier le paragraphe courant

C-R (F5) Insérer un autre fichier dans l’espace en cours C-W (F6) Recherche d’une chaîne ou d’une expression rationnelle C-Y (F7) Aller à l’écran précédent C-V (F8) Aller à l’écran suivant

C-K (F9) Couper la ligne courante vers le presse-papiers C-U (F10) Coller le presse-papiers à partir de la ligne courante C-C (F11) Indiquer la position du curseur C-T (F12) Appeler le correcteur orthographique (si dispo.)

C-_ (F13) (M-G) Aller à la ligne et à la colonne indiquées C- (F14) (M-R) Remplacer une chaîne ou une expression rationnelle C-ˆ (F15) (M-A) Marquer le texte à la position du curseur (F16) (M-W) Recommencer la dernière recherche

M-ˆ (M-6) Copier la ligne courante dans le presse-papiers M-} Mise en retrait de la ligne courante M-{ Annuler le retrait de la ligne courante

C-F Av ancer d’un caractère C-B Reculer d’un caractère C-blanc Av ancer d’un mot M-blanc Reculer d’un mot C-P Aller à la ligne précédente C-N Aller à la ligne suivante

C-A Aller au début de la ligne courante C-E Aller à la fin de la ligne courante M-( (M-9) Aller au début du paragraphe M-) (M-0) Aller à la fin du paragraphe M- (M-|) Aller à la première ligne du fichier M-/ (M-?) Aller à la dernière ligne du fichier

M-] Aller au crochet correspondant M-- (M-_) Remonter d’une ligne sans déplacer le curseur

64 Petit manuel Unix 2002 ÉDITEURS DE TEXTES

M-+ (M-=) Descendre d’une ligne sans déplacer le curseur

M-< (M-,) Basculer vers l’espace précédent M-> (M-.) Basculer vers l’espace suivant

M-V Insérer le prochain caractère tel quel C-I Insérer une tabulation à la position du curseur C-M Insérer un passage à la ligne à la position du curseur C-D Supprimer le caractère sous le curseur C-H Supprimer le caractère à la gauche du curseur M-T Coupe du curseur à la fin du fichier

M-J Justifier le fichier entier M-D Compter le nombre de mots, de lignes et de caractères C-L Rafraîchir (redessiner) l’écran courant

M-X Mode aide (commutateur) M-C Afficher la position du curseur (commutateur) M-O Utiliser 1 ligne de plus pour l’édition (commutateur) M-S Défilement progressif (commutateur) M-P Afficher les blancs (commutateur) M-Y Colorisation syntaxique (commutateur)

M-H Touche « Début » intelligente (commutateur) M-I Indenter automatiquement (commutateur) M-K Couper jusqu’en fin de ligne (commutateur) M-L Passer à la ligne automatiquement (commutateur) M-Q La touche tabulation ajoute des espaces (commutateur)

M-B Conserver des copies de sécurité (commutateur) M-F Mode multi-espace (commutateur) M-M Utiliser la souris (commutateur) M-N Pasdeconversion des formats DOS et Mac (commutateur) M-Z 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 com- mandes de ed(1) en les préfixant par :.Son grand inconvénient est de travailler par modes (mode com- mande/mode insertion) ce qui est relativement insupportable pour un utilisateur d’emacs.Jenevais donc vous donnez ici que la façon de sortir de vi,cequi est la seule chose raisonnable à faire si on y est entré par inadvertance : 1- sortir éventuellement du mode d’insertion en tapant : 2- sortir de l’éditeur sans enregistrer les modifications aveclaséquence de 4 caractères : :q!

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 troffetgroff: 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 avecman. .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 tabula- tion (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 con- servées. On peut également mettre dans le texte la commande \fx,avecxvalant R, I, H, S, C et P pour respec- tivement : 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 titresection date source manuel Exemple : .TH MAN 7 "25 July 1993" "Linux" "Linux Programmer’sManual" 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 avecitaliques .BR Gras alternant avecRoman .I Italiques .IB Italiques alternant avecgras .IR Italiques alternant avecRoman .RB Roman alternant avecgras .RI Roman alternant avecitaliques .SB Petit alternant avecgras .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,upour 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é avecledrapeau 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é avecundrapeau 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 χ majuscule ‘X’ est non un simple x majuscule. Ce com- poseur de textes donne de merveilleux résultats, mais sa description brèvedé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 aveccontrôle et coloration syntaxique, gestionnaire de courrier (RMAIL ou vm), lecteur de news (GNUS). La souris s’utilise avecles conventions suivantes : Bouton 1 (gauche) sélection Bouton 2 (milieu) insérer sélection (paste) Bouton 3 (droite) extension de sélection Un clic avecControl ou Shift fait apparaître des menus. Les commandes d’édition de lignes d’emacs sont disponibles dans beaucoup de champ texte (netscape, out- ils faits avecGTK+, ...) 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 avecX11. 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 informa- tions 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 Post- Script 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/)apour 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 CORBApour communi- quer.Les principaux composants sont :letableur gnumeric,letraitement de texte abiword,levisualiseur 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 ;ilpermet (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,dutraitement de texte openwriter,del’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) avecson 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 gqviewqui 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’envo yer 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 manyfeatures which makeitappear 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 fewBerkeleyextensions, 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 flowcon- trol 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 manyfeatures to aid interactive use and has the advan- tage 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 theyexist. If the envi- ronment 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. Toset 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” anyfilename 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’toverwrite existing files with “>”. −e errexit If not interactive,exit immediately if anyuntested 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;orifthe 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’sfrom input when interactive. −i interactive Force the shell to behave interactively. −l Makedash act as if it had been invokedasalogin 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. (UNIM- PLEMENTED 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 twotypes of operators: control operators and redirection operators (their meaning is discussed later). Following is a list of operators: Control operators: &&&();;; | ||

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 Abackslash 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: $‘"\. Otherwise it remains literal.

ReservedWords 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: !elif fi while case else for then { } do done until if esac Their meaning is discussed later.

Aliases An alias is a name and corresponding value set using the alias(1) builtin command. Wheneverareserved 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 howtocreate functions with arguments. Theycan 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 complexcommand or some other special construct may have been recog- nized.

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 offand assigned to the environment of the simple command. Redirection operators and their arguments (as described below) are stripped offand savedfor 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] isanoptional number,asin‘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 savedawayand made available to the command on stan- dard 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 substi- tution, 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 com- mand is searched for (by name) in that order.Theyeach 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 giveninthe 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 newprocess. Otherwise, if the command name doesn’tmatch a function or builtin, the command is searched for as a nor- mal 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 newshell had been invokedtohandle 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 ashell 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 twothings happen: 1. Command names containing a slash are simply executed without performing anysearches. 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 direc- tory 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,orafalse indication. The man page for each command should indicate the various exit codes and what theymean. 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 Complexcommands are combinations of simple commands with control operators or reserved words, together creating a larger complexcommand. More generally,acommand 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 Apipeline 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 anyredirection 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 NOTofthe 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. Forexample: $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 unlikesome 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 anyeffect it has on the environment is wiped).

Background Commands -- & If a command is terminated by the control operator ampersand (&), the shell executes the command asyn- chronously -- 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 Alist is a sequence of zero or more commands separated by newlines, , 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 pro- ceed 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 iffthe 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 twolists are executed repeatedly while the exit status of the first list is zero. The until command is simi- lar,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 “|” char- acters.

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 theywere one program: {printf " hello " ; printf " world\n" ; } > greeting Note that “}” must followacontrol 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 Afunction 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 makethe 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 vari- able named x. The only special parameter that can be made local is “-”. Making “-” local anyshell 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. Aparameter denoted by a name is called a variable. When starting up, the shell turns all the environment variables into shell variables. Newvariables can be set using the form name=value Variables set by the user must have a name consisting solely of alphabetics, numerics, and - the first of which must not be numeric. Aparameter can also be denoted by a number or a special character as explained below.

Positional Parameters Apositional parameter is a parameter denoted by a number (n > 0). The shell sets these initially to the val- ues of its command line arguments that followthe name of the shell script. The set builtin can also be used to set or reset them.

Special Parameters Aspecial parameter is a parameter denoted by one of the following special characters. The value of the parameter is listed next to its character. ∗ 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, evenwhen @ is double-quoted. What this basically means, for example, is if $1 is “abc” and $2 is “def ghi”, then "$@" expands to the twoarguments:

BSD 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 invokedshell. A subshell retains the same value of $ as its parent. ! Expands to the process ID of the most recent background command executed from the cur- rent shell. Forapipeline, 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’shome directory) Aword 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’shome directory. If the username is missing (as in ˜/foobar), the tilde is replaced with the value of the HOME variable (the current user’shome 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 aquoted 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, ofparameter 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 parame- ters 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.Inall 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 stan- dard 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; other- wise, the expansion of word is substituted. In the parameter expansions shown previously,use of the 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 pat- terns. If parameter is ∗ or @, the result of the expansion is unspecified. Enclosing the full parameter expan- sion 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〉satthe end of the substitution. (Embedded 〈newline〉sbefore the end of the output are not removed; however, during field splitting, theymay 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 sub- stitution, 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 parame- ter 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 tworestrictions 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 pat- tern is a period. The next section describes the patterns used for both Pathname Expansion and the case command.

Shell Patterns Apattern consists of normal characters, which match themselves, and meta-characters. The meta-characters are “!”, “∗”, “?”, and “[”. These characters lose their special meanings if theyare 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 theyare turned into meta-char- acters. An asterisk (“∗”) matches anystring of characters. Aquestion mark matches anysingle character.Aleft ( “[” ) 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. Acharacter class matches any of the characters between the square . 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, makeitthe first character listed (after the “!”, if any). Toinclude a minus sign, makeitthe 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 theyneed to perform some operation that can’tbeperformed 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 Anull 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.Ifjust 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 com- mand 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.Ifasingle 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 gav e.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 offthe effect of anypreceding −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 anyofthe following sequences of characters is encountered during output, the sequence is not out- put. Instead, the specified action is performed: \b Abackspace 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.

BSD January 19, 2003 82 DASH (1) BSD General Commands Manual DASH (1)

\n Output a newline character. \r Output a carriage return. \t Output a (horizontal) tab character. \v Output a vertical tab. \0digits Output the character whose value is givenbyzero 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 areal program, not a shell builtin or function). Anyredirections on the exec command are marked as permanent, so that theyare not undone when the exec command finishes. exit [exitstatus] Terminate the shell process. If exitstatus is givenitisused as the exit status of the shell; other- wise the exit status of the preceding command is used. export name . .. export −p The specified names are exported so that theywill appear in the environment of subsequent com- mands. 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 vari- able 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 pre- ceded by the command number. −n Suppress command numbers when listing with -l.

83 January 19, 2003 BSD DASH (1) BSD General Commands Manual DASH (1)

−r Reverse the order of the commands listed (with −l)oredited (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 Apositive number representing a command number; command numbers can be dis- played with the −l option. −number Aneg ative decimal number representing the command that was executed number of commands previously.For example, −1 is the immediately previous command. string Astring indicating the most recently entered command that begins with that string. If the old=newoperand 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 indexinthe shell variable OPTIND.When the shell is invoked, OPTIND is initialized to 1. Foreach option that requires an argument, the getopts builtin will place it in the shell variable OPTARG.Ifanoption is not allowed for in the optstring,then OPTARG will be unset. optstring is a string of recognized option letters (see getopt(3)). If aletter is followed by a colon, the option is expected to have anargument 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.Byspecifying a colon as the first character of optstring all errors will be ignored. Anonzero 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 howone might process the arguments for a command that can takethe 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 anyofthe following as equivalent: cmd −acarg file file cmd −a −c arg file file cmd −carg -a file file cmd −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 removesthe specified commands from the hash table (unless theyare functions) and then locates them. With the −v option, hash prints the locations of the com- mands 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.Howev er, ifthe 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 work- ing directory to be shown, that is, all symbolic links are resolved to their respective values. The −L option turns offthe effect of anypreceding −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.Ifabackslash 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,sothat theycannot 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: • Aleading 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 speci- fications 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 character. \b Write a character. \f Write a character. \n Write a character. \r Write a character. \t Write a character. \v Write a 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: # 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. Forthe 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, evenif no digits followthe point (normally,adecimal 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 removedfrom the result as theywould otherwise be. − Aminus 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 num- ber when using signed formats.

BSD January 19, 2003 86 DASH (1) BSD General Commands Manual DASH (1)

‘’ Aspace specifying that a blank should be left before a positive number for a signed format. A ‘+’ overrides a space if both are used; 0 Azero ‘0’ character indicating that zero-padding should be used rather than blank- padding. A ‘−’ overrides a ‘0’ if both are used; Field Width: An optional digit string specifying a field width;ifthe 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 makeupthe field width (note that a leading zero is a flag, but an embed- ded zero is part of a field width); Precision: An optional period, ‘.’, followed by an optional digit string giving a precision which speci- fies the number of digits to appear after the decimal point, for e and f formats, or the maxi- mum 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: Acharacter which indicates the type of format to use (one of diouxXfwEgGbcs). Afield 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 deci- mal, or unsigned hexadecimal (X or x), respectively. f The argument is printed in the style [−]ddd.ddd where the number of d’safter 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 )whichevergiv esfull 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 anyremaining characters in the string operand contain- ing it, anyremaining string operands, and anyadditional characters in the for- mat operand. \0num Write an 8−bit character whose ASCII value is the 1−, 2−, or 3−digit octal number num. 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.

87 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.Asaspecial 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 human- readable 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’spositional parameters to the speci- fied args. Tochange the positional parameters without changing anyoptions, 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 stickybit 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 evenifthis 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 compatibil- ity 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 anyofthe specified signals are received. The sig- nals 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 offasubshell, it resets trapped (but not ignored) signals to the default action. The trap com- mand has no effect on signals that were ignored on entry to the shell. trap without anyarguments 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 achievesthe 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 resolu- tions are: shell keyword, alias, shell builtin, command, tracked alias and not found. Foraliases 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 newlimits. 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 dis- played 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 anyone of these flags: −a showall the current limits −t showorset the limit on CPU time (in seconds) −f showorset the limit on the largest file that can be created (in 512-byte blocks) −d showorset the limit on the data segment size of a process (in kilobytes) −s showorset the limit on the stack size of a process (in kilobytes) −c showorset the limit on the largest core dump size that can be produced (in 512-byte blocks)

BSD January 19, 2003 90 DASH (1) BSD General Commands Manual DASH (1)

−m showorset the limit on the total physical memory that can be in use by a process (in kilobytes) −l showorset the limit on howmuch memory a process can lock with mlock(2) (in kilo- bytes) −p showorset the limit on the number of processes this user can have atone time −n showorset 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 removesthat 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 corre- sponding function or variable is unset, respectively.Ifagiv enname 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.Ifthe 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 vi- mode 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’ssimi- lar to vi: typing 〈ESC〉 will throwyou 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 Set automatically by login(1) from the user’slogin 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 arrivalofnew mail. Overridden by MAILPATH.

91 January 19, 2003 BSD DASH (1) BSD General Commands Manual DASH (1)

MAILCHECK The frequencyinseconds that the shell checks for the arrivalofmail in the files specified by the MAILPATH or the MAIL file. If set to 0, the check will occur at each prompt. MAILPATH Acolon “:” separated list of file names, for the shell to check for incoming mail. This envi- ronment 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,inwhich 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 theyare 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.Itisused to create, display,modify and otherwise manipulate text files. red is a restricted ed:itcan only edit files in the current directory and cannot execute shell commands.

If invokedwith a file argument, then a copyof file is read into the editor’sbuffer.Changes are made to this copyand not directly to file itself. Upon quitting ed,any changes not explicitly savedwith a ‘w’ command are lost.

Editing is done in twodistinct 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.Atypical 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 (.)onaline.

All ed commands operate on whole lines or ranges of lines; e.g., the ‘d’ command deletes lines; the ‘m’ command moveslines, and so on. It is possible to modify only a portion of a line by means of replacement, as in the example above.Howev erevenhere, 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 giventhan the command accepts, then default addresses are supplied.

OPTIONS -G Forces backwards compatibility.Affects the commands ‘G’, ‘V’, ‘f ’, ‘l’, ‘m’, ‘t’,and ‘!!’. -s 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 offwith 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 file- name 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.

Aline address is constructed from one of the bases in the list below, optionally followed by a numeric off- set. The offset may include anycombination of digits, operators (i.e., +, - and ˆ)and whitespace. Addresses are read from left to right, and their values are computed relative tothe 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 legalwhereveritmakes sense.

An address range is twoaddresses separated either by a or . The value of the first address in a range cannot exceed the value of the the second. If only one address is giveninarange, then the sec- ond address is set to the givenaddress. If an n-tuple of addresses is givenwhere n>2, then the corre- sponding range is determined by the last twoaddresses 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 tothe current address. In a semicolon- delimited range, the first address is used to set the current address, and the second address is interpreted rel- ative tothe 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.

, % The first through last lines in the buffer.This is equivalent to the address range 1,$.

94 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 buf- fer 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 Anycharacter c not listed below, including ‘{’, ’}’, ‘(’, ‘)’, ‘<’ and ‘>’, matches itself.

\c Abackslash-escaped character c other than ‘{’, ’}’, ‘(’, ‘)’, ‘<’, ‘>’, ‘b’, ’B’, ‘w’, ‘W’, ‘+’, and ‘?’ matches itself.

. Matches anysingle character.

[char-class] Matches anysingle character in char-class.Toinclude a ‘]’ in char-class,itmust be the first character.Arange 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:] [:alpha:] [:digit:] [:print:] [:upper:] [:blank:] [:graph:] [:punct:] [:xdigit:]

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 sup- ported). See regex(3) for an explanation of these constructs.

10 November 1994 95 ED(1) ED(1)

[ˆchar-class] Matches anysingle 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. Asubsequent back- reference 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 totheir left delimiter.

∗ Matches the single character regular expression or subexpression immediately preceding it zero or more times. If ’∗’isthe first character of a regular expression or subexpression, then it matches itself. The ‘∗’operator sometimes yields unexpected results. Forexample, 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 anyofthese 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 charac- ters, including the (_).

The following extended operators are preceded by a backslash (\) to distinguish them from traditional ed syntax.

\‘ \’ Unconditionally matches the beginning (\‘) or ending (\’) of a line.

\? Optionally matches the single character regular expression or subexpression immediately preced- ing it. Forexample, 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 ‘\’. However, ‘\b\b’ is a valid regular expression whereas ‘\<\>’ is not.

96 10 November 1994 ED(1) ED(1)

\B Matches (a null string) inside a word.

\w Matches anycharacter in a word.

\W Matches anycharacter not in a word.

COMMANDS All ed commands are single characters, though some require additonal parameters. If a command’sparam- eters extend oversev eral 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 anyof‘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 com- mand 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). Te xtis 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. Te xtisentered in input mode. The current address is set to last line entered.

(.,.)d Deletes the addressed lines from the buffer.Ifthere is a line after the deleted range, then the cur- rent 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. Anylines in the buffer are deleted before the newfile 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. Anylines in the buffer are deleted before the output of command is read. The cur- rent 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 cur- rent 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 (\). Anycommands are allowed, except for ‘g’, ‘G’, ‘v’,and ‘V’.Anewline 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 . Foreach 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) com- mand-list.

The format of command-list is the same as that of the ‘g’ command. A newline alone acts as a null command list. Asingle ‘&’ repeats the last non-null command list.

H Toggles the printing of error explanations. By default, explanations are not printed. It is recom- mended 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. Te xtisentered 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 sin- gle 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 )insubsequent commands. The mark is not cleared until the line is deleted or oth- erwise modified.

(.,.)l Prints the addressed lines unambiguously.Ifinv okedfrom 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(.) Moveslines in the buffer.The addressed lines are movedtoafter 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 invokedfrom 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 aprompt 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.Other- wise, 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 anyofthe addressed lines. The current address is set the last line affected.

re and replacement may be delimited by anycharacter other than space and newline (see the ‘s’ command below). If one or twoofthe 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 theyare escaped with abackslash (\).

(.,.)s Repeats the last substitution. This form of the ‘s’ command accepts a count suffix ‘n’,orany combination of the characters ‘r’, ‘g’,and ‘p’.Ifacount 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 sub- stitution. 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 owninv erse.

(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 file- name 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 asemicolon 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.∗ Buffer file ed.hup 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, SoftwareTools in Pascal , Addison-Wesley, 1981.

LIMITATIONS ed processes file arguments for backslash escapes, i.e., in a filename, anycharacters preceded by a back- slash (\) 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) com- mand.

Attempting to quit ed or edit another file before writing a modified buffer results in an error.Ifthe

100 10 November 1994 ED(1) ED(1)

command is entered a second time, it succeeds, but anychanges 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’simplementation of the AWK programming language. It conforms to the defini- tion 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,byAho, 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. Multi- ple −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 theymay 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,tothe 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 twoflags and the −m option are from the Bell Labs research version of UNIX awk.Theyare ignored by gawk,since gawk has no pre-defined limits. −W traditional −W compat −−traditional −−compat Run in compatibility mode. In compatibility mode, gawk behavesidentically to UNIX awk;none of the GNU-specific extensions are recognized. The use of −−traditional is preferred overthe 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 implementa- tions. −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.Howev er, their use is likely to break old AWK programs, so gawk only provides them if theyare 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 copyof gawk on the standard output. This is useful mainly for knowing if the current copyof gawk on your system is up to date with respect to what- ev erthe 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 allowfurther arguments to the AWK program itself to start with a ‘‘−’’. This is mainly for consistencywith the argument parsing convention used by most other POSIX programs. In compatibility mode, anyother options are flagged as illegal, but are otherwise ignored. In normal opera- tion, 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. AW KPROGRAM 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 multi- ple times on the command line. Gawk will read the program text as if all the program-filesand command line source texts had been concatenated together.This is useful for building libraries of AWK functions, without having to include them in each newAWK 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 wasbuilt and installed.) If a file name giventothe −f option contains a ‘‘/’’character,nopath 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 con- trol howinput is broken into fields and records. It is also useful for controlling state if multiple passes are needed overasingle data file. If the value of a particular element of ARGV is empty (""), gawk skips overit. Foreach record in the input, gawk tests to see if it matches any pattern in the AWK program. Foreach 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). VA RIABLES, RECORDS AND FIELDS AWKvariables are dynamic; theycome into existence when theyare first used. Their values are either floating-point numbers or strings, or both, depending upon howtheyare used. AWK also has one dimen- sional 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 howrecords are separated by assigning values to the built-in variable RS.If RS is anysingle character,that character separates records. Otherwise, RS is a regular expression. Textinthe input that matches this regular expression will separate the record. However, incompatibility 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,inaddition to whatevervalue 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 howfields are split when FS is a regular expression, and howrecords 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 newvalue 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 anyintervening 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 newvalue 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,orthe pro- gram source). ARGIND The indexin ARGV of the current file being processed. ARGV Array of command line arguments. The array is indexedfrom 0 to ARGC −1.Dynami- cally changing the contents of ARGV can control the files used for data. CONVFMT The conversion format for numbers, "%.6g",bydefault. ENVIRON An array containing the values of the current environment. The array is indexedbythe environment variables, each element being the value of that variable (e.g., ENVI- RON["HOME"] might be /home/arnold). Changing this array does not affect the environment seen by programs which gawk spawns via redirection or the system() func- tion. (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 Awhite-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 ev olves overtime. 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,aspace 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".Aswith 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",bydefault. OFS The output field separator,aspace by default. ORS The output record separator,bydefault a newline. RS The input record separator,bydefault a newline. RT The record terminator. Gawk sets RT to the input text that matched the character or reg- ular expression specified by RS. RSTART The indexofthe first character matched by match();0ifnomatch. RLENGTH The length of the string matched by match();−1ifnomatch. 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 expres- sion 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 indexedbythe string "A\034B\034C".All arrays in AWK are associative,i.e. indexedbystring values. The special operator in may be used in an if or while statement to see if an array has an indexconsisting of aparticular 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 overall 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. Howthe value of a variable is interpreted depends upon its context. If used in a numeric expression, it will be treated as a number,ifused 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, eventhough all numbers in AWK are floating-point, inte- gral 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 twovariables are numeric, theyare 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 per- formed. Two strings are compared, of course, as strings. According to the POSIX standard, eveniftwo 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, theyare string constants. The idea of ‘‘numeric string’’only applies to fields, getline input, FILENAME, ARGV elements, ENVIRON ele- ments 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 AWKisaline 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. Amissing 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,astatement ends with a newline, however, this is not the case for lines end- ing 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 state- ments within the action part of a pattern-action pair (the usual case), and to the pattern-action statements themselves. Patterns AWKpatterns 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 twospecial 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 anyofthe 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 anyofthe operators defined belowinthe section on actions. These gener- ally test whether certain fields match certain regular expressions. The &&, ||,and ! operators are logical AND, logical OR, and logical NOT, respectively,asinC.Theydo 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 likethe 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 rangepattern.Itmatches all input records starting with a record that matches pattern1,and continuing until a record that matches pattern2,inclusive.Itdoes not combine with anyother sort of pattern expression. Regular Expressions Regular expressions are the extended kind found in egrep.Theyare composed of characters as follows: c matches the non-metacharacter c. \c matches the literal character c. . matches anycharacter including newline. ˆ matches the beginning of a string. $ matches the end of a string. [abc...] character list, matches anyofthe characters abc.... [ˆabc...] negated character list, matches anycharacter 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 twonumbers inside braces denote an interval expression.Ifthere is one number in the braces, the preceding regexp r is repeated n times. If there are twonumbers 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 anyword-constituent character (letter,digit, or underscore). \W matches anycharacter 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 legalinregular expressions. Character classes are a newfeature introduced in the POSIX standard. Acharacter class is a special nota- tion for describing lists of characters that have a specific attribute, but where the actual characters them- selves can vary from country to country and/or from character set to character set. Forexample, the notion of what is an alphabetic character differs in the USA and in France. Acharacter 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 [:,akeyword 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 charac- ters). [:space:] Space characters (such as space, tab, and formfeed, to name a few). [:upper:] Upper-case alphabetic characters. [:xdigit:] Characters that are hexadecimal digits. Forexample, before the POSIX standard, to match alphanumeric characters, you would have had to write /[A−Za−z0−9]/.Ifyour 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. Tw o 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 charac- ter,aswell as several characters that are equivalent for collating,orsorting, purposes. (E.g., in French, a plain ‘‘e’’and a grave-accented e` are equivalent.) Collating Symbols Acollating 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 aregexpthat 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`.’’ Inthis case, [[=e]] is a regexp that matches anyof .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; theydonot 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;theyare 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 opera- tors described above.Howev er, 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 expres- sions are not available, and neither are the POSIX character classes ([[:alnum:]] and so on). Char- acters described by octal and hexadecimal escape sequences are treated literally,eveniftheyrep- resent regexp metacharacters. −−re−interval Allowinterval expressions in regexps, evenif −−traditional has been provided. Actions Action statements are enclosed in braces, { and }.Action statements consist of the usual assignment, condi- tional, 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 (...) 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/)onthe 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 evalu- ated.

110 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 overwith 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 overwith 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,astwo words. While this usage is still recognized, it generates a warn- ing 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 vari- able. 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 anybuffers 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 conver- sion specification formats: %c An ASCII character.Ifthe 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 Adecimal number (the integer part). %e %E Afloating point number of the form [−]d.dddddde[+ −]dd.The %E format uses E instead of e. %f Afloating point number of the form [−]ddd.dddddd. %g %G Use %e or %f conversion, whicheverisshorter,with nonsignificant zeros suppressed. The %G format uses %E instead of %e. %o An unsigned octal number (again, an integer). %s Acharacter string. %x %X An unsigned hexadecimal number (an integer). %X format uses ABCDEF instead of abcdef. %% Asingle % 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 Fornumeric 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, evenifthe data to be formatted is positive.The + overrides the space modi- fier. # 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 removedfrom the result. 0 Aleading 0 (zero) acts as a flag, that indicates output should be padded with zeroes instead of spa- ces. This applies eventonon-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 Anumber that specifies the precision to use when printing. Forthe %e, %E,and %f formats, this specifies the number of digits you want printed to the right of the decimal point. Forthe %g,and %G formats, it specifies the maximum number of significant digits. Forthe %d, %o, %i, %u, %x,and %X formats, it specifies the minimum number of digits to print. Fora 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 recog- nizes certain special filenames internally.These filenames allowaccess 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) sys- tem call, $3 is the value of the getgid(2) system call, and $4 is the value of the getegid(2) sys- tem call. If there are anyadditional fields, theyare 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 touse print "You blew it!" | "cat 1>&2" These file names may also be used on the command line to name data files. Numeric Functions AWKhas 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 newseed for the random number generator.Ifno 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]) 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 num- ber 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

Free Software Foundation Apr 28 1999 113 GAWK(1) Utility Commands GAWK(1)

be used to indicate just the text that matched the n’thparenthesized 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 AWKLanguage Pro gramming for a fuller discussion of the rules for &’s and backslashes in the replacement text of sub(), gsub(),and gen- sub(). index(s, t) returns the indexofthe string t in the string s,or0if t is not present. length([s]) returns the length of the string s,orthe 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 num- ber of fields. If r is omitted, FS is used instead. The array a is cleared first. Split- ting behavesidentically 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 copyofthe 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 copyofthe 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 informa- tion, gawk provides the following twofunctions for obtaining time stamps and formatting them. systime() returns the current time of day as the number of seconds since the Epoch (Midnight UTC, Jan- uary 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 Cfor 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: \\ Aliteral backslash. \a The ‘‘alert’’character; usually the ASCII BEL character. \b backspace.

114 Apr 28 1999 Free Software Foundation GAWK(1) Utility Commands GAWK(1)

\f form-feed. \n newline. \r carriage return. \t horizontal tab. \v vertical tab. \xhexdigits The character represented by the string of hexadecimal digits following the \x.Asin ANSI C, all fol- lowing 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 theyare 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 func- tion. 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: Theyare 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, a, b) # a&bare local { ..... }

/abc/ { ... ; f(1, 2) ; ... } The left parenthesis in a function call is required to immediately followthe 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 ini- tialized 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:

{nlines++ } END { 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-Wes- ley, 1988. ISBN 0-201-07981-X. AWKLanguage Pro gramming,Edition 1.0, published by the Free Software Foundation, 1995. POSIX COMPATIBILITY Aprimary goal for gawk is compatibility with the POSIX standard, as well as with the latest version of UNIX awk.Tothis 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 com- mand line variable assignment happens when awk would otherwise open the argument as a file, which is after the BEGIN block is executed. However, inearlier implementations, when such an assignment appeared before anyfile names, the assignment would happen before the BEGIN block was run. Applica- tions came to depend on this ‘‘feature.’’ When awk waschanged to match its documentation, this option wasadded 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 ‘‘−−’’ tosignal the end of arguments. In com- patibility 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 wasusing, to allowkeeping track of random number sequences. Therefore srand() in gawk also returns its current seed. Other newfeatures 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 Cconversion specifications in printf (done first in AT&T’s version). GNU EXTENSIONS Gawk has a number of extensions to POSIX awk.Theyare 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 envi- ronment 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 invokedwith 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’’tothe −F option. Since this is a rather ugly special case, it is not the default behav- ior.This behavior also does not occur if −−posix has been specified. To really get a tab character as the field separator,itisbest to use quotes: gawk −F’\t’ .... HISTORICAL FEATURES There are twofeatures of historical AWK implementations that gawk supports. First, it is possible to call the length() built-in function not only with no argument, but evenwithout 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’’inthe 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 behavesexactly 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 giventhe 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,itsynchronizes output to the standard output with output to /dev/std- out,while on a system with those files, the output is actually to different open files. Caveat Emptor. Syntactically invalid single character programs tend to overflowthe parse stack, generating a rather unhelp- ful 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 wasdesigned 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,tobecompatible with the orig- inal 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 newversion 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 /2 was done by Kai Uwe Rommel, with contributions and help from Darrel Hankerson. Fred Fish supplied support for the Amiga. BUGREPORTS If you find a bug in gawk,please send electronic mail to [email protected], with acarbon copyto [email protected] include your operating system and its revision, the version of gawk,what C com- piler 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 twothings. First, verify that you have the latest version of gawk. Manybugs (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. Whateveryou 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 givenabove. ACKNOWLEDGEMENTS Brian Kernighan of Bell Labs provided valuable assistance during testing and debugging. Wethank him. COPYING PERMISSIONS Copyright ©) 1996,97,98,99 Free Software Foundation, Inc. Permission is granted to makeand distribute verbatim copies of this manual page provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copyand distribute modified versions of this manual page under the conditions for verbatim copying, provided that the entire resulting derivedwork is distributed under the terms of a permis- sion notice identical to this one. Permission is granted to copyand 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 approvedbythe 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 igno- rant les blancs en début de ligne, comme sort(1) le fait avecl’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 avecunseul 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.Astream 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 overthe 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 invokedwith 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 process- ing the input. If no -e,-f,--expression,or --file options are givenonthe command-line, then the first non-option argument on the command line is taken to be the script to be executed. If anycommand-line parameters remain after processing the above,these parameters are interpreted as the names of input files to be processed. Afile 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 serveasareminder to those who already knowsed; 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 anymore 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 correspond- ing 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 char- acter in dest. Addresses Sed commands can be givenwith 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 twoaddresses, 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, evenif addr2 selects an earlier line; and if addr2 is a regexp,itwill 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’thline starting with line first.For example, ‘‘sed -n 1˜2p’’will print all the odd- numbered 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 anycharacter. Regular expressions POSIX.2 BREs should be supported, but theyaren’tcompletely yet. The \n sequence in a regular expres- sion 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 \ 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, anyofvarious books on sed,the sed FA Q (http://www.wollery.demon.co.uk/sedtut10.txt, http://www.ptug.org/sed/sedfaq.htm). BUGS E-mail bug reports to [email protected] 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.

Pardé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,etterminer avecuncode 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’environ- nement. 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. −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 avecles minuscules accentuées...) −i Ignorer pour le tri les caractères en dehors de l’intervalle ASCII octal 040-0176 (bornes com- prises).

124 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 correspon- dant à 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 aveclaplus 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 égale- ment un fichier d’entrée, sort copie les données dans un fichier temporaire avant le tri pour pou- voir é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 non- blanches. Ceci signifie qu’avecl’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 con- sidérées comme égales. Pour l’action −c,vérifier qu’aucune lignes consécutivesnesoient égales. +POS1 [−POS2] Indiquer un champ à utiliser comme clé de tri pour chaque ligne. Le champ consiste en une por- tion 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 syntaxepossible pour indiquer les clés de tri. Les positions des champs et des car- actè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)oudepuis 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éfixeconstitué 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épenda- ment 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 avecunseul 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.Laversion 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) conti- ennent 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 Dec Hex Car Oct Dec Hex Car 000 0 00 NUL ’\0’ 100 64 40 @ 001 1 01 SOH 101 65 41 A 002 2 02 STX 102 66 42 B 003 3 03 ETX 103 67 43 C 004 4 04 EOT 104 68 44 D 005 5 05 ENQ 105 69 45 E 006 6 06 ACK 106 70 46 F 007 7 07 BEL ’\a’ 107 71 47 G 010 8 08 BS ’\b’ 110 72 48 H 011 9 09 HT ’\t’ 111 73 49 I 012 10 0A LF ’\n’ 112 74 4A J 013 11 0B VT ’\v’ 113 75 4B K 014 12 0C FF ’\f’ 114 76 4C L 015 13 0D CR ’\r’ 115 77 4D M 016 14 0E SO 116 78 4E N 017 15 0F SI 117 79 4F O 020 16 10 DLE 120 80 50 P 021 17 11 DC1 121 81 51 Q 022 18 12 DC2 122 82 52 R 023 19 13 DC3 123 83 53 S 024 20 14 DC4 124 84 54 T 025 21 15 NAK 125 85 55 U 026 22 16 SYN 126 86 56 V 027 23 17 ETB 127 87 57 W 030 24 18 CAN 130 88 58 X 031 25 19 EM 131 89 59 Y 032 26 1A SUB 132 90 5A Z 033 27 1B ESC 133 91 5B [ 034 28 1C FS 134 92 5C \ ’\\’ 035 29 1D GS 135 93 5D ] 036 30 1E RS 136 94 5E ˆ 037 31 1F US 137 95 5F _ 040 32 20 SPACE 140 96 60 ‘ 041 33 21 ! 141 97 61 a 042 34 22 " 142 98 62 b 043 35 23 # 143 99 63 c 044 36 24 $ 144 100 64 d 045 37 25 % 145 101 65 e 046 38 26 & 146 102 66 f 047 39 27 ’ 147 103 67 g

Linux 25 Janvier 1997 127 ASCII(7) Manuel de l’administrateur Linux ASCII(7)

050 40 28 ( 150 104 68 h 051 41 29 ) 151 105 69 i 052 42 2A ∗ 152 106 6A j 053 43 2B + 153 107 6B k 054 44 2C , 154 108 6C l 055 45 2D − 155 109 6D m 056 46 2E . 156 110 6E n 057 47 2F / 157 111 6F o 060 48 30 0 160 112 70 p 061 49 31 1 161 113 71 q 062 50 32 2 162 114 72 r 063 51 33 3 163 115 73 s 064 52 34 4 164 116 74 t 065 53 35 5 165 117 75 u 066 54 36 6 166 118 76 v 067 55 37 7 167 119 77 w 070 56 38 8 170 120 78 x 071 57 39 9 171 121 79 y 072 58 3A : 172 122 7A z 073 59 3B ; 173 123 7B { 074 60 3C < 174 124 7C | 075 61 3D = 175 125 7D } 076 62 3E > 176 126 7E ˜ 077 63 3F ? 177 127 7F 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 ver- ticale 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’sManual 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 No. 1", which has become widely implemented and may already be seen as the de-facto standard ASCII replacement. However, itlacks the EUROsymbol and does not fully coverFinnish 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 The full set of ISO 8859 alphabets includes: ISO 8859-1 West European languages (Latin-1) ISO 8859-2 Central and East European languages (Latin-2) ISO 8859-3 Southeast European and miscellaneous languages (Latin-3) ISO 8859-4 Scandinavian/Baltic languages (Latin-4) ISO 8859-5 Latin/Cyrillic ISO 8859-6 Latin/Arabic ISO 8859-7 Latin/Greek ISO 8859-8 Latin/Hebrew ISO 8859-9 Latin-1 modification for Turkish (Latin-5) ISO 8859-10 Lappish/Nordic/Eskimo languages (Latin-6) ISO 8859-11 Latin/Thai ISO 8859-13 Baltic Rim languages (Latin-7) ISO 8859-14 Celtic (Latin-8) ISO 8859-15 West European languages (Latin-9) ISO 8859-16 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 showthe proper glyphs in an environment configured for ISO 8859-15. Oct Dec HexChar Description 240 160 A0 NO-BREAK SPACE 241 161 A1 ¡ INVERTED 242 162 A2 ¢ CENT SIGN 243 163 A3 £ POUND SIGN 244 164 A4 ¤ EUROSIGN 245 165 A5 ¥ YEN SIGN 246 166 A6 ¦ LATIN CAPITAL LETTER S WITH CARON 247 167 A7 § 250 168 A8 ¨ LATIN SMALL LETTER S WITH CARON 251 169 A9 © COPYRIGHT SIGN 252 170 AA ª FEMININE ORDINAL INDICATOR 253 171 AB « LEFT-POINTING DOUBLE ANGLE 254 172 AC ¬ NOTSIGN 255 173 AD 256 174 AE ® REGISTERED SIGN 257 175 AF ¯ MACRON 260 176 B0 ° DEGREE SIGN 261 177 B1 ± PLUS-MINUS SIGN

Linux 1999-05-31 129 ISO_8859-15(7) Linux Programmer’sManual ISO_8859-15(7)

262 178 B2 ² SUPERSCRIPT TWO 263 179 B3 ³ SUPERSCRIPT THREE 264 180 B4 ´ LATIN CAPITAL LETTER Z WITH CARON 265 181 B5 µ MICROSIGN 266 182 B6 ¶ PILCROW SIGN 267 183 B7 · MIDDLE DOT 270 184 B8 ¸ LATIN SMALL LETTER Z WITH CARON 271 185 B9 ¹ SUPERSCRIPT ONE 272 186 BA º MASCULINE ORDINAL INDICATOR 273 187 BB » RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 274 188 BC ¼ LATIN CAPITAL OE 275 189 BD ½ LATIN SMALL LIGATURE OE 276 190 BE ¾ LATIN CAPITAL LETTER Y WITH DIAERESIS 277 191 BF ¿ INVERTED 300 192 C0 À LATIN CAPITAL LETTER A WITH GRAVE 301 193 C1 Á LATIN CAPITAL LETTER A WITH ACUTE 302 194 C2 Â LATIN CAPITAL LETTER A WITH CIRCUMFLEX 303 195 C3 Ã LATIN CAPITAL LETTER A WITH TILDE 304 196 C4 Ä LATIN CAPITAL LETTER A WITH DIAERESIS 305 197 C5 Å LATIN CAPITAL LETTER A WITH RING ABOVE 306 198 C6 Æ LATIN CAPITAL LETTER AE 307 199 C7 Ç LATIN CAPITAL LETTER C WITH CEDILLA 310 200 C8 È LATIN CAPITAL LETTER E WITH GRAVE 311 201 C9 É LATIN CAPITAL LETTER E WITH ACUTE 312 202 CA Ê LATIN CAPITAL LETTER E WITH CIRCUMFLEX 313 203 CB Ë LATIN CAPITAL LETTER E WITH DIAERESIS 314 204 CC Ì LATIN CAPITAL LETTER I WITH GRAVE 315 205 CD Í LATIN CAPITAL LETTER I WITH ACUTE 316 206 CE Î LATIN CAPITAL LETTER I WITH CIRCUMFLEX 317 207 CF Ï LATIN CAPITAL LETTER I WITH DIAERESIS 320 208 D0 Ð LATIN CAPITAL LETTER ETH 321 209 D1 Ñ LATIN CAPITAL LETTER N WITH TILDE 322 210 D2 Ò LATIN CAPITAL LETTER O WITH GRAVE 323 211 D3 Ó LATIN CAPITAL LETTER O WITH ACUTE 324 212 D4 Ô LATIN CAPITAL LETTER O WITH CIRCUMFLEX 325 213 D5 Õ LATIN CAPITAL LETTER O WITH TILDE 326 214 D6 Ö LATIN CAPITAL LETTER O WITH DIAERESIS 327 215 D7 × MULTIPLICATION SIGN 330 216 D8 Ø LATIN CAPITAL LETTER O WITH STROKE 331 217 D9 Ù LATIN CAPITAL LETTER U WITH GRAVE 332 218 DA Ú LATIN CAPITAL LETTER U WITH ACUTE 333 219 DB Û LATIN CAPITAL LETTER U WITH CIRCUMFLEX 334 220 DC Ü LATIN CAPITAL LETTER U WITH DIAERESIS 335 221 DD Ý LATIN CAPITAL LETTER Y WITH ACUTE 336 222 DE Þ LATIN CAPITAL LETTER 337 223 DF ß LATIN SMALL LETTER SHARP S 340 224 E0 à LATIN SMALL LETTER A WITH GRAVE 341 225 E1 á LATIN SMALL LETTER A WITH ACUTE 342 226 E2 â LATIN SMALL LETTER A WITH CIRCUMFLEX 343 227 E3 ã LATIN SMALL LETTER A WITH TILDE 344 228 E4 ä LATIN SMALL LETTER A WITH DIAERESIS 345 229 E5 å LATIN SMALL LETTER A WITH RING ABOVE 346 230 E6 æ LATIN SMALL LETTER AE

130 1999-05-31 Linux ISO_8859-15(7) Linux Programmer’sManual ISO_8859-15(7)

347 231 E7 ç LATIN SMALL LETTER C WITH CEDILLA 350 232 E8 è LATIN SMALL LETTER E WITH GRAVE 351 233 E9 é LATIN SMALL LETTER E WITH ACUTE 352 234 EA ê LATIN SMALL LETTER E WITH CIRCUMFLEX 353 235 EB ë LATIN SMALL LETTER E WITH DIAERESIS 354 236 EC ì LATIN SMALL LETTER I WITH GRAVE 355 237 ED í LATIN SMALL LETTER I WITH ACUTE 356 238 EE î LATIN SMALL LETTER I WITH CIRCUMFLEX 357 239 EF ï LATIN SMALL LETTER I WITH DIAERESIS 360 240 F0 ð LATIN SMALL LETTER ETH 361 241 F1 ñ LATIN SMALL LETTER N WITH TILDE 362 242 F2 ò LATIN SMALL LETTER O WITH GRAVE 363 243 F3 ó LATIN SMALL LETTER O WITH ACUTE 364 244 F4 ô LATIN SMALL LETTER O WITH CIRCUMFLEX 365 245 F5 õ LATIN SMALL LETTER O WITH TILDE 366 246 F6 ö LATIN SMALL LETTER O WITH DIAERESIS 367 247 F7 ÷ DIVISION SIGN 370 248 F8 ø LATIN SMALL LETTER O WITH STROKE 371 249 F9 ù LATIN SMALL LETTER U WITH GRAVE 372 250 FA ú LATIN SMALL LETTER U WITH ACUTE 373 251 FB û LATIN SMALL LETTER U WITH CIRCUMFLEX 374 252 FC ü LATIN SMALL LETTER U WITH DIAERESIS 375 253 FD ý LATIN SMALL LETTER Y WITH ACUTE 376 254 FE þ LATIN SMALL LETTER THORN 377 255 FF ÿ 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’sManual 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 anyother 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 scripts, but also Chinese, Japanese and Korean Han ideographs as well as scripts such as , , , , Bengali, , Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam, Thai, Lao, Khmer,, Tibetan, Runic, Ethiopic, Canadian Syllabics, Cherokee, Mongolian, , Myanmar,Sinhala, , Yi, and others. For scripts not yet covered, research on howtobest encode them for computer usage is still going on and theywill be added eventually.This might eventually include not only Hieroglyphs and various historic Indo-European languages, but evensome selected artistic scripts such as ,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 manyword 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 (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 tothe standard, therefore of the entire code space, only a small fraction of group 0 will everbeactually 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 coveronly more exotic characters for special scientific, dictionary printing, publishing industry,higher-levelprotocol 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 twoencoding 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 byUCS-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 0x00ffare 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 non- spacing accent keysonatypewriter.Acombining character just adds an accent to the previous character. The most important accented characters have codes of their own in UCS, however, the mechanism allows us to add accents and other diacritical marks to anycharacter.The combining characters always followthe character which theymodify.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 or for mathematical typesetting and users of the International Phonetic Alphabet. Implementation Levels As not all systems are expected to support advanced mechanisms likecombining characters, ISO 10646-1 specifies the following three implementation levels of UCS: Level1 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

132 2001-05-11 GNU UNICODE(7) Linux Programmer’sManual UNICODE(7)

supported. Level2 In addition to level1,combining characters are nowallowed for some languages where theyare essential (e.g., Thai, Lao, Hebrew, Arabic, Devanagari, Malayalam, etc.). Level3 All UCS characters are supported. The Unicode 3.0 Standard published by the contains exactly the UCS Basic Multilingual Plane at implementation level3,asdescribed 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. Theyprovide 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 likeASCII 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, howmanypositions (0–2) the cursor is advanced by the output of a character. Under Linux, in general only the BMP at implementation level1should 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 (level2), 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 0xf8ffwill neverbeassigned to anycharacters by the standard and is reserved for private usage. Forthe Linux community,this private area has been subdivided further into the range 0xe000 to 0xefff which can be used individually by anyend-user and the Linux zone in the range 0xf000 to 0xf8ffwhere extensions are coordinated among all Linux users. The registry of the characters assigned to the Linux zone is currently maintained by H. Peter Anvin . 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.

Agood 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 newClibrary functions for handling wide and multi-byte character encodings, but it does not yet coverISO C99, which improved wide and multi-byte character support evenfurther. ∗ Unicode Technical Reports. http://www.unicode.org/unicode/reports/

GNU 2001-05-11 133 UNICODE(7) Linux Programmer’sManual 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 evensimple overstriking combining characters, butusually 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’sManual 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 many16-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’tread 16-bit words as characters without major modifications. Forthese 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),asuperset of Unicode, occupies evena31-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 0xffare neverused 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 howlong this multi-byte sequence is. All further bytes in a multi- byte 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, howeverthe Unicode standard specifies no characters above 0x10ffff,soUnicode 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’sManual UTF-8(7)

used. The UCS code values 0xd800–0xdfff (UTF-16 surrogates) as well as 0xfffeand 0xffff (UCS non- characters) 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 toselect 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 tobeaware that twoassumptions made so far are no longer valid in UTF-8 locales. Firstly,asingle byte does not necessarily correspond anymore 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 manynon-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’sManual 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() INTRODUCTION()

138 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−javacompiler − 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 ...... 33 lint − C program checker − vérificateur de sources C ...... 34 ln − link − lier ...... 22 locate − locate − localiser ...... 25 login − login − connexion ...... 5 lp − offline printer − impression en différé ...... 16 ls − list − lister ...... 41 lsof − list open files − liste des fichiers ouverts ...... 55 mail − mail − courrier ...... 51 make−make−fabriquer ...... 34 man − manuel − manuel ...... 49 mesg − message − message ...... 51 mkdir − makedirectory − création de répertoire ...... 11 more − more and more − de plus en plus ...... 17 mv − move − déplacer ...... 23 nano - Nano’sANOther editor - NAno un NOuvel éditeur ...... 61 netbeans − Java IDE − EDI Java ...... 35 netstat − net statistics − statistiques réseau ...... 55 nice − nice − mignon ...... 39 nmap − network map − carte réseau ...... 35 nm − name − nom ...... 35 nohup − no hangup − ne pas raccrocher ...... 39 od − octal dump − impression en octal ...... 36 passwd − password − mot de passe ...... 6 paste − paste − coller ...... 18 patch − patch − rustine ...... 36 pc − pascal compiler − compilateur pascal ...... 28 perfmeter − performance meter − mesure de performance ...... 56 perl − practical extraction and report language − perle ...... 28 php − php − php ...... 28 prof − profile − profil ...... 36 pr − print − imprimer ...... 18 ps − process status − statut des processus ...... 42 pwd − print working directory − imprime le répertoire de travail ...... 45 python − python − python ...... 29 ranlib − makearandom library − fabriquer une bibliothèque ...... 36 recode − recode text file − recoder des fichiers texte ...... 18 rmdir − remove directory − destruction de répertoire ...... 11 rm − remove − enlever...... 23 rsync − remote file synchronisation − synchronisation de fichiers à distance ...... 7 rup − remote time up − temps de marche distant ...... 56 rusers − remote users − utilisateurs distants ...... 45 scp − secure copy−copie sûre ...... 10 script − script − script ...... 39 sftp − secure file transfer program − programme de transfert sécurisé de fichier ...... 53 size − size − taille ...... 37 sleep − sleep − dormir ...... 39 sox − sound exchange − conversion de fichiers son ...... 19 split − split − découper un fichier ...... 19 sshfs − ssh file system − système de fichiers sur ssh ...... 10 ssh − OpenSSH secure shell client − shell de sécurité à distance ...... 8 strace − system call trace − trace des appels systèmes ...... 37 strip − strip − enlever...... 37 stty − set terminal type − positionner des options de terminal ...... 5

140 Petit manuel Unix 2001 INDEX

tail − tail − queue ...... 19 talk − talk − parler ...... 51 tar − tape archive − archive sur bande ...... 19 tee − tee − té ...... 20 test − test − tester ...... 49 time − time − temps ...... 37 top − top − dessus ...... 56 touch − touch − touche ...... 23 tr − translate − remplace ...... 20 tty − terminal − terminal ...... 45 uname − name of current system − nom du système ...... 56 uniq − unique − unique ...... 21 uptime − time up − temps de marche ...... 57 users − users − utilisateurs ...... 45 vi - visual editor - éditeur visuel ...... 63 vmstat − virtual memory statistics − statistique de la mémoire virtuelle ...... 57 wc − word count − compte de mots ...... 21 web-browsers − −navigateurs web ...... 53 whereis − where is − où est-ce ...... 26 which − which − lequel ...... 26 who − who − qui ...... 46 write − write − écrire ...... 52 w−who and what − qui et quoi ...... 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 avecl’ASCII

Petit manuel Unix 2001 141