Dernière mise-à-jour : 2020/01/30 03:27
Les options sous Linux peuvent être exprimées au format court ou au format long. Plusieurs différences sont importantes à noter.
Premièrement les options courtes sont précédées par un simple tiré -, tandis que les options longues sont précédées par deux tirés –.
Un exemple est l'option de l'aide pour la plupart des commandes bash :
Deuxièmement les options courtes peuvent être combinées tandis que les options longues ne peuvent pas l'être. Par exemple, la ligne de commande ls -l -a -i peut être aussi écrite ls -lai, ls -lia ou encore ls -ali :
[root@centos7 ~]# ls -lai /tmp total 244 11071 drwxrwxrwt. 10 root root 260 Sep 30 06:24 . 128 dr-xr-xr-x. 18 root root 4096 Dec 10 2015 .. 13635 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .font-unix 24858 drwxr-xr-x. 2 root root 100 Sep 30 06:05 hsperfdata_root 13597 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .ICE-unix 287056 drwxr-xr-x. 2 root root 100 Sep 28 12:30 inode 24861 srw-------. 1 root root 0 Sep 28 10:52 .java_pid3213 25344 srw-------. 1 root root 0 Sep 28 10:52 .java_pid3302 16615 drwx------. 3 root root 60 Sep 28 10:49 systemd-private-45071248a58f4fd2a4de940a5734c8ec-cups.service-ODc5L6 13595 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .Test-unix 13590 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .X11-unix 13629 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .XIM-unix 8098838 -rw-------. 1 root root 242724 Sep 30 05:45 yum_save_tx.2016-09-30.05-45.FF7KO4.yumtx [root@centos7 ~]# ls -ali /tmp total 244 11071 drwxrwxrwt. 10 root root 260 Sep 30 06:24 . 128 dr-xr-xr-x. 18 root root 4096 Dec 10 2015 .. 13635 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .font-unix 24858 drwxr-xr-x. 2 root root 100 Sep 30 06:05 hsperfdata_root 13597 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .ICE-unix 287056 drwxr-xr-x. 2 root root 100 Sep 28 12:30 inode 24861 srw-------. 1 root root 0 Sep 28 10:52 .java_pid3213 25344 srw-------. 1 root root 0 Sep 28 10:52 .java_pid3302 16615 drwx------. 3 root root 60 Sep 28 10:49 systemd-private-45071248a58f4fd2a4de940a5734c8ec-cups.service-ODc5L6 13595 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .Test-unix 13590 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .X11-unix 13629 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .XIM-unix 8098838 -rw-------. 1 root root 242724 Sep 30 05:45 yum_save_tx.2016-09-30.05-45.FF7KO4.yumtx
La commande ls -l –all –inode ne peut pas être écrite ls -l –allinode :
[root@centos7 ~]# ls -l --all --inode /tmp total 244 11071 drwxrwxrwt. 10 root root 260 Sep 30 06:24 . 128 dr-xr-xr-x. 18 root root 4096 Dec 10 2015 .. 13635 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .font-unix 24858 drwxr-xr-x. 2 root root 100 Sep 30 06:05 hsperfdata_root 13597 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .ICE-unix 287056 drwxr-xr-x. 2 root root 100 Sep 28 12:30 inode 24861 srw-------. 1 root root 0 Sep 28 10:52 .java_pid3213 25344 srw-------. 1 root root 0 Sep 28 10:52 .java_pid3302 16615 drwx------. 3 root root 60 Sep 28 10:49 systemd-private-45071248a58f4fd2a4de940a5734c8ec-cups.service-ODc5L6 13595 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .Test-unix 13590 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .X11-unix 13629 drwxrwxrwt. 2 root root 40 Sep 28 10:48 .XIM-unix 8098838 -rw-------. 1 root root 242724 Sep 30 05:45 yum_save_tx.2016-09-30.05-45.FF7KO4.yumtx [root@centos7 ~]# ls -l --allinode /tmp ls: unrecognized option '--allinode' Try 'ls --help' for more information
Important : Les options prenant un argument ne sont pas combinées avec les autres options.
Cette commande affiche le répertoire courant de travail :
[trainee@centos7 ~]$ pwd /home/trainee
A faire : Utilisez la commande help avec l'option pwd pour visualiser les options de la commande.
Cette commande permet de changer de répertoire courant pour le répertoire passé en argument à la commande :
[trainee@centos7 ~]$ cd /tmp [trainee@centos7 tmp]$ pwd /tmp [trainee@centos7 tmp]$
A faire : Utilisez la commande help avec l'option cd pour visualiser les options de la commande.
Cette commande permet de lister le contenu d'un répertoire passé en argument à la commande. Si aucun argument n'est spécifié, la commande liste le contenu du répertoire courant :
[trainee@centos7 tmp]$ ls hsperfdata_root inode systemd-private-45071248a58f4fd2a4de940a5734c8ec-cups.service-ODc5L6
A faire : Utilisez l'option –help de la commande ls pour visualiser les options de la commande.
La commande lsof affiche des informations sur les fichiers ouverts par des processus :
[trainee@centos7 tmp]$ su - Password: fenestros Last login: Thu Sep 29 06:24:28 CEST 2016 on pts/0 [root@centos7 ~]# lsof | more COMMAND PID TID USER FD TYPE DEVICE SIZE/OFF NODE NAME systemd 1 root cwd DIR 8,2 4096 128 / systemd 1 root rtd DIR 8,2 4096 128 / systemd 1 root txt REG 8,2 1494056 33607555 /usr/lib/systemd/systemd systemd 1 root mem REG 8,2 20032 17241167 /usr/lib64/libuuid.so.1.3.0 systemd 1 root mem REG 8,2 252696 20114965 /usr/lib64/libblkid.so.1.1.0 systemd 1 root mem REG 8,2 90632 18751025 /usr/lib64/libz.so.1.2.7 systemd 1 root mem REG 8,2 19888 17326380 /usr/lib64/libattr.so.1.1.0 systemd 1 root mem REG 8,2 19520 17239651 /usr/lib64/libdl-2.17.so systemd 1 root mem REG 8,2 153192 18023397 /usr/lib64/liblzma.so.5.0.99 systemd 1 root mem REG 8,2 398272 18105157 /usr/lib64/libpcre.so.1.2.0 systemd 1 root mem REG 8,2 2107816 17239525 /usr/lib64/libc-2.17.so systemd 1 root mem REG 8,2 142304 17240882 /usr/lib64/libpthread-2.17.so systemd 1 root mem REG 8,2 88720 17511831 /usr/lib64/libgcc_s-4.8.5-20150702.so.1 systemd 1 root mem REG 8,2 44096 17241011 /usr/lib64/librt-2.17.so systemd 1 root mem REG 8,2 260784 20114966 /usr/lib64/libmount.so.1.1.0 systemd 1 root mem REG 8,2 91768 18023376 /usr/lib64/libkmod.so.2.2.10 systemd 1 root mem REG 8,2 118792 17326381 /usr/lib64/libaudit.so.1.0.0 systemd 1 root mem REG 8,2 61648 18105139 /usr/lib64/libpam.so.0.83.1 systemd 1 root mem REG 8,2 20024 17326423 /usr/lib64/libcap.so.2.22 systemd 1 root mem REG 8,2 147120 18447456 /usr/lib64/libselinux.so.1 systemd 1 root mem REG 8,2 164440 21744303 /usr/lib64/ld-2.17.so systemd 1 root mem REG 8,2 1333123 50334524 /etc/selinux/targeted/contexts/files/file_contexts.bin --More--
A faire : Utilisez l'option –help de la commande lsof pour visualiser les options de la commande.
Cette commande sert à modifier l'horodatage de la date de dernière modification du contenu (mtime) et la date du dernier accès (atime), d'un ou de plusieurs fichiers passé(s) en argument(s), selon la date courante. Si le(s) fichier(s) n'existe(nt) pas, il(s) est (sont) créé(s) :
[root@centos7 ~]# exit logout [trainee@centos7 tmp]$ touch test [trainee@centos7 tmp]$ ls hsperfdata_root systemd-private-45071248a58f4fd2a4de940a5734c8ec-cups.service-ODc5L6 inode test
A faire : Utilisez l'option –help de la commande touch pour visualiser les options de la commande.
Cette commande écrit les arguments vers la sortie standard (autrement dit à l'écran) :
[trainee@centos7 tmp]$ echo fenestros fenestros
A faire : Utilisez la commande help avec l'option echo pour visualiser les options de la commande.
La commande cp permet de copier une source vers une destination ou de multiples sources vers un répertoire :
[trainee@centos7 tmp]$ cp test ~ [trainee@centos7 tmp]$ ls -l ~ total 4 drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Desktop drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Documents drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Downloads drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Music drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Pictures drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Public drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Templates -rw-rw-r--. 1 trainee trainee 0 Sep 29 17:23 test drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Videos -rw-rw-r--. 1 trainee trainee 442 Sep 29 00:53 vitext
Important : Notez l'utilisation du caractère ~ (tilde) qui est un caractère spécial indiquant le répertoire personnel de l'utilisateur courant, dans ce cas /home/trainee.
A faire : Utilisez l'option –help de la commande cp pour visualiser les options de la commande.
Cette commande permet de connaître le type d'un fichier:
[trainee@centos7 tmp]$ file ~/test /home/trainee/test: empty
Important : Notez que la commande vous indique le type de fichier en fonction de son contenu. Dans l'exemple précédent, puisque le fichier est vide, la commande file ne peut pas indiqué le type de fichier.
Redirigez, en utilisant le caractère >, la sortie de la commande echo vers le fichier /home/trainee/test de façon à ce que ce dernier contient le texte fenestros :
[trainee@centos7 tmp]$ echo "fenestros" > ~/test
En utilisant de nouveau la commande file, celle-ci est capable de vous indiquer le type de fichier :
[trainee@centos7 tmp]$ file ~/test /home/trainee/test: ASCII text
A faire : Utilisez l'option –help de la commande file pour visualiser les options de la commande.
La commande cat permet de concaténer les fichiers passés en argument, ou de l'entrée standard ( le clavier ), vers la sortie standard ( l'écran ). Dans le cas où il n'y a qu'un seul fichier passé en argument, le contenu de celui-ci est affiché à l'écran :
[trainee@centos7 tmp]$ cat ~/test fenestros
A faire : Utilisez l'option –help de la commande cat pour visualiser les options de la commande.
La commande mv permet déplacer ou de renommer un fichier ou répertoire.
Utilisez la commande mv pour déplacer le fichier test de votre répertoire personnel vers le répertoire courant :
[trainee@centos7 tmp]$ mv ~/test . [trainee@centos7 tmp]$ ls -l ~ total 4 drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Desktop drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Documents drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Downloads drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Music drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Pictures drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Public drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Templates drwxr-xr-x. 2 trainee trainee 6 Apr 30 11:54 Videos -rw-rw-r--. 1 trainee trainee 442 Sep 29 00:53 vitext [trainee@centos7 tmp]$ mv test TeSt [trainee@centos7 tmp]$ ls -l total 4 drwxr-xr-x. 2 root root 80 Sep 28 10:52 hsperfdata_root drwxr-xr-x. 2 root root 100 Sep 28 12:30 inode drwx------. 3 root root 60 Sep 28 10:49 systemd-private-45071248a58f4fd2a4de940a5734c8ec-cups.service-ODc5L6 -rw-rw-r--. 1 trainee trainee 10 Sep 29 17:28 TeSt
Important : Notez l'utilisation du raccourci . pour indiquer le répertoire courant.
A faire : Utilisez l'option –help de la commande mv pour visualiser les options de la commande.
La commande mkdir permet de créer un répertoire.
[trainee@centos7 tmp]$ cd ~ [trainee@centos7 ~]$ mkdir testdir [trainee@centos7 ~]$ ls Desktop Documents Downloads Music Pictures Public Templates testdir Videos vitext
A faire : Utilisez l'option –help de la commande mkdir pour visualiser les options de la commande.
La commande rmdir permet de supprimer un répertoire vide :
[trainee@centos7 ~]$ rmdir testdir [trainee@centos7 ~]$ ls Desktop Documents Downloads Music Pictures Public Templates Videos vitext
A faire : Utilisez l'option –help de la commande rmdir pour visualiser les options de la commande.
La commande rm permet de supprimer un répertoire vide ou non ou un fichier :
[trainee@centos7 ~]$ mkdir testdir1 [trainee@centos7 ~]$ cd /tmp [trainee@centos7 tmp]$ echo "fenestros" > TeSt [trainee@centos7 tmp]$ cd ~ [trainee@centos7 ~]$ mv /tmp/TeSt ~/testdir1 [trainee@centos7 ~]$ ls -lR testdir1/ testdir1/: total 4 -rw-rw-r--. 1 trainee trainee 10 Sep 29 18:13 TeSt [trainee@centos7 ~]$ rmdir testdir1/ rmdir: failed to remove ‘testdir1/’: Directory not empty [trainee@centos7 ~]$ rm -rf testdir1/ [trainee@centos7 ~]$ ls Desktop Documents Downloads Music Pictures Public Templates Videos vitext
A faire : Utilisez l'option –help de la commande rm pour visualiser les options de la commande.
Cette commande sert à rechercher un ou des fichiers dans le répertoire courant ou le répertoire spécifié en argument :
[trainee@centos7 ~]$ find acc find: ‘acc’: No such file or directory [trainee@centos7 ~]$ find aac aac
Important : Notez que si le fichier n'existe pas le système vous en informe clairement. Notez aussi que ce fichier existe le système vous en informe en vous indiquant son nom.
A faire : Utilisez l'option –help de la commande find pour visualiser les options de la commande.
La commande locate sert à rechercher un ou des fichiers dans l'ensemble du système de fichiers en commençant à la racine (/) en spécifiant une chaîne à rechercher en argumant à la commande. La commande locate utilise une base de données afin d'effectuer sa recherche. Pour construire ou mettre à jour cette base de données avant l'utilisation de la commande pour une recherche, il faut utiliser la commande updatedb en tant que root.
La base de données par défaut est /var/lib/mlocate/mlocate.db :
[root@centos7 ~]# ls -l /var/lib/mlocate/mlocate.db -rw-r-----. 1 root slocate 3887117 Sep 29 03:46 /var/lib/mlocate/mlocate.db
Important : Pour plus d'information concernant le format de la base de données, consultez man 5 locatedb.
La commande updatedb peut être configurée en éditant son fichier de configuration /etc/updatedb.conf :
[root@centos7 ~]# cat /etc/updatedb.conf PRUNE_BIND_MOUNTS = "yes" PRUNEFS = "9p afs anon_inodefs auto autofs bdev binfmt_misc cgroup cifs coda configfs cpuset debugfs devpts ecryptfs exofs fuse fuse.sshfs fusectl gfs gfs2 hugetlbfs inotifyfs iso9660 jffs2 lustre mqueue ncpfs nfs nfs4 nfsd pipefs proc ramfs rootfs rpc_pipefs securityfs selinuxfs sfs sockfs sysfs tmpfs ubifs udf usbfs" PRUNENAMES = ".git .hg .svn" PRUNEPATHS = "/afs /media /mnt /net /sfs /tmp /udev /var/cache/ccache /var/lib/yum/yumdb /var/spool/cups /var/spool/squid /var/tmp"
L'utilisation des deux commandes est illustrée ci-après :
[root@centos7 ~]# updatedb [root@centos7 ~]# locate aac /home/trainee/aac /usr/lib/modules/3.10.0-327.13.1.el7.x86_64/kernel/drivers/scsi/aacraid /usr/lib/modules/3.10.0-327.13.1.el7.x86_64/kernel/drivers/scsi/aacraid/aacraid.ko /usr/lib/modules/3.10.0-327.el7.x86_64/kernel/drivers/scsi/aacraid /usr/lib/modules/3.10.0-327.el7.x86_64/kernel/drivers/scsi/aacraid/aacraid.ko /usr/lib/python2.7/site-packages/ipalib/plugins/caacl.py /usr/lib/python2.7/site-packages/ipalib/plugins/caacl.pyc /usr/lib/python2.7/site-packages/ipalib/plugins/caacl.pyo /usr/share/gtk-doc/html/gst-plugins-good-plugins-1.0/gst-plugins-good-plugins-aacparse.html /usr/share/gupnp-dlna-2.0/dlna-profiles/aac.xml /usr/share/mime/audio/aac.xml /usr/src/kernels/3.10.0-327.13.1.el7.x86_64/drivers/scsi/aacraid /usr/src/kernels/3.10.0-327.13.1.el7.x86_64/drivers/scsi/aacraid/Makefile /usr/src/kernels/3.10.0-327.13.1.el7.x86_64/include/config/scsi/aacraid.h /usr/src/kernels/3.10.0-327.el7.x86_64/drivers/scsi/aacraid /usr/src/kernels/3.10.0-327.el7.x86_64/drivers/scsi/aacraid/Makefile /usr/src/kernels/3.10.0-327.el7.x86_64/include/config/scsi/aacraid.h
A faire : Utilisez l'option –help des commandes updatedb et locate pour visualiser les options des commandes.
La commande whereis permet une recherche de l'emplacement des exécutables, des fichiers de configuration et des manuels pour la commande passée en argument :
[root@centos7 ~]# whereis passwd passwd: /usr/bin/passwd /etc/passwd /usr/share/man/man1/passwd.1.gz /usr/share/man/man5/passwd.5.gz
A faire : Utilisez l'option –help de la commande whereis pour visualiser les options de la commande.
La commande which permet une recherche de l'emplacement d'un exécutable dans le PATH de l'utilisateur courant et retourne le premier qui est trouvé :
[root@centos7 ~]# which passwd /bin/passwd
A faire : Utilisez l'option –help de la commande which pour visualiser les options de la commande.
La commande du peut être utilisée pour afficher la taille des fichiers contenus dans les répertoires passés en arguments. L'utilisation suivante de la commande avec les options -s et -h sur la racine du système affiche la somme des sous-répertoires avec un affichage humanisé en Ko, Mo et Go :
[root@centos7 ~]# du -sh /* 2>/dev/null 0 /bin 187M /boot 0 /dev 33M /etc 20M /home 0 /lib 0 /lib64 0 /lost+found 0 /media 0 /mnt 173M /opt 0 /proc 43M /root 8.7M /run 0 /sbin 0 /srv 0 /sys 64K /tmp 3.6G /usr 228M /var
Important : Notez l'utilisation de la redirection 2>/dev/null. Cette chaîne envoie les erreurs éventuelles, contenues dans le canal 2 appelé le canal des erreurs, à /dev/null de façon à ce que les erreurs n'apparaissent pas à l'écran. Le canal des erreurs sera couvert dans le cours La Ligne de Commande.
A faire : Utilisez l'option –help de la commande du pour visualiser les options de la commande.
Afin de poursuivre, il convient de créer une arborescence à sauvegarder :
[root@centos7 ~]# mkdir -p /test/repY; mkdir /test/repZ [root@centos7 ~]# cd /test/repY; touch Y1 Y2 Y3 [root@centos7 repY]# cd /test/repZ; touch Z1 Z2 [root@centos7 repZ]# ls -lR /test /test: total 0 drwxr-xr-x. 2 root root 33 Oct 27 11:24 repY drwxr-xr-x. 2 root root 24 Oct 27 11:25 repZ /test/repY: total 0 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y1 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y2 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y3 /test/repZ: total 0 -rw-r--r--. 1 root root 0 Oct 27 11:25 Z1 -rw-r--r--. 1 root root 0 Oct 27 11:25 Z2
Le programme tar a été originellement prévu pour sauvegarder sur des bandes magnétiques, d'où son nom issu de tape archiver.
La commande tar peut sauvegarder vers :
Les options de la commande tar sont :
[root@centos7 repZ]# tar --help Usage: tar [OPTION...] [FILE]... GNU `tar' saves many files together into a single tape or disk archive, and can restore individual files from the archive. Examples: tar -cf archive.tar foo bar # Create archive.tar from files foo and bar. tar -tvf archive.tar # List all files in archive.tar verbosely. tar -xf archive.tar # Extract all files from archive.tar. Main operation mode: -A, --catenate, --concatenate append tar files to an archive -c, --create create a new archive -d, --diff, --compare find differences between archive and file system --delete delete from the archive (not on mag tapes!) -r, --append append files to the end of an archive -t, --list list the contents of an archive --test-label test the archive volume label and exit -u, --update only append files newer than copy in archive -x, --extract, --get extract files from an archive Operation modifiers: --check-device check device numbers when creating incremental archives (default) -g, --listed-incremental=FILE handle new GNU-format incremental backup -G, --incremental handle old GNU-format incremental backup --ignore-failed-read do not exit with nonzero on unreadable files --level=NUMBER dump level for created listed-incremental archive -n, --seek archive is seekable --no-check-device do not check device numbers when creating incremental archives --no-seek archive is not seekable --occurrence[=NUMBER] process only the NUMBERth occurrence of each file in the archive; this option is valid only in conjunction with one of the subcommands --delete, --diff, --extract or --list and when a list of files is given either on the command line or via the -T option; NUMBER defaults to 1 --sparse-version=MAJOR[.MINOR] set version of the sparse format to use (implies --sparse) -S, --sparse handle sparse files efficiently Overwrite control: -k, --keep-old-files don't replace existing files when extracting, treat them as errors --keep-newer-files don't replace existing files that are newer than their archive copies --no-overwrite-dir preserve metadata of existing directories --overwrite overwrite existing files when extracting --overwrite-dir overwrite metadata of existing directories when extracting (default) --recursive-unlink empty hierarchies prior to extracting directory --remove-files remove files after adding them to the archive --skip-old-files don't replace existing files when extracting, silently skip over them -U, --unlink-first remove each file prior to extracting over it -W, --verify attempt to verify the archive after writing it Select output stream: --ignore-command-error ignore exit codes of children --no-ignore-command-error treat non-zero exit codes of children as error -O, --to-stdout extract files to standard output --to-command=COMMAND pipe extracted files to another program Handling of file attributes: --atime-preserve[=METHOD] preserve access times on dumped files, either by restoring the times after reading (METHOD='replace'; default) or by not setting the times in the first place (METHOD='system') --delay-directory-restore delay setting modification times and permissions of extracted directories until the end of extraction --group=NAME force NAME as group for added files --mode=CHANGES force (symbolic) mode CHANGES for added files --mtime=DATE-OR-FILE set mtime for added files from DATE-OR-FILE -m, --touch don't extract file modified time --no-delay-directory-restore cancel the effect of --delay-directory-restore option --no-same-owner extract files as yourself (default for ordinary users) --no-same-permissions apply the user's umask when extracting permissions from the archive (default for ordinary users) --numeric-owner always use numbers for user/group names --owner=NAME force NAME as owner for added files -p, --preserve-permissions, --same-permissions extract information about file permissions (default for superuser) --preserve same as both -p and -s --same-owner try extracting files with the same ownership as exists in the archive (default for superuser) -s, --preserve-order, --same-order sort names to extract to match archive Handling of extended file attributes: --acls Enable the POSIX ACLs support --no-acls Disable the POSIX ACLs support --no-selinux Disable the SELinux context support --no-xattrs Disable extended attributes support --selinux Enable the SELinux context support --xattrs Enable extended attributes support --xattrs-exclude=MASK specify the exclude pattern for xattr keys --xattrs-include=MASK specify the include pattern for xattr keys Device selection and switching: -f, --file=ARCHIVE use archive file or device ARCHIVE --force-local archive file is local even if it has a colon -F, --info-script=NAME, --new-volume-script=NAME run script at end of each tape (implies -M) -L, --tape-length=NUMBER change tape after writing NUMBER x 1024 bytes -M, --multi-volume create/list/extract multi-volume archive --rmt-command=COMMAND use given rmt COMMAND instead of rmt --rsh-command=COMMAND use remote COMMAND instead of rsh --volno-file=FILE use/update the volume number in FILE Device blocking: -b, --blocking-factor=BLOCKS BLOCKS x 512 bytes per record -B, --read-full-records reblock as we read (for 4.2BSD pipes) -i, --ignore-zeros ignore zeroed blocks in archive (means EOF) --record-size=NUMBER NUMBER of bytes per record, multiple of 512 Archive format selection: -H, --format=FORMAT create archive of the given format FORMAT is one of the following: gnu GNU tar 1.13.x format oldgnu GNU format as per tar <= 1.12 pax POSIX 1003.1-2001 (pax) format posix same as pax ustar POSIX 1003.1-1988 (ustar) format v7 old V7 tar format --old-archive, --portability same as --format=v7 --pax-option=keyword[[:]=value][,keyword[[:]=value]]... control pax keywords --posix same as --format=posix -V, --label=TEXT create archive with volume name TEXT; at list/extract time, use TEXT as a globbing pattern for volume name Compression options: -a, --auto-compress use archive suffix to determine the compression program -I, --use-compress-program=PROG filter through PROG (must accept -d) -j, --bzip2 filter the archive through bzip2 -J, --xz filter the archive through xz --lzip filter the archive through lzip --lzma filter the archive through lzma --lzop --no-auto-compress do not use archive suffix to determine the compression program -z, --gzip, --gunzip, --ungzip filter the archive through gzip -Z, --compress, --uncompress filter the archive through compress Local file selection: --add-file=FILE add given FILE to the archive (useful if its name starts with a dash) --backup[=CONTROL] backup before removal, choose version CONTROL -C, --directory=DIR change to directory DIR --exclude=PATTERN exclude files, given as a PATTERN --exclude-backups exclude backup and lock files --exclude-caches exclude contents of directories containing CACHEDIR.TAG, except for the tag file itself --exclude-caches-all exclude directories containing CACHEDIR.TAG --exclude-caches-under exclude everything under directories containing CACHEDIR.TAG --exclude-tag=FILE exclude contents of directories containing FILE, except for FILE itself --exclude-tag-all=FILE exclude directories containing FILE --exclude-tag-under=FILE exclude everything under directories containing FILE --exclude-vcs exclude version control system directories -h, --dereference follow symlinks; archive and dump the files they point to --hard-dereference follow hard links; archive and dump the files they refer to -K, --starting-file=MEMBER-NAME begin at member MEMBER-NAME in the archive --newer-mtime=DATE compare date and time when data changed only --no-null disable the effect of the previous --null option --no-recursion avoid descending automatically in directories --no-unquote do not unquote filenames read with -T --null -T reads null-terminated names, disable -C -N, --newer=DATE-OR-FILE, --after-date=DATE-OR-FILE only store files newer than DATE-OR-FILE --one-file-system stay in local file system when creating archive -P, --absolute-names don't strip leading `/'s from file names --recursion recurse into directories (default) --suffix=STRING backup before removal, override usual suffix ('~' unless overridden by environment variable SIMPLE_BACKUP_SUFFIX) -T, --files-from=FILE get names to extract or create from FILE --unquote unquote filenames read with -T (default) -X, --exclude-from=FILE exclude patterns listed in FILE File name transformations: --strip-components=NUMBER strip NUMBER leading components from file names on extraction --transform=EXPRESSION, --xform=EXPRESSION use sed replace EXPRESSION to transform file names File name matching options (affect both exclude and include patterns): --anchored patterns match file name start --ignore-case ignore case --no-anchored patterns match after any `/' (default for exclusion) --no-ignore-case case sensitive matching (default) --no-wildcards verbatim string matching --no-wildcards-match-slash wildcards do not match `/' --wildcards use wildcards (default) --wildcards-match-slash wildcards match `/' (default for exclusion) Informative output: --checkpoint[=NUMBER] display progress messages every NUMBERth record (default 10) --checkpoint-action=ACTION execute ACTION on each checkpoint --full-time print file time to its full resolution --index-file=FILE send verbose output to FILE -l, --check-links print a message if not all links are dumped --no-quote-chars=STRING disable quoting for characters from STRING --quote-chars=STRING additionally quote characters from STRING --quoting-style=STYLE set name quoting style; see below for valid STYLE values -R, --block-number show block number within archive with each message --show-defaults show tar defaults --show-omitted-dirs when listing or extracting, list each directory that does not match search criteria --show-transformed-names, --show-stored-names show file or archive names after transformation --totals[=SIGNAL] print total bytes after processing the archive; with an argument - print total bytes when this SIGNAL is delivered; Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1 and SIGUSR2; the names without SIG prefix are also accepted --utc print file modification times in UTC -v, --verbose verbosely list files processed --warning=KEYWORD warning control -w, --interactive, --confirmation ask for confirmation for every action Compatibility options: -o when creating, same as --old-archive; when extracting, same as --no-same-owner Other options: -?, --help give this help list --restrict disable use of some potentially harmful options --usage give a short usage message --version print program version Mandatory or optional arguments to long options are also mandatory or optional for any corresponding short options. The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control may be set with --backup or VERSION_CONTROL, values are: none, off never make backups t, numbered make numbered backups nil, existing numbered if numbered backups exist, simple otherwise never, simple always make simple backups Valid arguments for the --quoting-style option are: literal shell shell-always c c-maybe escape locale clocale *This* tar defaults to: --format=gnu -f- -b20 --quoting-style=escape --rmt-command=/etc/rmt --rsh-command=/usr/bin/ssh Report bugs to <bug-tar@gnu.org>.
Vous allez maintenant sauvegarder votre dossier test ainsi que son contenu vers un fichier :
[root@centos7 repZ]# tar cvf /tmp/test.tar /test tar: Removing leading `/' from member names /test/ /test/repY/ /test/repY/Y1 /test/repY/Y2 /test/repY/Y3 /test/repZ/ /test/repZ/Z1 /test/repZ/Z2
Pour visualiser la table of contents de votre sauvegarde, utilisez la commande suivante :
[root@centos7 repZ]# tar tvf /tmp/test.tar drwxr-xr-x root/root 0 2015-10-27 11:24 test/ drwxr-xr-x root/root 0 2015-10-27 11:24 test/repY/ -rw-r--r-- root/root 0 2015-10-27 11:24 test/repY/Y1 -rw-r--r-- root/root 0 2015-10-27 11:24 test/repY/Y2 -rw-r--r-- root/root 0 2015-10-27 11:24 test/repY/Y3 drwxr-xr-x root/root 0 2015-10-27 11:25 test/repZ/ -rw-r--r-- root/root 0 2015-10-27 11:25 test/repZ/Z1 -rw-r--r-- root/root 0 2015-10-27 11:25 test/repZ/Z2
Afin de créer une sauvegarde incrémentale, vous avez besoin de créer un fichier qui servira de référence de date :
[root@centos7 repZ]# touch /tmp/dateref
Modifiez maintenant deux des fichiers de votre arborescence test :
[root@centos7 repZ]# echo "CentOS est super \!" > /test/repY/Y1 [root@centos7 repZ]# echo "RHEL is wonderful \!" > /test/repZ/Z1
Pour procéder à votre sauvegarde incrémentale, vous devez sauvegarder uniquement les fichiers modifiés ou créés depuis la création de votre fichier /tmp/dateref.
Saisissez donc la commande suivante :
[root@centos7 repZ]# tar -cvf /tmp/incremental.tar -N /tmp/dateref /test tar: Removing leading `/' from member names /test/ /test/repY/ /test/repY/Y1 tar: /test/repY/Y2: file is unchanged; not dumped tar: /test/repY/Y3: file is unchanged; not dumped /test/repZ/ /test/repZ/Z1 tar: /test/repZ/Z2: file is unchanged; not dumped
Important - Notez l'utilisation de l'option -N avec l’argument /tmp/dateref qui permet d'identifier les fichiers modifiés ou créés depuis la création de /tmp/dateref.
Contrôlez maintenant le contenu de l'archive /tmp/incremental.tar :
[root@centos7 repZ]# tar tvf /tmp/incremental.tar drwxr-xr-x root/root 0 2015-10-27 11:24 test/ drwxr-xr-x root/root 0 2015-10-27 11:24 test/repY/ -rw-r--r-- root/root 20 2015-10-27 11:29 test/repY/Y1 drwxr-xr-x root/root 0 2015-10-27 11:25 test/repZ/ -rw-r--r-- root/root 21 2015-10-27 11:29 test/repZ/Z1
Supprimez maintenant le contenu du répertoire test :
[root@centos repZ]# rm -rf /test/*
Important - Notez que le système vous permet de supprimer le répertoire /test/repZ, or vous vous situez dans ce même répertoire !
Afin de pouvoir restaurer les fichiers de votre première sauvegarde, placez-vous à la racine de votre système et restaurez le contenu de votre répertoire test en saisissant la commande tar suivante :
[root@centos7 repZ]# cd / [root@centos7 /]# tar xvf /tmp/test.tar test/ test/repY/ test/repY/Y1 test/repY/Y2 test/repY/Y3 test/repZ/ test/repZ/Z1 test/repZ/Z2
Constatez maintenant que l'opération s'est bien déroulée :
[root@centos7 /]# ls -lR /test /test: total 0 drwxr-xr-x. 2 root root 33 Oct 27 11:24 repY drwxr-xr-x. 2 root root 24 Oct 27 11:25 repZ /test/repY: total 0 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y1 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y2 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y3 /test/repZ: total 0 -rw-r--r--. 1 root root 0 Oct 27 11:25 Z1 -rw-r--r--. 1 root root 0 Oct 27 11:25 Z2
Important - Notez qu'à ce stade les fichiers /test/repY/Y1 et /test/repZ/Z1 sont vides.
Restaurez maintenant votre archive incrémentale :
[root@centos7 /]# tar xvf /tmp/incremental.tar test/ test/repY/ test/repY/Y1 test/repZ/ test/repZ/Z1
Constatez maintenant que l'opération s'est bien déroulée :
[root@centos7 /]# ls -lR /test /test: total 0 drwxr-xr-x. 2 root root 33 Oct 27 11:24 repY drwxr-xr-x. 2 root root 24 Oct 27 11:25 repZ /test/repY: total 4 -rw-r--r--. 1 root root 20 Oct 27 11:29 Y1 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y2 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y3 /test/repZ: total 4 -rw-r--r--. 1 root root 21 Oct 27 11:29 Z1 -rw-r--r--. 1 root root 0 Oct 27 11:25 Z2
Important - Notez que les fichiers /test/repY/Y1 et /test/repZ/Z1 sont maintenant non-vides.
Dernièrement, la commande tar peut archiver en utilisant des algorithmes de compression :
Algorythme | Option de la commande tar |
---|---|
gzip | z |
bzip2 | j |
lzma | J |
La commande cpio (Copy Input To Output). cpio peut gérer les archives au format tar. La différence majeure entre tar et cpio est que ce dernier stocke les chemins d'accès aux fichiers sauvgardés en même temps que les fichiers eux-mêmes. Ceci implique que dans le cas où le chemin absolu a été spécifié lors de la sauvegarde, il est impossible de restaurer un fichier à un autre emplacement que son emplacement d'origine.
Vous allez utiliser maintenant le logiciel cpio pour effectuer les sauvegardes et restaurations.
Les options de la commande cpio sont :
[root@centos7 /]# cpio --help Usage: cpio [OPTION...] [destination-directory] GNU `cpio' copies files to and from archives Examples: # Copy files named in name-list to the archive cpio -o < name-list [> archive] # Extract files from the archive cpio -i [< archive] # Copy files named in name-list to destination-directory cpio -p destination-directory < name-list Main operation mode: -i, --extract Extract files from an archive (run in copy-in mode) -o, --create Create the archive (run in copy-out mode) -p, --pass-through Run in copy-pass mode -t, --list Print a table of contents of the input Operation modifiers valid in any mode: --block-size=BLOCK-SIZE Set the I/O block size to BLOCK-SIZE * 512 bytes -B Set the I/O block size to 5120 bytes -c Identical to "-H newc", use the new (SVR4) portable format.If you wish the old portable (ASCII) archive format, use "-H odc" instead. -C, --io-size=NUMBER Set the I/O block size to the given NUMBER of bytes --force-local Archive file is local, even if its name contains colons -f, --nonmatching Only copy files that do not match any of the given patterns -F, --file=[[USER@]HOST:]FILE-NAME Use this FILE-NAME instead of standard input or output. Optional USER and HOST specify the user and host names in case of a remote archive -H, --format=FORMAT Use given archive FORMAT -M, --message=STRING Print STRING when the end of a volume of the backup media is reached -n, --numeric-uid-gid In the verbose table of contents listing, show numeric UID and GID --quiet Do not print the number of blocks copied --rsh-command=COMMAND Use remote COMMAND instead of rsh -v, --verbose Verbosely list the files processed -V, --dot Print a "." for each file processed -W, --warning=FLAG Control warning display. Currently FLAG is one of 'none', 'truncate', 'all'. Multiple options accumulate. Operation modifiers valid only in copy-in mode: -b, --swap Swap both halfwords of words and bytes of halfwords in the data. Equivalent to -sS -r, --rename Interactively rename files -s, --swap-bytes Swap the bytes of each halfword in the files -S, --swap-halfwords Swap the halfwords of each word (4 bytes) in the files --to-stdout Extract files to standard output -E, --pattern-file=FILE Read additional patterns specifying filenames to extract or list from FILE --only-verify-crc When reading a CRC format archive, only verify the checksum of each file in the archive, don't actually extract the files Operation modifiers valid only in copy-out mode: -A, --append Append to an existing archive. -O [[USER@]HOST:]FILE-NAME Archive filename to use instead of standard output. Optional USER and HOST specify the user and host names in case of a remote archive Operation modifiers valid only in copy-pass mode: -l, --link Link files instead of copying them, when possible Operation modifiers valid in copy-in and copy-out modes: --absolute-filenames Do not strip file system prefix components from the file names --no-absolute-filenames Create all files relative to the current directory Operation modifiers valid in copy-out and copy-pass modes: -0, --null A list of filenames is terminated by a null character instead of a newline -a, --reset-access-time Reset the access times of files after reading them -I [[USER@]HOST:]FILE-NAME Archive filename to use instead of standard input. Optional USER and HOST specify the user and host names in case of a remote archive -L, --dereference Dereference symbolic links (copy the files that they point to instead of copying the links). -R, --owner=[USER][:.][GROUP] Set the ownership of all files created to the specified USER and/or GROUP Operation modifiers valid in copy-in and copy-pass modes: -d, --make-directories Create leading directories where needed -m, --preserve-modification-time Retain previous file modification times when creating files --no-preserve-owner Do not change the ownership of the files --sparse Write files with large blocks of zeros as sparse files -u, --unconditional Replace all files unconditionally -?, --help give this help list --usage give a short usage message --version print program version Mandatory or optional arguments to long options are also mandatory or optional for any corresponding short options. Report bugs to <bug-cpio@gnu.org>.
Dans un premier temps, vous devez utiliser la commande find pour construire une liste de fichiers à sauvegarder :
[root@centos7 /]# find /test > /tmp/cpio.liste [root@centos7 /]# cat /tmp/cpio.liste /test /test/repY /test/repY/Y2 /test/repY/Y3 /test/repY/Y1 /test/repZ /test/repZ/Z2 /test/repZ/Z1
Sauvegardez maintenant les fichiers et répertoires référencés par le fichier /tmp/cpio.liste :
[root@centos7 /]# cpio -ov < /tmp/cpio.liste > /tmp/test.cpio /test /test/repY /test/repY/Y2 /test/repY/Y3 /test/repY/Y1 /test/repZ /test/repZ/Z2 /test/repZ/Z1 1 block
Consultez maintenant la table of contents de votre sauvegarde :
[root@centos7 /]# cpio -it < /tmp/test.cpio /test /test/repY /test/repY/Y2 /test/repY/Y3 /test/repY/Y1 /test/repZ /test/repZ/Z2 /test/repZ/Z1 1 block
Supprimez maintenant le répertoire /test/repY et son contenu :
[root@centos7 /]# rm -rf /test/repY
Contrôlez le bon déroulement de la suppression :
[root@centos7 /]# ls -lR /test /test: total 0 drwxr-xr-x. 2 root root 24 Oct 27 11:25 repZ /test/repZ: total 4 -rw-r--r--. 1 root root 21 Oct 27 11:29 Z1 -rw-r--r--. 1 root root 0 Oct 27 11:25 Z2
Restaurez les fichiers supprimés :
[root@centos7 /]# cpio -ivdum "/test/repY/*" < /tmp/test.cpio /test/repY/Y2 /test/repY/Y3 /test/repY/Y1 1 block
Important - Notez l'utilisation de la chaîne “/test/repY/*” qui permet de rechercher uniquement le répertoire repY ainsi que les fichiers Y1, Y2 et Y3 dans l'archive test.cpio.
Contrôlez le bon déroulement de la restauration :
[root@centos7 /]# ls -lR /test /test: total 0 drwxr-xr-x. 2 root root 33 Oct 27 11:43 repY drwxr-xr-x. 2 root root 24 Oct 27 11:25 repZ /test/repY: total 4 -rw-r--r--. 1 root root 20 Oct 27 11:29 Y1 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y2 -rw-r--r--. 1 root root 0 Oct 27 11:24 Y3 /test/repZ: total 4 -rw-r--r--. 1 root root 21 Oct 27 11:29 Z1 -rw-r--r--. 1 root root 0 Oct 27 11:25 Z2
La commande dd n'est pas réellement une commande de sauvegarde.
La commande dd copie le fichier passé en entrée dans le fichier de sortie en limitant le nombre d'octets copiés par l'utilisation de deux options :
Les options de la commande dd sont :
[root@centos7 /]# dd --help Usage: dd [OPERAND]... or: dd OPTION Copy a file, converting and formatting according to the operands. bs=BYTES read and write up to BYTES bytes at a time cbs=BYTES convert BYTES bytes at a time conv=CONVS convert the file as per the comma separated symbol list count=N copy only N input blocks ibs=BYTES read up to BYTES bytes at a time (default: 512) if=FILE read from FILE instead of stdin iflag=FLAGS read as per the comma separated symbol list obs=BYTES write BYTES bytes at a time (default: 512) of=FILE write to FILE instead of stdout oflag=FLAGS write as per the comma separated symbol list seek=N skip N obs-sized blocks at start of output skip=N skip N ibs-sized blocks at start of input status=WHICH WHICH info to suppress outputting to stderr; 'noxfer' suppresses transfer stats, 'none' suppresses all N and BYTES may be followed by the following multiplicative suffixes: c =1, w =2, b =512, kB =1000, K =1024, MB =1000*1000, M =1024*1024, xM =M GB =1000*1000*1000, G =1024*1024*1024, and so on for T, P, E, Z, Y. Each CONV symbol may be: ascii from EBCDIC to ASCII ebcdic from ASCII to EBCDIC ibm from ASCII to alternate EBCDIC block pad newline-terminated records with spaces to cbs-size unblock replace trailing spaces in cbs-size records with newline lcase change upper case to lower case ucase change lower case to upper case sparse try to seek rather than write the output for NUL input blocks swab swap every pair of input bytes sync pad every input block with NULs to ibs-size; when used with block or unblock, pad with spaces rather than NULs excl fail if the output file already exists nocreat do not create the output file notrunc do not truncate the output file noerror continue after read errors fdatasync physically write output file data before finishing fsync likewise, but also write metadata Each FLAG symbol may be: append append mode (makes sense only for output; conv=notrunc suggested) direct use direct I/O for data directory fail unless a directory dsync use synchronized I/O for data sync likewise, but also for metadata fullblock accumulate full blocks of input (iflag only) nonblock use non-blocking I/O noatime do not update access time nocache discard cached data noctty do not assign controlling terminal from file nofollow do not follow symlinks count_bytes treat 'count=N' as a byte count (iflag only) skip_bytes treat 'skip=N' as a byte count (iflag only) seek_bytes treat 'seek=N' as a byte count (oflag only) Sending a USR1 signal to a running 'dd' process makes it print I/O statistics to standard error and then resume copying. $ dd if=/dev/zero of=/dev/null& pid=$! $ kill -USR1 $pid; sleep 1; kill $pid 18335302+0 records in 18335302+0 records out 9387674624 bytes (9.4 GB) copied, 34.6279 seconds, 271 MB/s Options are: --help display this help and exit --version output version information and exit GNU coreutils online help: <http://www.gnu.org/software/coreutils/> For complete documentation, run: info coreutils 'dd invocation'
Vous allez utiliser maintenant le logiciel dd pour effectuer une sauvegarde de votre MBR et de la table des partitions.
Effectuez une sauvegarde de votre MBR qui se trouve dans les premiers 446 octets de votre disque /dev/sda :
[root@centos7 /]# dd if=/dev/sda of=/tmp/mbr.save bs=1 count=446 446+0 records in 446+0 records out 446 bytes (446 B) copied, 0.0568353 s, 7.8 kB/s
Effectuez maintenant une sauvegarde de votre table des partitions qui se trouve dans les 64 octets après les 446 précédemment sauvegardés :
[root@centos7 /]# dd if=/dev/sda of=/tmp/tblpart.save bs=1 count=64 skip=446 64+0 records in 64+0 records out 64 bytes (64 B) copied, 0.000831091 s, 77.0 kB/s
Important - Notez l'utilisation de l'option skip qui permet de positionner le début de la sauvegarde au 447ième octet.
Les commandes dump et restore se basent sur le format d'enregistrement des données ( ext3 ). Pour cette raison il n'est pas possible de sauvegarder des répertoires à l'intérieur d'un système de fichiers mais uniquement des systèmes de fichiers complets.
Il est important de noter que le système de fichier ne doit pas être utilisé pendant le processus de dump. Pour cette raison il est normalement conseillé de démonter le système de fichiers.
Il existe 10 niveaux de dump possibles de 0 à 9. Lors d'un dump le niveau est spécifié. Chaque fois qu'un dump est effectué, cette information est sauvegardée dans le fichier /etc/dumpdates.
Par définition un dump de niveau 0 est une sauvegarde complète tandis que le dump de niveau 1 est une sauvegarde incrémentale.
Notez que les fichiers sont sauvegardés avec des nom relatifs. Ceci implique que vous devez vous positionner dans le système de fichiers lors de la restauration avec la commande restore.
La commande gzip est un utilitaire de compression sous GNU/Linux. La commande gunzip est un utilitaire de décompression sous GNU/Linux.
Les options de la commande gzip sont :
[root@centos7 /]# gzip --help Usage: gzip [OPTION]... [FILE]... Compress or uncompress FILEs (by default, compress FILES in-place). Mandatory arguments to long options are mandatory for short options too. -c, --stdout write on standard output, keep original files unchanged -d, --decompress decompress -f, --force force overwrite of output file and compress links -h, --help give this help -l, --list list compressed file contents -L, --license display software license -n, --no-name do not save or restore the original name and time stamp -N, --name save or restore the original name and time stamp -q, --quiet suppress all warnings -r, --recursive operate recursively on directories -S, --suffix=SUF use suffix SUF on compressed files -t, --test test compressed file integrity -v, --verbose verbose mode -V, --version display version number -1, --fast compress faster -9, --best compress better --rsyncable Make rsync-friendly archive With no FILE, or when FILE is -, read standard input. Report bugs to <bug-gzip@gnu.org>.
Les options de la commande gunzip sont :
[root@centos7 /]# gunzip --help Usage: /bin/gunzip [OPTION]... [FILE]... Uncompress FILEs (by default, in-place). Mandatory arguments to long options are mandatory for short options too. -c, --stdout write on standard output, keep original files unchanged -f, --force force overwrite of output file and compress links -l, --list list compressed file contents -n, --no-name do not save or restore the original name and time stamp -N, --name save or restore the original name and time stamp -q, --quiet suppress all warnings -r, --recursive operate recursively on directories -S, --suffix=SUF use suffix SUF on compressed files -t, --test test compressed file integrity -v, --verbose verbose mode --help display this help and exit --version display version information and exit With no FILE, or when FILE is -, read standard input. Report bugs to <bug-gzip@gnu.org>.
Utilisez gzip pour compresser votre fichier tar :
[root@centos7 /]# gzip /tmp/test.tar
Constatez la taille du fichier test.tar.gz :
[root@centos7 /]# ls -l /tmp/test.tar.gz -rw-r--r--. 1 root root 219 Oct 27 11:27 /tmp/test.tar.gz
Important - Notez que le fichier compressé a été créé dans le même répertoire que le fichier source et que le fichier source a disparu.
Décompressez le fichier test.tar.gz :
[root@centos /]# gunzip /tmp/test.tar.gz
La commande bzip2 est un utilitaire de compression sous GNU/Linux. La commande bunzip2 est un utilitaire de décompression sous GNU/Linux.
Les options de la commande bzip2 sont :
[root@centos7 /]# bzip2 --help bzip2, a block-sorting file compressor. Version 1.0.6, 6-Sept-2010. usage: bzip2 [flags and input files in any order] -h --help print this message -d --decompress force decompression -z --compress force compression -k --keep keep (don't delete) input files -f --force overwrite existing output files -t --test test compressed file integrity -c --stdout output to standard out -q --quiet suppress noncritical error messages -v --verbose be verbose (a 2nd -v gives more) -L --license display software version & license -V --version display software version & license -s --small use less memory (at most 2500k) -1 .. -9 set block size to 100k .. 900k --fast alias for -1 --best alias for -9 If invoked as `bzip2', default action is to compress. as `bunzip2', default action is to decompress. as `bzcat', default action is to decompress to stdout. If no file names are given, bzip2 compresses or decompresses from standard input to standard output. You can combine short flags, so `-v -4' means the same as -v4 or -4v, &c.
Les options de la commande bunzip2 sont :
[root@centos7 /]# bunzip2 --help bzip2, a block-sorting file compressor. Version 1.0.6, 6-Sept-2010. usage: bunzip2 [flags and input files in any order] -h --help print this message -d --decompress force decompression -z --compress force compression -k --keep keep (don't delete) input files -f --force overwrite existing output files -t --test test compressed file integrity -c --stdout output to standard out -q --quiet suppress noncritical error messages -v --verbose be verbose (a 2nd -v gives more) -L --license display software version & license -V --version display software version & license -s --small use less memory (at most 2500k) -1 .. -9 set block size to 100k .. 900k --fast alias for -1 --best alias for -9 If invoked as `bzip2', default action is to compress. as `bunzip2', default action is to decompress. as `bzcat', default action is to decompress to stdout. If no file names are given, bzip2 compresses or decompresses from standard input to standard output. You can combine short flags, so `-v -4' means the same as -v4 or -4v, &c.
Utilisez bzip2 pour compresser votre fichier tar :
[root@centos7 /]# bzip2 /tmp/test.tar
Constatez la taille du fichier tar.bz2 :
[root@centos7 /]# ls -l /tmp | grep test.tar.bz2 -rw-r--r--. 1 root root 206 Oct 27 11:27 test.tar.bz2
Important - Notez que le fichier compressé a été créé dans le même répertoire que le fichier source et que le fichier source a disparu.
Décompressez le fichier tar.bz2 :
[root@centos7 /]# bunzip2 /tmp/test.tar.bz2
La commande xz est un utilitaire de compression sous GNU/Linux. D'autres commandes sont :
La commande xz ne compressera pas le fichier si :
La commande xz ne décompressera pas le fichier si :
Les options de la commande xz sont :
[root@centos7 /]# xz --help Usage: xz [OPTION]... [FILE]... Compress or decompress FILEs in the .xz format. -z, --compress force compression -d, --decompress, --uncompress force decompression -t, --test test compressed file integrity -l, --list list information about .xz files -k, --keep keep (don't delete) input files -f, --force force overwrite of output file and (de)compress links -c, --stdout, --to-stdout write to standard output and don't delete input files -0 ... -9 compression preset; default is 6; take compressor *and* decompressor memory usage into account before using 7-9! -e, --extreme try to improve compression ratio by using more CPU time; does not affect decompressor memory requirements -T, --threads=NUM use at most NUM threads; the default is 1; set to 0 to use the number of processor cores -q, --quiet suppress warnings; specify twice to suppress errors too -v, --verbose be verbose; specify twice for even more verbose -h, --help display this short help and exit -H, --long-help display the long help (lists also the advanced options) -V, --version display the version number and exit With no FILE, or when FILE is -, read standard input. Report bugs to <lasse.collin@tukaani.org> (in English or Finnish). XZ Utils home page: <http://tukaani.org/xz/>
Utilisez xz pour compresser votre fichier tar :
[root@centos7 /]# xz /tmp/test.tar
Important - Notez que le fonctionnement par défaut de la commande est identique à celui de l'option -z.
Constatez la présence du fichier test.tar.xz :
[root@centos7 /]# ls -l /tmp | grep test.tar.xz -rw-r--r--. 1 root root 232 Oct 27 11:27 test.tar.xz
Important - Notez que le fichier compressé a été créé dans le même répertoire que le fichier source et que le fichier source a disparu. Le fichier source peut être maintenue si l'option –keep est spécifiée. Si le fichier test.tar.xz avait déjà existé, la commande aurait échouée avec un message d'erreur. L'extension du fichier est .xz, cependant la commande peut aussi gérer l'extension .lzma.
Décompressez le fichier test.tar.xz :
[root@centos7 /]# xz -d /tmp/test.tar.xz [root@centos7 /]# ls -l /tmp | grep test -rw-rw-r--. 1 trainee trainee 0 Oct 15 13:31 test -rw-r--r--. 1 root root 512 Oct 27 11:40 test.cpio -rw-r--r--. 1 root root 10240 Oct 27 11:27 test.tar
Il existe d'autres utilitaires pour la compression, chacun produisant un fichier ayant une extension spécifique :
Outil | Extension | Commande de Compression | Commande de Décompression |
---|---|---|---|
compress | .Z | compress | uncompress |
rar | .rar | rar | unrar |
zip | .zip | zip | unzip |
Lors de l'utilisation du shell, nous avons souvent besoin d'exécuter une commande sur plusieurs fichiers au lieu de les traiter individuellement. A cette fin nous pouvons utiliser les caractères spéciaux.
Caractère Spéciaux | Description |
---|---|
* | Représente 0 ou plus de caractères |
? | Représente un caractère |
[abc] | Représente un caractère parmi ceux entre crochets |
[!abc] | Représente un caractère ne trouvant pas parmi ceux entre crochets |
?(expression1|expression2| …) | Représente 0 ou 1 fois l'expression1 ou 0 ou 1 fois l'expression2 … |
*(expression1|expression2| …) | Représente 0 à x fois l'expression1 ou 0 à x fois l'expression2 … |
+(expression1|expression2| …) | Représente 1 à x fois l'expression1 ou 1 à x fois l'expression2 … |
@(expression1|expression2| …) | Représente 1 fois l'expression1 ou 1 fois l'expression2 … |
!(expression1|expression2| …) | Représente 0 fois l'expression1 ou 0 fois l'expression2 … |
Dans votre répertoire individuel, créez un répertoire training. Ensuite créez dans ce répertoire 5 fichiers nommés respectivement f1, f2, f3, f4 et f5 :
[trainee@centos7 ~]$ mkdir training [trainee@centos7 ~]$ cd training [trainee@centos7 training]$ touch f1 f2 f3 f4 f5
Afin de démontrer l'utilisation du caractère spécial *, saisissez la commande suivante :
[trainee@centos7 training]$ echo f* f1 f2 f3 f4 f5
Important : Notez que le caractère * remplace un caractère ou une suite de caractères.
Créez maintenant les fichiers f52 et f62 :
[trainee@centos7 training]$ touch f52 f62
Saisissez ensuite la commande suivante :
[trainee@centos7 training]$ echo f?2 f52 f62
Important : Notez que le caractère ? remplace un seul caractère.
L'utilisation peut prendre plusieurs formes différentes :
Joker | Description |
---|---|
[xyz] | Représente le caractère x ou y ou z |
[m-t] | Représente le caractère m ou n …. t |
[!xyz] | Représente un caractère autre que x ou y ou z |
[!m-t] | Représente un caractère autre que m ou n …. t |
Afin de démontrer l'utilisation des caractères [ et ], créez le fichier a100 :
[trainee@centos7 training]$ touch a100
Ensuite saisissez les commandes suivantes et notez le résultat :
[trainee@centos7 training]$ echo [a-f]* a100 f1 f2 f3 f4 f5 f52 f62 [trainee@centos7 training]$ echo [af]* a100 f1 f2 f3 f4 f5 f52 f62
Important : Notez ici que tous les fichiers commençant par les lettres a, b, c, d, e ou f sont affichés à l'écran.
[trainee@centos7 training]$ echo [!a]* f1 f2 f3 f4 f5 f52 f62
Important : Notez ici que tous les fichiers sont affichés à l'écran, à l'exception d'un fichier commençant par la lettre a .
[trainee@centos7 training]$ echo [a-b]* a100
Important : Notez ici que seul le fichier commençant par la lettre a est affiché à l'écran car il n'existe pas de fichiers commençant par la lettre b.
[trainee@centos7 training]$ echo [a-f] [a-f]
Important : Notez que dans ce cas, il n'existe pas de fichiers dénommés a, b, c, d, e ou f. Pour cette raison, n'ayant trouvé aucune correspondance entre le filtre utilisé et les objets dans le répertoire courant, le commande echo retourne le filtre passé en argument, c'est-à-dire [a-f].
Activez l'option extglob du shell bash afin de pouvoir utiliser ?(expression), *(expression), +(expression), @(expression) et !(expression) :
[trainee@centos7 training]$ shopt -s extglob
La commande shopt est utilisée pour activer ou désactiver les options du comportement optional du shell. La liste des options peut être visualisée en exécutant la commande shopt sans options :
[trainee@centos7 training]$ shopt autocd off cdable_vars off cdspell off checkhash off checkjobs off checkwinsize on cmdhist on compat31 off compat32 off compat40 off compat41 off direxpand off dirspell off dotglob off execfail off expand_aliases on extdebug off extglob on extquote on failglob off force_fignore on globstar off gnu_errfmt off histappend on histreedit off histverify off hostcomplete off huponexit off interactive_comments on lastpipe off lithist off login_shell on mailwarn off no_empty_cmd_completion off nocaseglob off nocasematch off nullglob off progcomp on promptvars on restricted_shell off shift_verbose off sourcepath on xpg_echo of
Créez les fichiers f, f.txt, f123.txt, f123123.txt, f123123123.txt :
[trainee@centos7 training]$ touch f f.txt f123.txt f123123.txt f123123123.txt
Saisissez la commande suivante :
[trainee@centos7 training]$ ls f?(123).txt f123.txt f.txt
Important : Notez ici que la commande affiche les fichiers ayant un nom contenant 0 ou 1 occurence de la chaîne 123.
Saisissez la commande suivante :
[trainee@centos7 training]$ ls f*(123).txt f123123123.txt f123123.txt f123.txt f.txt
Important : Notez ici que la commande affiche les fichiers ayant un nom contenant de 0 jusqu'à x occurences de la chaîne 123.
Saisissez la commande suivante :
[trainee@centos7 training]$ ls f+(123).txt f123123123.txt f123123.txt f123.txt
Important : Notez ici que la commande affiche les fichiers ayant un nom contenant entre 1 et x occurences de la chaîne 123.
Saisissez la commande suivante :
[trainee@centos7 training]$ ls f@(123).txt f123.txt
Important : Notez ici que la commande affiche les fichiers ayant un nom contenant 1 seule occurence de la chaîne 123.
Saisissez la commande suivante :
[trainee@centos7 training]$ ls f!(123).txt f123123123.txt f123123.txt f.txt
Important : Notez ici que la commande n'affiche que les fichiers ayant un nom qui ne contient pas la chaîne 123.
Afin d'utiliser un caractère spécial dans un contexte littéral, il faut utiliser un caractère d'échappement. Il existe trois caractères d'échappement :
Caractère | Description |
---|---|
\ | Protège le caractère qui le suit |
' ' | Protège tout caractère, à l'exception du caractère ' lui-même, se trouvant entre les deux ' |
“ ” | Protège tout caractère, à l'exception des caractères “ lui-même, $, \ et ', se trouvant entre les deux “ |
Afin d'illustrer l'utilisation des caractères d'échappement, considérons la commande suivante :
$ echo * est un caractère spécial [Entrée]
Lors de la saisie de cette commande dans votre répertoire training, vous obtiendrez une fenêtre similaire à celle-ci :
[trainee@centos7 training]$ echo * est un caractère spécial a100 f f1 f123123123.txt f123123.txt f123.txt f2 f3 f4 f5 f52 f62 f.txt est un caractère spécial [trainee@centos7 training]$ echo \* est un caractère spécial * est un caractère spécial [trainee@centos7 training]$ echo "* est un caractère spécial" * est un caractère spécial [trainee@centos7 training]$ echo '* est un caractère spécial' * est un caractère spécial
<html>
Copyright © 2004-2017 Hugh Norris.<br><br> <a rel=“license” href=“http://creativecommons.org/licenses/by-nc-nd/3.0/fr/”><img alt=“Licence Creative Commons” style=“border-width:0” src=“http://i.creativecommons.org/l/by-nc-nd/3.0/fr/88x31.png” /></a><br />Ce(tte) oeuvre est mise à disposition selon les termes de la <a rel=“license” href=“http://creativecommons.org/licenses/by-nc-nd/3.0/fr/”>Licence Creative Commons Attribution - Pas d’Utilisation Commerciale - Pas de Modification 3.0 France</a>.
</html>