Anda di halaman 1dari 43

Chapter 1.

GNU/Linux tutorials

Chapter 1. GNU/Linux tutorials


Table of Contents 1.1. Console basics 1.1.1. The shell prompt 1.1.2. The shell prompt under X 1.1.3. The root account 1.1.4. The root shell prompt 1.1.5. GUI system administration tools 1.1.6. Virtual consoles 1.1.7. How to leave the command prompt 1.1.8. How to shutdown the system 1.1.9. Recovering a sane console 1.1.10. Additional package suggestions for the newbie 1.1.11. An extra user account 1.1.12. sudo configuration 1.1.13. Play time 1.2. Unix-like filesystem 1.2.1. Unix file basics 1.2.2. Filesystem internals 1.2.3. Filesystem permissions 1.2.4. Control of permissions for newly created files: umask 1.2.5. Permissions for groups of users (group) 1.2.6. Timestamps 1.2.7. Links 1.2.8. Named pipes (FIFOs) 1.2.9. Sockets 1.2.10. Device files 1.2.11. Special device files 1.2.12. procfs and sysfs 1.2.13. tmpfs 1.3. Midnight Commander (MC) 1.3.1. Customization of MC 1.3.2. Starting MC 1.3.3. File manager in MC 1.3.4. Command-line tricks in MC 1.3.5. The internal editor in MC 1.3.6. The internal viewer in MC

1.3.7. Auto-start features of MC 1.3.8. FTP virtual filesystem of MC 1.4. The basic Unix-like work environment 1.4.1. The login shell 1.4.2. Customizing bash 1.4.3. Special key strokes 1.4.4. Unix style mouse operations 1.4.5. The pager 1.4.6. The text editor 1.4.7. Setting a default text editor 1.4.8. Customizing vim 1.4.9. Recording the shell activities 1.4.10. Basic Unix commands 1.5. The simple shell command 1.5.1. Command execution and environment variable 1.5.2. "$ A G variable LN" 1.5.3. "$ A H variable PT" 1.5.4. "$ O E variable HM" 1.5.5. Command line options 1.5.6. Shell glob 1.5.7. Return value of the command 1.5.8. Typical command sequences and shell redirection 1.5.9. Command alias 1.6. Unix-like text processing 1.6.1. Unix text tools 1.6.2. Regular expressions 1.6.3. Replacement expressions 1.6.4. Global substitution with regular expressions 1.6.5. Extracting data from text file table 1.6.6. Script snippets for piping commands I think learning a computer system is like learning a new foreign language. Although tutorial books and documentation are helpful, you have to practice it yourself. In order to help you get started smoothly, I elaborate a few basic points. The powerful design of Debian GNU/Linux comes from the Unix operating system, i.e., a multiuser, multitasking operating system. You must learn to take advantage of the power of these features and similarities between Unix and GNU/Linux. Don't shy away from Unix oriented texts and don't rely solely on GNU/Linux texts, as this robs you of much useful information. Note If you have been using any Unix-like system for a while with command line tools, you

probably know everything I explain here. Please use this as a reality check and refresher.

1.1. Console basics


1.1.1. The shell prompt
Upon starting the system, you are presented with the character based login screen if you did not install X Window System with the display manager such as g m . Suppose your hostname is f o the login prompt d3 o, looks as follows.
folgn o oi:

If you did install a GUI environment such as GNOME or KDE, then you can get to a login prompt by CtrlAlt-F1, and you can return to the GUI environment via Alt-F7 (see Section 1.1.6, Virtual consoles below for more). At the login prompt, you type your username, e.g. p n u n and press the Enter-key, then type your egi, password and press the Enter-key again. Note Following the Unix tradition, the username and password of the Debian system are case sensitive. The username is usually chosen only from the lowercase. The first user account is usually created during the installation. Additional user accounts can be created with adduser(8) by root. The system starts with the greeting message stored in "/ t / o d (Message Of The Day) and presents a ecmt" command prompt.
Dba GULnxlnysdfoty ein N/iu en/i o t1 folgn pnun o oi: egi Pswr: asod Ls lgn SnAr2 0:93 20 o ty at oi: u p 2 92:4 07 n t1 Lnxsop 262--m6 # SPSnAr1 2:54 UC20 x66 iu noy ..01ad4 1 M u p 5 02:9 T 07 8_4 Teporm icue wt teDba GULnxsse aefe sfwr; h rgas nldd ih h ein N/iu ytm r re otae teeatdsrbto trsfrec pormaedsrbdi te h xc itiuin em o ah rga r ecie n h idvda flsi /s/hr/o//oyih. niiul ie n ursaedc*cprgt Dba GULnxcmswt ASLTL N WRAT,t teetn ein N/iu oe ih BOUEY O ARNY o h xet pritdb apial lw emte y plcbe a. fo~ o:$

Here, the main part of the greeting message can be customized by editing the "/ t / o d t i " file. The ecmt.al first line is generated from the system information using "u a e - n v ". nm srm Now you are in the shell. The shell interprets your commands.

1.1.2. The shell prompt under X


If you installed X Window System with a display manager such as GNOME's g m by selecting "Desktop d3 environment" task during the installation, you are presented with the graphical login screen upon starting your

system. You type your username and your password to login to the non-privileged user account. Use tab to navigate between username and password, or use the mouse and primary click. You can gain the shell prompt under X by starting a x t r i a - m l t rprogram such as gnome-emnleuao terminal(1), rxvt(1) or xterm(1). Under the GNOME Desktop environment, clicking "Applications" "Accessories" "Terminal" does the trick. You can also see the section below Section 1.1.6, Virtual consoles. Under some other Desktop systems (like f u b x there may be no obvious starting point for the menu. If l x o ), this happens, just try (right) clicking the center of the screen and hope for a menu to pop-up.

1.1.3. The root account


The root account is also called superuser or privileged user. From this account, you can perform the following system administration tasks. Read, write, and remove any files on the system irrespective of their file permissions Set file ownership and permissions of any files on the system Set the password of any non-privileged users on the system Login to any accounts without their passwords This unlimited power of root account requires you to be considerate and responsible when using it. Warning Never share the root password with others. Note File permissions of a file (including hardware devices such as CD-ROM etc. which are just another file for the Debian system) may render it unusable or inaccessible by nonroot users. Although the use of root account is a quick way to test this kind of situation, its resolution should be done through proper setting of file permissions and user's group membership (see Section 1.2.3, Filesystem permissions).

1.1.4. The root shell prompt


Here are a few basic methods to gain the root shell prompt by using the root password. Type r o at the character based login prompt. ot Click "Applications" "Accessories" "Root Terminal", under the GNOME Desktop environment. Type "s - " from any user shell prompt. u l This does not preserve the environment of the current user. Type "s " from any user shell prompt. u This preserves some of the environment of the current user.

1.1.5. GUI system administration tools


When your desktop menu does not start GUI system administration tools automatically with the appropriate privilege, you can start them from the root shell prompt of the X terminal emulator, such as gnometerminal(1), rxvt(1), or xterm(1). See Section 1.1.4, The root shell prompt and Section 7.8.4, Running X clients as root. Warning Never start the X display/session manager under the root account by typing in r o to ot the prompt of the display manager such as gdm3(1). Warning Never run untrusted remote GUI program under X Window when critical information is displayed since it may eavesdrop your X screen.

1.1.6. Virtual consoles


In the default Debian system, there are six switchable VT100-like character consoles available to start the command shell directly on the Linux host. Unless you are in a GUI environment, you can switch between the virtual consoles by pressing the L f - l - e and one of the F F keys simultaneously. Each character etAtky 1 6 console allows independent login to the account and offers the multiuser environment. This multiuser environment is a great Unix feature, and very addictive. If you are under the X Window System, you gain access to the character console 1 by pressing C r - l tlAt F key, i.e., the l f - t l k y the l f - l - e , and the F - e are pressed together. You can get 1 etCr-e, etAtky 1ky back to the X Window System, normally running on the virtual console 7, by pressing A t F . l-7 You can alternatively change to another virtual console, e.g. to the console 1, from the commandline.
#cv 1 ht

1.1.7. How to leave the command prompt


You type C r - , i.e., the l f - t l k yand the d k ypressed together, at the command prompt to tlD etCr-e -e close the shell activity. If you are at the character console, you return to the login prompt with this. Even though these control characters are referred as "control D" with the upper case, you do not need to press the Shift-key. The short hand expression, ^ , is also used for C r - . Alternately, you can type "exit". D tlD If you are at x-terminal-emulator(1), you can close x t r i a - m l t rwindow with this. -emnleuao

1.1.8. How to shutdown the system


Just like any other modern OS where the file operation involves caching data in memory for improved performance, the Debian system needs the proper shutdown procedure before power can safely be turned off. This is to maintain the integrity of files, by forcing all changes in memory to be written to disk. If the software power control is available, the shutdown procedure automatically turns off power of the system. (Otherwise, you may have to press power button for few seconds after the shutdown procedure.) You can shutdown the system under the normal multiuser mode from the commandline.

#sudw - nw hton h o

You can shutdown the system under the single-user mode from the commandline.
#pwrf - oeof i f

Alternatively, you may type C r - l - e e e(The l f - t l k y the l f - l - e , and the tlAtDlt etCr-e, etAtKy D l t are pressed together) to shutdown if "/ t / n t a " contains eee eciitb "c : 2 4 : t l l d l / b n s u d w - 1 - - n w in it. See inittab(5) for details. a135crate:si/hton t a h o" See Section 6.9.6, How to shutdown the remote system on SSH.

1.1.9. Recovering a sane console


When the screen goes berserk after doing some funny things such as "c t < o e b n r - i e ", type a sm-iayfl> "r s t at the command prompt. You may not be able to see the command echoed as you type. You may ee" also issue "c e r to clean up the screen. la"

1.1.10. Additional package suggestions for the newbie


Although even the minimal installation of the Debian system without any desktop environment tasks provides the basic Unix functionality, it is a good idea to install few additional commandline and curses based character terminal packages such as m and v mwith apt-get(8) for beginners to get started by the following. c i
#atgtudt p-e pae .. . #atgtisalm vmsd p-e ntl c i uo .. .

If you already had these packages installed, no new packages are installed. Table 1.1. List of interesting text-mode program packages package popcon
m c sd uo vm i

size

description

V:10, I:26 1297 A text-mode full-screen file manager V:45, I:73 1397 A program to allow limited root privileges to users V:17, I:38 1873 Unix text editor Vi IMproved, a programmers text editor (standard version) I:94 830 Unix text editor Vi IMproved, a programmers text editor (compact version) V:5, I:9 V:2, I:3 13038 GNU project Emacs, the Lisp based extensible text editor (version 23) 584 The Unix style cut-and-paste on the text console (daemon)

v m t n V:13, i-iy eas3 mc2 wm 3 gm p

V:30, I:86 1924 Text-mode WWW browsers

It may be a good idea to read some informative documentations. Table 1.2. List of informative documentation packages package popcon size description Debian Project documentation, (Debian FAQ) and other

dcdba o-ein dba-oiy einplc dvlpreeoes rfrne eeec mitgie an-ud dba-itr einhsoy dba-a einfq dclnxtx o-iu-et dclnxhm o-iu-tl ssdi-ud yamngie

I:84 I:7 I:0.7 I:0.5 I:0.2 I:77 I:84 I:0.5 I:0.2

408

documents

3381 Debian Policy Manual and related documents 1299 Guidelines and information for Debian developers 706 Debian New Maintainers' Guide

3571 History of the Debian Project 1212 Debian FAQ 8616 Linux HOWTOs and FAQ (text) 62564 Linux HOWTOs and FAQ (html) 964 The Linux System Administrators' Guide

You can install some of these packages by the following.


#atgtisalpcaenm p-e ntl akg_ae

1.1.11. An extra user account


If you do not want to use your main user account for the following training activities, you can create a training user account, e.g. f s by the following. ih
#adsrfs due ih

Answer all questions. This creates a new account named as f s . After your practice, you can remove this user account and its ih home directory by the following.
#dlsr-rmv-oefs eue -eoehm ih

1.1.12. sudo configuration


For the typical single user workstation such as the desktop Debian system on the laptop PC, it is common to deploy simple configuration of sudo(8) as follows to let the non-privileged user, e.g. p n u n to gain egi, administrative privilege just with his user password but without the root password.
#eh "egi AL(L)AL > /t/uor co pnun L=AL L" > ecsdes

Alternatively, it is also common to do as follows to let the non-privileged user, e.g. p n u n to gain egi, administrative privilege without any password.
#eh "egi AL(L)NPSW:L"> /t/uor co pnun L=AL OASDAL > ecsdes

This trick should only be used for the single user workstation which you administer and where you are the only user. Warning Do not set up accounts of regular users on multiuser workstation like this because it would be very bad for system security.

Caution The password and the account of the p n u nin the above example requires as much egi protection as the root password and the root account. Caution Administrative privilege in this context belongs to someone authorized to perform the system administration task on the workstation. Never give some manager in the Admin department of your company or your boss such privilege unless they are authorized and capable. Note For providing access privilege to limited devices and limited files, you should consider to use group to provide limited access instead of using the r o privilege via sudo(8). ot Note With more thoughtful and careful configuration, sudo(8) can grant limited administrative privileges to other users on a shared system without sharing the root password. This can help with accountability with hosts with multiple administrators so you can tell who did what. On the other hand, you might not want anyone else to have such privileges.

1.1.13. Play time


Now you are ready to play with the Debian system without risks as long as you use the non-privileged user account. This is because the Debian system is, even after the default installation, configured with proper file permissions which prevent non-privileged users from damaging the system. Of course, there may still be some holes which can be exploited but those who worry about these issues should not be reading this section but should be reading Securing Debian Manual. We learn the Debian system as a Unix-like system with the following. Section 1.2, Unix-like filesystem (basic concept) Section 1.3, Midnight Commander (MC) (survival method) Section 1.4, The basic Unix-like work environment (basic method) Section 1.5, The simple shell command (shell mechanism) Section 1.6, Unix-like text processing (text processing method)

1.2. Unix-like filesystem


In GNU/Linux and other Unix-like operating systems, files are organized into directories. All files and directories are arranged in one big tree rooted at "/ It's called a tree because if you draw the filesystem, it ". looks like a tree but it is upside down. These files and directories can be spread out over several devices. mount(8) serves to attach the filesystem found on some device to the big file tree. Conversely, umount(8) detaches it again. On recent Linux kernels, mount(8) with some options can bind part of a file tree somewhere else or can mount filesystem as shared,

private, slave, or unbindable. Supported mount options for each filesystem are available in "/ h r / o / i u - o - . . / o u e t t o / i e y t m / s a e d c l n x d c 2 6 * D c m n a i n f l s s e s ". Directories on Unix systems are called folders on some other systems. Please also note that there is no concept for drive such as "A " on any Unix system. There is one filesystem, and everything is included. This : is a huge advantage compared to Windows.

1.2.1. Unix file basics


Here are some Unix file basics. Filenames are case sensitive. That is, "M F L " and "M F l " are different files. YIE yie The root directory means root of the filesystem referred as simply "/ Don't confuse this with the ". home directory for the root user: "/ o t r o ". Every directory has a name which can contain any letters or symbols except "/ The root directory ". is an exception; its name is "/ (pronounced "slash" or "the root directory") and it cannot be renamed. " Each file or directory is designated by a fully-qualified filename, absolute filename, or path, giving the sequence of directories which must be passed through to reach it. The three terms are synonymous. All fully-qualified filenames begin with the "/ directory, and there's a "/ between each directory or " " file in the filename. The first "/ is the top level directory, and the other "/ separate successive " "'s subdirectories, until we reach the last entry which is the name of the actual file. The words used here can be confusing. Take the following fully-qualified filename as an example: "/ s / h r / e t b e / s m p g ". However, people also refers to its basename "u . a . z ursaekyalsu.a.z smpg" alone as a filename. The root directory has a number of branches, such as "/ t / and "/ s / These subdirectories in ec" u r ". turn branch into still more subdirectories, such as "/ t / n t d " and "/ s / o a / The whole ecii./ u r l c l ". thing viewed collectively is called the directory tree. You can think of an absolute filename as a route from the base of the tree ("/ to the end of some branch (a file). You also hear people talk about the ") directory tree as if it were a family tree encompassing all direct descendants of a single figure called the root directory ("/ thus subdirectories have parents, and a path shows the complete ancestry of a "): file. There are also relative paths that begin somewhere other than the root directory. You should remember that the directory ". / refers to the parent directory. This terminology also applies to other ." directory like structures, such as hierarchical data structures. There's no special directory path name component that corresponds to a physical device, such as your hard disk. This differs from RT-11, CP/M, OpenVMS, MS-DOS, AmigaOS, and Microsoft Windows, where the path contains a device name such as "C \ (However, directory entries do exist : ". that refer to physical devices as a part of the normal filesystem. See Section 1.2.2, Filesystem internals.) Note While you can use almost any letters or symbols in a file name, in practice it is a bad idea to do so. It is better to avoid any characters that often have special meanings on the command line, including spaces, tabs, newlines, and other special characters: { } ( ) [ ] ' ` " \ / > < | ; ! # & ^ * % @ $. If you want to separate words in

a name, good choices are the period, hyphen, and underscore. You could also capitalize each word, "L k T i ". Experienced Linux users tend to avoid spaces in iehs filenames. Note The word "root" can mean either "root user" or "root directory". The context of their usage should make it clear. Note The word path is used not only for fully-qualified filename as above but also for the command search path. The intended meaning is usually clear from the context. The detailed best practices for the file hierarchy are described in the Filesystem Hierarchy Standard ("/ s / h r / o / e i n p l c / h / h - . . x . z and hier(7)). You should remember the ursaedcdba-oiyfsfs23ttg" following facts as the starter. Table 1.3. List of usage of key directories directory
/ /t/ ec

usage of the directory the root directory system wide configuration files all the home directories for all non-privileged users

/ a / o / system log files vrlg /oe hm/

1.2.2. Filesystem internals


Following the Unix tradition, the Debian GNU/Linux system provides the filesystem under which physical data on hard disks and other storage devices reside, and the interaction with the hardware devices such as console screens and remote serial consoles are represented in an unified manner under "/ e / d v ". Each file, directory, named pipe (a way two programs can share data), or physical device on a Debian GNU/Linux system has a data structure called an inode which describes its associated attributes such as the user who owns it (owner), the group that it belongs to, the time last accessed, etc. If you are really interested, see "/ s / n l d / i u / s h for the exact definition of "s r c i o e in the Debian GNU/Linux uricuelnxf." tut nd" system. The idea of representing just about everything in the filesystem was a Unix innovation, and modern Linux kernels have developed this idea ever further. Now, even information about processes running in the computer can be found in the filesystem. This abstract and unified representation of physical entities and internal processes is very powerful since this allows us to use the same command for the same kind of operation on many totally different devices. It is even possible to change the way the kernel works by writing data to special files that are linked to running processes. Tip If you need to identify the correspondence between the file tree and the physical entity, execute mount(8) with no arguments.

1.2.3. Filesystem permissions


Filesystem permissions of Unix-like system are defined for three categories of affected users. The user who owns the file (u) Other users in the group which the file belongs to (g) All other users (o) also referred to as "world" and "everyone" For the file, each corresponding permission allows following actions. The read (r) permission allows owner to examine contents of the file. The write (w) permission allows owner to modify the file. The execute (x) permission allows owner to run the file as a command. For the directory, each corresponding permission allows following actions. The read (r) permission allows owner to list contents of the directory. The write (w) permission allows owner to add or remove files in the directory. The execute (x) permission allows owner to access files in the directory. Here, the execute permission on a directory means not only to allow reading of files in that directory but also to allow viewing their attributes, such as the size and the modification time. ls(1) is used to display permission information (and more) for files and directories. When it is invoked with the "- " option, it displays the following information in the order given. l Type of file (first character) Access permission of the file (nine characters, consisting of three characters each for user, group, and other in this order) Number of hard links to the file Name of the user who owns the file Name of the group which the file belongs to Size of the file in characters (bytes) Date and time of the file (mtime) Name of the file Table 1.4. List of the first character of "l - " output s l character meaning
-

d l c b p s

normal file directory symlink character device node block device node named pipe socket

chown(1) is used from the root account to change the owner of the file. chgrp(1) is used from the file's owner or root account to change the group of the file. chmod(1) is used from the file's owner or root account to change file and directory access permissions. Basic syntax to manipulate a f ofile is the following. o
#con<eonr fo hw nwwe> o #cgp<egop fo hr nwru> o #cmd [ga[-]rxs],.]fo ho uo]+=[wXt[.. o

For example, you can make a directory tree to be owned by a user f oand shared by a group b rby the o a following.
#c /oelcto/ d sm/oain #con- fobr. hw R o:a #cmd- u+w,=X. ho R grXor

There are three more special permission bits. The set user ID bit (s or S instead of user's x) The set group ID bit (s or S instead of group's x) The sticky bit (t or T instead of other's x) Here the output of "l - " for these bits is capitalized if execution bits hidden by these outputs are unset. s l Setting set user ID on an executable file allows a user to execute the executable file with the owner ID of the file (for example root). Similarly, setting set group ID on an executable file allows a user to execute the executable file with the group ID of the file (for example root). Because these settings can cause security risks, enabling them requires extra caution. Setting set group ID on a directory enables the BSD-like file creation scheme where all files created in the directory belong to the group of the directory. Setting the sticky bit on a directory prevents a file in the directory from being removed by a user who is not the owner of the file. In order to secure contents of a file in world-writable directories such as "/ m " or in tp group-writable directories, one must not only reset the write permission for the file but also set the sticky bit on the directory. Otherwise, the file can be removed and a new file can be created with the same name by any user who has write access to the directory. Here are a few interesting examples of file permissions.
$l - /t/asd/t/hdw/e/p /s/bnei4 s l ecpsw ecsao dvpp ursi/xm

cw--- 1ro ro r---ot ot 18 020-42 0:0/e/p 0, 070-9 70 dvpp -wr-- 1ro ro r--rot ot 12 20-41 0:9/t/asd 47 070-6 01 ecpsw -wr-- 1ro sao r---ot hdw 9320-41 0:9/t/hdw 4 070-6 01 ecsao -wrx- 1ro ro rs-rx ot ot 705 20-42 0:9/s/bnei4 006 070-2 52 ursi/xm $l -d/m /a/m /s/oa /a/al/s/r s l tp vrtp urlcl vrmi ursc dwrxw 1 ro ro 49 20-42 0:9/m rxwrt 0 ot ot 06 070-9 75 tp dwrs- 1 ro saf49 20-32 1:8/s/oa rxwrx 0 ot tf 06 070-4 84 urlcl dwrs- 4ro sc 49 20-42 0:1/s/r rxwrx ot r 06 070-7 03 ursc dwrs- 2ro mi 49 20-32 2:3/a/al rxwrx ot al 06 070-8 33 vrmi dwrxw 2ro ro 49 20-42 0:1/a/m rxwrt ot ot 06 070-9 71 vrtp

There is an alternative numeric mode to describe file permissions with chmod(1). This numeric mode uses 3 to 4 digit wide octal (radix=8) numbers. Table 1.5. The numeric mode for file permissions in chmod(1) commands digit 2nd digit 3rd digit 4th digit meaning sum of read (=4), write (=2), and execute (=1) permissions for user ditto for group ditto for other

1st optional digit sum of set user ID (=4), set group ID (=2), and sticky bit (=1)

This sounds complicated but it is actually quite simple. If you look at the first few (2-10) columns from "l s l command output and read it as a binary (radix=2) representation of file permissions ("-" being "0" and " "rwx" being "1"), the last 3 digit of the numeric mode value should make sense as an octal (radix=8) representation of file permissions to you. For example, try the following
$tuhfobr oc o a $cmdur,orfo ho =wg= o $cmd64br ho 4 a $l - fobr s l o a -wr-- 1pnunpnun1 20-42 0:2br r--regi egi 7 070-9 82 a -wr-- 1pnunpnun1 20-42 0:2fo r--regi egi 2 070-9 82 o

Tip If you need to access information displayed by "l - " in shell script, you should use s l pertinent commands such as test(1), stat(1) and readlink(1). The shell builtin such as "[ " or "t s " may be used too. et

1.2.4. Control of permissions for newly created files: umask


What permissions are applied to a newly created file or directory is restricted by the u a kshell builtin ms command. See dash(1), bash(1), and builtins(7).
(ieprisos =(euse fl prisos &~uakvle fl emsin) rqetd ie emsin) (ms au)

Table 1.6. The umask value examples umask file permissions created directory permissions created usage

02 02 00 02

-wr-r--r-wr-r-wr-

-wrxrx-rx -wrxrxwrx

writable only by the user writable by the group

The Debian system uses a user private group (UPG) scheme as its default. A UPG is created whenever a new user is added to the system. A UPG has the same name as the user for which it was created and that user is the only member of the UPG. UPG scheme makes it is safe to set umask to 0 0 since every user has 02 their own private group. (In some Unix variants, it is quite common to setup all normal users belonging to a single u e sgroup and is good idea to set umask to 0 2 for security in such cases.) sr 02

1.2.5. Permissions for groups of users (group)


In order to make group permissions to be applied to a particular user, that user needs to be made a member of the group using "s d v g ". uo ir Note Alternatively, you may dynamically add users to groups during the authentication process by adding "a t o t o a p m g o p s " line to "/ t / a . / o m n uh pinl a_ru.o ecpmdcmoa t " and setting "/ t / e u i y g o p c n ". (See Chapter 4, Authentication.) uh ecscrt/ru.of The hardware devices are just another kind of file on the Debian system. If you have problems accessing devices such as CD-ROM and USB memory stick from a user account, you should make that user a member of the relevant group. Some notable system-provided groups allow their members to access particular files and devices without r o privilege. ot Table 1.7. List of notable system-provided groups for file access group
dp i crm do ado ui vdo ie

description for accessible files and devices direct access to serial ports ("/ e / t S 0 3 ") dvty[-] limited access to serial ports for Dialup IP connection to trusted peers CD-ROM, DVD+/-RW drives audio device video device system monitoring logs some directories for junior administrative work: "/ s / o a ", "/ o e urlcl hm" Tip You need to belong to the d a o tgroup to reconfigure modem, dial anywhere, etc. ilu But if r o creates pre-defined configuration files for trusted peers in ot "/ t / p / e r / you only need to belong to the d pgroup to create Dialup IP e c p p p e s ", i connection to those trusted peers using pppd(8), pon(1), and poff(1) commands.

d a o t full and ilu

s a n r scanner(s) cne am d saf tf

Some notable system-provided groups allow their members to execute particular commands without r o ot privilege. Table 1.8. List of notable system provided groups for particular command executions group
sd uo

accessible commands execute s d without their password uo add, modify, and remove printers from printer databases

l a m n execute commands to pdi

For the full listing of the system provided users and groups, see the recent version of the "Users and Groups" document in "/ s / h r / o / a e p s w / s r - n - r u s h m " provided by the b s ursaedcbs-asduesadgop.tl ae p s w package. asd See passwd(5), group(5), shadow(5), newgrp(1), vipw(8), vigr(8), and pam_group(8) for management commands of the user and group system.

1.2.6. Timestamps
There are three types of timestamps for a GNU/Linux file. Table 1.9. List of types of timestamps type meaning

mtime the file modification time (l - ) s l ctime the file status change time (l - c s l) atime the last file access time (l - u s l) Note ctime is not file creation time. Overwriting a file changes all of the mtime, ctime, and atime attributes of the file. Changing ownership or permission of a file changes the ctime and atime attributes of the file. Reading a file changes the atime of the file. Note Even simply reading a file on the Debian system normally causes a file write operation to update atime information in the inode. Mounting a filesystem with "n a i e or otm" "r l t m " option makes the system skip this operation and results in faster file access eaie for the read. This is often recommended for laptops, because it reduces hard drive activity and saves power. See mount(8). Use touch(1) command to change timestamps of existing files. For timestamps, the l command outputs different strings under the modern English locale ("e _ S U F 8 s n U . T - ")

from under the old one ("C ").


$LN=nU.T- l - fo AGe_SUF8 s l o -wr-- 1pnunpnun320-30 0:7fo r--regi egi 080-5 04 o $LN= l - fo AGC s l o -wr-- 1pnunpnun3Mr 50:7fo r--regi egi a 04 o

Tip See Section 9.2.5, Customized display of time and date to customize "l - " output. s l

1.2.7. Links
There are two methods of associating a file "f o with a different filename "b r o" a ". Hard link Duplicate name for an existing file "l f o b r n o a" Symbolic link or symlink Special file that points to another file by name "l - f o b r n s o a" See the following example for changes in link counts and the subtle differences in the result of the r m command.
$eh "rgnlCnet >fo co Oiia otn" o $l -ifo s l o 2951-wr-- 1pnunpnun1 20-42 0:5fo 382 r--regi egi 7 070-9 81 o $l fobr n o a #hr ln ad ik $l - fobz #smik n s o a yln $l -ifobrbz s l o a a 2951-wr-- 2pnunpnun1 20-42 0:5br 382 r--regi egi 7 070-9 81 a 2958lwrxw 1pnunpnun 320-42 0:6bz- fo 383 rxwrx egi egi 070-9 81 a > o 2951-wr-- 2pnunpnun1 20-42 0:5fo 382 r--regi egi 7 070-9 81 o $r fo m o $eh "e Cnet >fo co Nw otn" o $l -ifobrbz s l o a a 2951-wr-- 1pnunpnun1 20-42 0:5br 382 r--regi egi 7 070-9 81 a 2958lwrxw 1pnunpnun 320-42 0:6bz- fo 383 rxwrx egi egi 070-9 81 a > o 2950-wr-- 1pnunpnun1 20-42 0:7fo 384 r--regi egi 2 070-9 81 o $ctbr a a Oiia Cnet rgnl otn $ctbz a a NwCnet e otn

The hardlink can be made within the same filesystem and shares the same inode number which the "- " i option with ls(1) reveals. The symlink always has nominal file access permissions of "r x w r x as shown in the above example, w r x w ", with the effective access permissions dictated by permissions of the file that it points to.

Caution It is generally good idea not to create complicated symbolic links or hardlinks at all unless you have a very good reason. It may cause nightmares where the logical combination of the symbolic links results in loops in the filesystem. Note It is generally preferable to use symbolic links rather than hardlinks unless you have a good reason for using a hardlink. The ". directory links to the directory that it appears in, thus the link count of any new directory starts at 2. " The ". " directory links to the parent directory, thus the link count of the directory increases with the addition . of new subdirectories. If you are just moving to Linux from Windows, it soon becomes clear how well-designed the filename linking of Unix is, compared with the nearest Windows equivalent of "shortcuts". Because it is implemented in the filesystem, applications can't see any difference between a linked file and the original. In the case of hardlinks, there really is no difference.

1.2.8. Named pipes (FIFOs)


A named pipe is a file that acts like a pipe. You put something into the file, and it comes out the other end. Thus it's called a FIFO, or First-In-First-Out: the first thing you put in the pipe is the first thing to come out the other end. If you write to a named pipe, the process which is writing to the pipe doesn't terminate until the information being written is read from the pipe. If you read from a named pipe, the reading process waits until there is nothing to read before terminating. The size of the pipe is always zero --- it does not store data, it just links two processes like the shell "| However, since this pipe has a name, the two processes don't have to be on ". the same command line or even be run by the same user. Pipes were a very influential innovation of Unix. For example, try the following
$c;mff mpp d kio yie $eh "el">yie&#ptit bcgon co hlo mpp u no akrud []82 1 02 $l - mpp s l yie pwr-- 1pnunpnun020-42 0:5mpp r--regi egi 070-9 82 yie $ctmpp a yie hlo el [] Dn 1+ oe eh "el">yie co hlo mpp $l mpp s yie mpp yie $r mpp m yie

1.2.9. Sockets
Sockets are used extensively by all the Internet communication, databases, and the operating system itself. It is similar to the named pipe (FIFO) and allows processes to exchange information even between different computers. For the socket, those processes do not need to be running at the same time nor to be running as the children of the same ancestor process. This is the endpoint for the inter process communication (IPC). The exchange of information may occur over the network between different hosts. The two most common ones are the Internet socket and the Unix domain socket.

Tip "n t t t - n provides a very useful overview of sockets that are open on a given esa a" system.

1.2.10. Device files


Device files refer to physical or virtual devices on your system, such as your hard disk, video card, screen, or keyboard. An example of a virtual device is the console, represented by "/ e / o s l ". dvcnoe There are 2 types of device files. Character device Accessed one character at a time 1 character = 1 byte E.g. keyboard device, serial port, Block device accessed in larger units called blocks 1 block > 1 byte E.g. hard disk, You can read and write device files, though the file may well contain binary data which may be an incomprehensible-to-humans gibberish. Writing data directly to these files is sometimes useful for the troubleshooting of hardware connections. For example, you can dump a text file to the printer device "/ e / p " or send modem commands to the appropriate serial port "/ e / t S ". But, unless this is done dvl0 dvty0 carefully, it may cause a major disaster. So be cautious. Note For the normal access to a printer, use lp(1). The device node number are displayed by executing ls(1) as the following.
$l - /e/d /e/tS /e/eo s l dvha dvty0 dvzr bwr-- 1ro crm 3 020-42 0:0/e/d r-w-ot do , 070-9 70 dvha cwr-- 1ro daot4 6 20-42 0:0/e/tS r-w-ot ilu , 4 070-9 70 dvty0 cwr-w 1ro ro r-wrot ot 1 520-42 0:0/e/eo , 070-9 70 dvzr

"/ e / d " has the major device number 3 and the minor device number 0. This is read/write dvha accessible by the user who belongs to c r mgroup. do "/ e / t S " has the major device number 4 and the minor device number 64. This is read/write dvty0 accessible by the user who belongs to d a o tgroup. ilu "/ e / e o has the major device number 1 and the minor device number 5. This is read/write dvzr" accessible by anyone.

In the Linux 2.6 system, the filesystem under "/ e / is automatically populated by the udev(7) mechanism. dv"

1.2.11. Special device files


There are some special device files. Table 1.10. List of special device files device file
/e/ul dvnl /e/ul dvnl /e/eo dvzr /e/adm dvrno

action description of response read read read return "end-of-file (EOF) character" return "the \ (NUL) character" (not the same as the number zero ASCII) 0 return random characters from a true random number generator, delivering real entropy (slow) return random characters from a cryptographically secure pseudorandom number generator write return nothing (a bottomless data dump pit)

/ e / r n o read dvuadm /e/ul dvfl

write return the disk-full (ENOSPC) error

These are frequently used in conjunction with the shell redirection (see Section 1.5.8, Typical command sequences and shell redirection).

1.2.12. procfs and sysfs


The procfs and sysfs mounted on "/ r c and "/ y " are the pseudo-filesystem and expose internal data po" ss structures of the kernel to the userspace. In other word, these entries are virtual, meaning that they act as a convenient window into the operation of the operating system. The directory "/ r c contains (among other things) one subdirectory for each process running on the po" system, which is named after the process ID (PID). System utilities that access process information, such as ps(1), get their information from this directory structure. The directories under "/ r c s s " contain interface to change certain kernel parameters at run time. (You po/y/ may do the same through specialized sysctl(8) command or its preload/configuration file "/ t / y c r . o f e c s s t l c n ".) Note The Linux kernel may complain "Too many open files". You can fix this by increasing "f l - a " value to a larger value from the root shell, e.g., "e h " 5 3 " > iemx co 656 / r c s s f / i e m x (This was needed on older kernels). po/y/sfl-a" People frequently panic when they notice one file in particular - "/ r c k o e - which is generally huge. po/cr" This is (more or less) a copy of the content of your computer's memory. It's used to debug the kernel. It is a virtual file that points to computer memory, so don't worry about its size. The directory under "/ y " contains exported kernel data structures, their attributes, and their linkages ss between them. It also contains interface to change certain kernel parameters at run time.

See "p o . x ( g ) "s s s t t . z " and other related documents in the Linux kernel documentation r c t t . z ", y f . x ( g ) ("/ s / h r / o / i u - o - . . / o u e t t o / i e y t m / ") provided by the l n x ursaedclnxdc26*Dcmnainflsses* iud c 2 6 *package. o-..

1.2.13. tmpfs
The tmpfs is a temporary filesystem which keeps all files in the virtual memory. The data of the tmpfs in the page cache on memory may be swapped out to the swap space on disk as needed. The directory "/ u " is mounted as the tmpfs in the early boot process. This enables writing to it even when rn the directory "/ is mounted as read-only. This is the new location for the storage of transient state files and " replaces several locations described in the Filesystem Hierarchy Standard version 2.3: "/ a / u " "/ u " vrrn rn "/ a / o k "/ u / o k vrlc" rnlc" "/ e / h " "/ u / h " dvsm rnsm See "t p s t t . z " in the Linux kernel documentation ("/ s / h r / o / i u - o mf.x(g) ursaedclnxdc * D c m n a i n f l s s e s * provided by the l n x d c *package. / o u e t t o / i e y t m / ") iu-o-

1.3. Midnight Commander (MC)


Midnight Commander (MC) is a GNU "Swiss army knife" for the Linux console and other terminal environments. This gives newbie a menu driven console experience which is much easier to learn than standard Unix commands. You may need to install the Midnight Commander package which is titled "m " by the following. c
$sd atgtisalm uo p-e ntl c

Use the mc(1) command to explore the Debian system. This is the best way to learn. Please explore few interesting locations just using the cursor keys and Enter key. "/ t " and its subdirectories ec "/ a / o " and its subdirectories vrlg "/ s / h r / o " and its subdirectories ursaedc "/ b n and "/ i " si" bn

1.3.1. Customization of MC
In order to make MC to change working directory upon exit and c to the directory, I suggest to modify d "~ . a h c to include a script provided by the m package. /bsr" c
./s/i/cm.h urlbm/cs

See mc(1) (under the "- " option) for the reason. (If you do not understand what exactly I am talking here, P you can do this later.)

1.3.2. Starting MC
MC can be started by the following.
$m c

MC takes care of all file operations through its menu, requiring minimal user effort. Just press F1 to get the help screen. You can play with MC just by pressing cursor-keys and function-keys. Note In some consoles such as gnome-terminal(1), key strokes of function-keys may be stolen by the console program. You can disable these features by "Edit" "Keyboard Shortcuts" for g o e t r i a . nm-emnl If you encounter character encoding problem which displays garbage characters, adding "- " to MC's a command line may help prevent problems. If this doesn't clear up your display problems with MC, see Section 9.6.6, The terminal configuration.

1.3.3. File manager in MC


The default is two directory panels containing file lists. Another useful mode is to set the right window to "information" to see file access privilege information, etc. Following are some essential keystrokes. With the gpm(8) daemon running, one can use a mouse on Linux character consoles, too. (Make sure to press the shift-key to obtain the normal behavior of cut and paste in MC.) Table 1.11. The key bindings of MC key
F 1 F 3 F 4 F 9 F0 1 Tb a

key binding help menu internal file viewer internal editor activate pull down menu exit Midnight Commander move between two windows file for a multiple-file operation such as copy delete file (be careful---set MC to safe delete mode) self-explanatory

I s r or C r - mark net tlT Dl e

Cursor keys

1.3.4. Command-line tricks in MC


c command d

changes the directory shown on the selected screen. the command line. Use this with cp(1) and mv(1)

C r - n e or A t E t rcopies a filename to tlEtr l-ne

commands together with command-line editing.

A t T bshows shell filename expansion choices. l-a

One can specify the starting directory for both windows as arguments to MC; for example, "m / t c ec /ot r o ".
E c+ n k y F (i.e., E c+ 1 F , etc.; E c+ 0 F 0 s -e n s 1 s 1)

Pressing E cbefore the key has the same effect as pressing the A tand the key together.; i.e., type s l E c+ cfor A t C E cis called meta-key and sometimes noted as "M ". s l-. s -

1.3.5. The internal editor in MC


The internal editor has an interesting cut-and-paste scheme. Pressing F marks the start of a selection, a 3 second F marks the end of selection and highlights the selection. Then you can move your cursor. If you 3 press F6, the selected area is moved to the cursor location. If you press F5, the selected area is copied and inserted at the cursor location. F saves the file. F 0gets you out. Most cursor keys work intuitively. 2 1 This editor can be directly started on a file using one of the following commands.
$m - flnm_oei c e ieaet_dt $mei flnm_oei cdt ieaet_dt

This is not a multi-window editor, but one can use multiple Linux consoles to achieve the same effect. To copy between windows, use Alt-F<n> keys to switch virtual consoles and use "FileInsert file" or "FileCopy to file" to move a portion of a file to another file. This internal editor can be replaced with any external editor of choice. Also, many programs use the environment variables "$ D T R or "$ I U L to decide which editor to use. EIO" VSA" If you are uncomfortable with vim(1) or nano(1) initially, you may set these to "m e i " by adding the cdt following lines to "~ . a h c / b s r ".
epr EIO=cdt xot DTRmei epr VSA=cdt xot IULmei

I do recommend setting these to "v m if possible. i" If you are uncomfortable with vim(1), you can keep using mcedit(1) for most system maintenance tasks.

1.3.6. The internal viewer in MC


MC is a very smart viewer. This is a great tool for searching words in documents. I always use this for files in the "/ s / h r / o " directory. This is the fastest way to browse through masses of Linux information. ursaedc This viewer can be directly started using one of the following commands.
$m - pt/oflnm_ove c v aht/ieaet_iw $mve pt/oflnm_ove ciw aht/ieaet_iw

1.3.7. Auto-start features of MC


Press Enter on a file, and the appropriate program handles the content of the file (see Section 9.5.11,

Customizing program to be started). This is a very convenient MC feature. Table 1.12. The reaction to the enter key in MC file type executable file man file html file reaction to enter key execute command pipe content to viewer software pipe content to web browser

"* t r g " and "* d b file browse its contents as if subdirectory .a.z .e"

In order to allow these viewer and virtual file features to function, viewable files should not be set as executable. Change their status using chmod(1) or via the MC file menu.

1.3.8. FTP virtual filesystem of MC


MC can be used to access files over the Internet using FTP. Go to the menu by pressing F , then type "p to 9 " activate the FTP virtual filesystem. Enter a URL in the form "u e n m : a s d h s n m . o a n a e s r a e p s w @ o t a e d m i n m ", which retrieves a remote directory that appears like a local one. Try "[http.us.debian.org/debian]" as the URL and browse the Debian archive.

1.4. The basic Unix-like work environment


Although MC enables you to do almost everything, it is very important for you to learn how to use the command line tools invoked from the shell prompt and become familiar with the Unix-like work environment.

1.4.1. The login shell


You can select your login shell with chsh(1). Table 1.13. List of shell programs package popcon
bs ah ts ch ds ah zh s pkh ds ch s

size

POSIX shell

description Bash: the GNU Bourne Again SHell (de facto standard) TENEX C Shell: an enhanced version of Berkeley csh Debian Almquist Shell, good for shell script Z shell: the standard shell with many enhancements public domain version of the Korn shell OpenBSD C Shell, a version of Berkeley csh Stand-alone shell with builtin commands (Not meant for standard "/ i / h b n s ") the real, AT&T version of the Korn shell

V:90, I:99 V:3, I:14 V:70, I:76 V:2, I:5

3935 Yes 1213 No 212 Yes Yes No Yes 11462 Yes 340

V:0.2, I:1.2 388 V:0.5, I:1.9

ss ah kh s

V:0.2, I:0.8 856 V:0.6, I:2

3092 Yes

r c ps oh

V:0.08, I:1.1 V:0.00, I:0.08

169 201

No Yes

implementation of the AT&T Plan 9 rc shell Policy-compliant Ordinary SHell (p k hderivative) ds

In this tutorial chapter, the interactive shell always means b s . ah

1.4.2. Customizing bash


You can customize bash(1) behavior by "~ . a h c / b s r ". For example, try the following.
#C uo eiigM D pn xtn C ./s/i/cm.h urlbm/cs #stCPT t go oe e DAH o od n CPT=:ursaedc~~Dstp~ DAH./s/hr/o::/eko: epr CPT xot DAH PT=$PT}:ursi:si AH"{AH"/s/bn/bn #stPT s i icue ue' piaebni i eit e AH o t nlds srs rvt i f t xss i [- ~bn];te f d /i hn PT=/i:$PT} AH~bn"{AH" f i epr PT xot AH EIO=i DTRvm epr EIO xot DTR

Tip You can find more b s customization tips, such as Section 9.2.7, Colorized ah commands, in Chapter 9, System tips.

1.4.3. Special key strokes


In the Unix-like environment, there are few key strokes which have special meanings. Please note that on a normal Linux character console, only the left-hand C r and A tkeys work as expected. Here are few tl l notable key strokes to remember. Table 1.14. List of key bindings for bash key
CrtlU CrtlH CrtlD CrtlC CrtlZ CrtlS

description of key binding erase line before cursor erase a character before cursor terminate input (exit shell if you are using shell) terminate a running program temporarily stop program by moving it to the background job halt output to screen

CrtlQ Cr-l-e tlAtDl L f - l - e (optionally, W n o s etAtky idwky e) U-ro parw CrtlR Tb a Cr- Tb tlV a

reactivate output to screen reboot/halt the system, see inittab(5) meta-key for Emacs and the similar UI start command history search under b s ah start incremental command history search under b s ah complete input of the filename to the command line under b s ah input T bwithout expansion to the command line under b s a ah

Tip The terminal feature of C r - can be disabled using stty(1). tlS

1.4.4. Unix style mouse operations


Unix style mouse operations are based on the 3 button mouse system. Table 1.15. List of Unix style mouse operations action Left-click Right-click Middle-click response select the start of selection select the end of selection and copy to the clipboard paste clipboard at the cursor

Left-click-and-drag mouse select and copy to the clipboard

The center wheel on the modern wheel mouse is considered middle mouse button and can be used for middle-click. Clicking left and right mouse buttons together serves as the middle-click under the 2 button mouse system situation. In order to use a mouse in Linux character consoles, you need to have gpm(8) running as daemon.

1.4.5. The pager


less(1) is the enhanced pager (file content browser). Hit "h for help. It can do much more than more(1) and " can be supercharged by executing "e a $ l s p p ) or "e a $ l s f l ) in the shell startup script. vl (esie" vl (esie" See more in "/ s / h r / o / e s / E S P N The "- " option allows raw character output and u r s a e d c l s f L S O E ". R enables ANSI color escape sequences. See less(1).

1.4.6. The text editor


You should become proficient in one of variants of Vim or Emacs programs which are popular in the Unixlike system. I think getting used to Vim commands is the right thing to do, since Vi-editor is always there in the Linux/Unix world. (Actually, original v or new n iare programs you find everywhere. I chose Vim instead for newbie i v since it offers you help through F key while it is similar enough and more powerful.) 1

If you chose either Emacs or XEmacs instead as your choice of the editor, that is another good choice indeed, particularly for programming. Emacs has a plethora of other features as well, including functioning as a newsreader, directory editor, mail program, etc. When used for programming or editing shell scripts, it intelligently recognizes the format of what you are working on, and tries to provide assistance. Some people maintain that the only program they need on Linux is Emacs. Ten minutes learning Emacs now can save hours later. Having the GNU Emacs manual for reference when learning Emacs is highly recommended. All these programs usually come with tutoring program for you to learn them by practice. Start Vim by typing "v m and press F1-key. You should at least read the first 35 lines. Then do the online training course by i" moving cursor to "| u o | and pressing C r - . ttr" tl] Note Good editors, such as Vim and Emacs, can be used to handle UTF-8 and other exotic encoding texts correctly with proper option in the x-terminal-emulator on X under UTF-8 locale with proper font settings. Please refer to their documentation on multibyte text.

1.4.7. Setting a default text editor


Debian comes with a number of different editors. We recommend to install the v mpackage, as mentioned i above. Debian provides unified access to the system default editor via command "/ s / i / d t r so other urbneio" programs (e.g., reportbug(1)) can invoke it. You can change it by the following.
$sd udt-lentvs-cni eio uo paeatraie -ofg dtr

The choice "/ s / i / i . a i " over "/ s / i / i . i y is my recommendation for newbies since urbnvmbsc urbnvmtn" it supports syntax highlighting. Tip Many programs use the environment variables "$ D T R or "$ I U L to decide EIO" VSA" which editor to use (see Section 1.3.5, The internal editor in MC and Section 9.5.11, Customizing program to be started). For the consistency on Debian system, set these to "/ s / i / d t r (Historically, "$ D T R was "e " and "$ I U L was "v ".) u r b n e i o ". EIO" d VSA" i

1.4.8. Customizing vim


You can customize vim(1) behavior by "~ . i r ". /vmc For example, try the following
"-----------------------------"Lclcniuain oa ofgrto " stncmail e ooptbe stnpse e oat stpseoge<2 e attgl=f> sno y n i $SR= "ot f UE = ro" stnmdln e ooeie

stnsafl e owpie es le stmdln e oeie stsafl e wpie edf ni "fle t aodteln aoebigrcgie a amdln ilr o vi h ie bv en eonzd s oeie "fle ilr "fle ilr

1.4.9. Recording the shell activities


The output of the shell command may roll off your screen and may be lost forever. It is good practice to log shell activities into the file for you to review them later. This kind of record is essential when you perform any system administration tasks. The basic method of recording the shell activity is to run it under script(1). For example, try the following
$srp cit Srp satd fl i tpsrp cit tre, ie s yecit

Do whatever shell commands under s r p . cit Press C r - to exit s r p . tlD cit


$vmtpsrp i yecit

See Section 9.2.3, Recording the shell activities cleanly .

1.4.10. Basic Unix commands


Let's learn basic Unix commands. Here I use "Unix" in its generic sense. Any Unix clone OSs usually offer equivalent commands. The Debian system is no exception. Do not worry if some commands do not work as you wish now. If a i sis used in the shell, its corresponding command outputs are different. These examples la are not meant to be executed in this order. Try all following commands from the non-privileged user account. Table 1.16. List of basic Unix commands command
pd w wom hai i d fl <o> ie fo tp ye p <omnnm> cmadae wih hc <omnnm> cmadae tp ye <omnnm> cmadae

description display name of current/working directory display current user name display current user identity (name, uid, gid, and associated groups) display a type of file for the file "< o > fo" display a file location of command "< o m n n m > cmadae" ,, display information on command "< o m n n m > cmadae"

arps<epoo ky wr> od mn- <ea k ky wr> od wai hts <omnnm> cmadae mna a <omnnm> cmadae if no <omnnm> cmadae l s l s a l s A l -a s l l -a s li l s d te re lo <o> sf fo lo - <i> sf p pd mdr<o> ki fo rdr<o> mi fo c <o> d fo c / d c d c /fo d <o> c . d . c ~fo d <o> c d <ecmt /t/od pgr ae tuh oc <ukie jnfl> c <o><a> p fo br r <ukie m jnfl> m <o><a> v fo br

find commands related to "< e - o d " kywr> ,, display one line explanation on command "< o m n n m > cmadae" display explanation on command "< o m n n m > (Unix style) cmadae" display rather long explanation on command "< o m n n m > (GNU style) cmadae" list contents of directory (non-dot files and directories) list contents of directory (all files and directories) list contents of directory (almost all files and directories, i.e., skip ". " and ". . ") list all contents of directory with detail information list all contents of directory with inode number and detail information list all directories under the current directory display file tree contents list open status of file "< o > fo" list files opened by the process ID: "< i > pd" make a new directory "< o > in the current directory fo" remove a directory "< o > in the current directory fo" change directory to the directory "< o > in the current directory or in the directory fo" listed in the variable "$ D A H CPT" change directory to the root directory change directory to the current user's home directory change directory to the absolute path directory "/ f o " <o> change directory to the parent directory change directory to the home directory of the user "< o > fo" change directory to the previous directory display contents of "/ t / o d using the default pager ecmt" create a empty file "< u k i e " jnfl> copy a existing file "< o > to a new file "< a > fo" br" remove a file "< u k i e " jnfl> rename an existing file "< o > to a new name "< a > ("< a > must not exist) fo" br" br"

move an existing file "< o > to a new location "< a > < o > (the directory fo" br/fo" m < o > < a > "< a > must exist) v fo br br"
m <o> v fo <a><a> br/bz

move an existing file "< o > to a new location with a new name "< a > < a > (the fo" br/bz" directory "< a > must exist but the directory "< a > < a > must not exist) br" br/bz"

cmd60<o> ho 0 fo cmd64<o> ho 4 fo cmd75<o> ho 5 fo fn .-ae id nm <atr> pten lct - . oae d <atr> pten ge - " rp e <atr> pten" *hm .tl tp o p ax|pgr s u ae p -f|pgr s e ae p ax|ge s u rp e"exm* []i4" p af|pgr s x ae kl <24 il 13> gi <o> zp fo gni <o>g uzp fo.z bi2<o> zp fo bni2 uzp <o>b2 fo.z x <o> z fo ux <o>x nz fo.z tr-v a xf <o>tr fo.a tr-vf a xz <o>trg fo.a.z tr-vf a xj <o>trb2 fo.a.z tr-vf a xJ <o>trx fo.a.z tr-v a cf <o>tr fo.a <a> br/ tr-vf a cz <o>trg fo.a.z <a> br/ tr-vf a cj <o>trb2 fo.a.z <a> br/ tr-vf a cJ

make an existing file "< o > to be non-readable and non-writable by the other fo" people (non-executable o > to be readable but non-writable by the other people make an existing file "< for all) fo" (non-executable for all) make an existing file "< o > to be readable but non-writable by the other people fo" (executable for all) find matching filenames using shell "< a t r > (slower) pten" find matching filenames using shell "< a t r > (quicker using regularly generated pten" database) find a "<pattern>" in all files ending with ". t l in current directory and display them hm" all display process information using full screen, type "q to quit " display information on all the running processes using BSD style output display information on all the running processes using Unix system-V style output display all processes running "e i " and "e i 4 xm xm" display information on all the running processes with ASCII art output kill a process identified by the process ID: "<1234>" compress "< o > to create "< o > g " using the Lempel-Ziv coding (LZ77) fo" fo.z decompress "< o > g " to create "< o > fo.z fo" compress "< o > to create "< o > b 2 using the Burrows-Wheeler block sorting fo" fo.z" text compression algorithm, and Huffman coding (better compression than g i ) zp decompress "< o > b 2 to create "< o > fo.z" fo" compress "< o > to create "< o > x " using the LempelZivMarkov chain fo" fo.z algorithm (better compression than b i 2 zp) decompress "< o > x " to create "< o > fo.z fo" extract files from "< o > t r archive fo.a" extract files from gzipped "< o > t r g " archive fo.a.z extract files from "< o > t r b 2 archive fo.a.z" extract files from "< o > t r x " archive fo.a.z archive contents of folder "< a > " in "< o > t r archive br/ fo.a" archive contents of folder "< a > " in compressed "< o > t r g " archive br/ fo.a.z archive contents of folder "< a > " in "< o > t r b 2 archive br/ fo.a.z"

<o>trx fo.a.z <a> br/ za RAM.z ct EDEg |pgr ae za RAM.z ct EDEg >fo o za RAM.z ct EDEg > fo > o

archive contents of folder "< a > " in "< o > t r x " archive br/ fo.a.z display contents of compressed "R A M . z using the default pager EDEg" create a file "f o with the decompressed content of "R A M . z o" EDEg" append the decompressed content of "R A M . z to the end of the file "f o (if it EDEg" o" does not exist, create it first)

Note Unix has a tradition to hide filenames which start with ". They are traditionally files ". that contain configuration information and user preferences. Note For c command, see builtins(7). d Note The default pager of the bare bone Debian system is more(1) which cannot scroll back. By installing the l s package using command line "a t g t i s a l l s ", es p-e ntl es less(1) becomes default pager and you can scroll back with cursor keys. Note The "[ and "] in the regular expression of the "p a x | g e - " e x m * " " " s u rp e []i4" command above enable g e to avoid matching itself. The "4 " in the regular rp * expression means 0 or more repeats of character "4 thus enables g e to match both " rp "e i " and "e i 4 Although "* is used in the shell filename glob and the regular xm x m ". " expression, their meanings are different. Learn the regular expression from grep(1). Please traverse directories and peek into the system using the above commands as training. If you have questions on any of console commands, please make sure to read the manual page. For example, try the following
$mnmn a a $mnbs a ah $mnbitn a ulis $mnge a rp $mnl a s

The style of man pages may be a little hard to get used to, because they are rather terse, particularly the older, very traditional ones. But once you get used to it, you come to appreciate their succinctness. Please note that many Unix-like commands including ones from GNU and BSD display brief help information if you invoke them in one of the following ways (or without any arguments in some cases).
$<omnnm>-hl cmadae -ep $<omnnm>cmadae h

1.5. The simple shell command


Now you have some feel on how to use the Debian system. Let's look deep into the mechanism of the command execution in the Debian system. Here, I have simplified reality for the newbie. See bash(1) for the

exact explanation. A simple command is a sequence of components. 1. Variable assignments (optional) 2. Command name 3. Arguments (optional) 4. Redirections (optional: >, > , <, < , etc.) > < 5. Control operator (optional: & , | , <newline> , ;, &, (, )) & |

1.5.1. Command execution and environment variable


Values of some environment variables change the behavior of some Unix commands. Default values of environment variables are initially set by the PAM system and then some of them may be reset by some application programs. The display manager such as g m resets environment variables. d3 The shell in its start up codes resets environment variables in "~ b s _ r f l " and "~ . a h c /ahpoie / b s r ".

1.5.2. "$ A G variable LN"


The full locale value given to "$ A G variable consists of 3 parts: "x _ Y Z Z ". LN" xY.ZZ Table 1.17. 3 parts of locale value locale value meaning
x x Y Y ZZ ZZ

ISO 639 language codes (lower case) such as "en" ISO 3166 country codes (upper case) such as "US" codeset, always set to "UTF-8"

For language codes and country codes, see pertinent description in the "i f g t e t n o e t x ". For the codeset on the modern Debian system, you should always set it to U F 8unless you specifically want Tto use the historic one with good reason and background knowledge. For fine details of the locale configuration, see Section 8.3, The locale. Note The "L N = n U " is not "L N = " nor "L N = n U . T - ". It is AGe_S AGC AGe_SUF8 "L N = n U . S - 8 9 1 (see Section 8.3.1, Basics of encoding). AGe_SIO85-" Table 1.18. List of locale recommendations

locale recommendation Language (area) e_SUF8 nU.TEnglish(USA)


e_BUF8 nG.Tf_RUF8 rF.Td_EUF8 eD.Ti_TUF8 tI.Te_SUF8 sE.Tc_SUF8 aE.Ts_EUF8 vS.Tp_RUF8 tB.Tr_UUF8 uR.Tz_NUF8 hC.Tz_WUF8 hT.Tj_PUF8 aJ.Tk_RUF8 oK.Tv_NUF8 iV.T-

English(Great_Britain) French(France) German(Germany) Italian(Italy) Spanish(Spain) Catalan(Spain) Swedish(Sweden) Portuguese(Brazil) Russian(Russia) Chinese(P.R._of_China) Chinese(Taiwan_R.O.C.) Japanese(Japan) Korean(Republic_of_Korea) Vietnamese(Vietnam)

Typical command execution uses a shell line sequence as the following.


$dt ae SnJn 31:73 JT20 u u 02:9 S 07 $LN=rF.T- dt AGf_RUF8 ae dmnh 3ji 20,1:73 (T+90 iace un 07 02:3 UC00)

Here, the program date(1) is executed with different values of the environment variable "$ A G L N ". For the first command, "$ A G is set to the system default locale value "e _ S U F 8 LN" n U . T - ". For the second command, "$ A G is set to the French UTF-8 locale value "f _ R U F 8 LN" r F . T - ". Most command executions usually do not have preceding environment variable definition. For the above example, you can alternatively execute as the following.
$LN=rF.TAGf_RUF8 $dt ae dmnh 3ji 20,1:73 (T+90 iace un 07 02:3 UC00)

As you can see here, the output of command is affected by the environment variable to produce French output. If you want the environment variable to be inherited to subprocesses (e.g., when calling shell script), you need to export it instead by the following.
$epr LN xot AG

Tip When filing a bug report, running and checking the command under "L N = n U . T - " is good idea if you use non-English environment. AGe_SUF8

See locale(5) and locale(7) for "$ A G and related environment variables. LN" Note I recommend you to configure the system environment just by the "$ A G variable and LN" to stay away from "$ C * variables unless it is absolutely needed. L_"

1.5.3. "$ A H variable PT"


When you type a command into the shell, the shell searches the command in the list of directories contained in the "$ A H environment variable. The value of the "$ A H environment variable is also called the shell's PT" PT" search path. In the default Debian installation, the "$ A H environment variable of user accounts may not include "/ b n PT" si" and "/ s / b n For example, the i c n i command needs to be issued with full path as u r s i ". fofg "/ b n i c n i ". (Similar i command is located in "/ i ".) si/fofg p bn You can change the "$ A H environment variable of Bash shell by "~ . a h p o i e or "~ . a h c PT" /bs_rfl" /bsr" files.

1.5.4. "$ O E variable HM"


Many commands stores user specific configuration in the home directory and changes their behavior by their contents. The home directory is identified by the environment variable "$ O E H M ". Table 1.19. List of "$ O E values HM" value of "$ O E HM"
/ /ot ro

program execution situation program run by the init process (daemon) program run from the normal root shell menu

/ o e < o m l u e > program run from the normal user shell hm/nra_sr / o e < o m l u e > program run from the normal user GUI desktop hm/nra_sr / o e < o m l u e > program run as root with "s d p o r m hm/nra_sr uo rga" /ot ro

program run as root with "s d - p o r m uo H rga" Tip Shell expands "~ " to current user's home directory, i.e., "$ O E ". Shell expands / HM/ "~ o / to f o home directory, i.e., "/ o e f o ". fo" o 's hm/o/

1.5.5. Command line options


Some commands take arguments. Arguments starting with "- or "- " are called options and control the " behavior of the command.
$dt ae MnOt2 2:20 CT20 o c 7 30:9 E 03 $dt ae R

Mn 2 Ot20 2:24 +10 o, 7 c 03 30:0 00

Here the command-line argument "- " changes date(1) behavior to output RFC2822 compliant date string. R

1.5.6. Shell glob


Often you want a command to work with a group of files without typing all of them. The filename expansion pattern using the shell glob, (sometimes referred as wildcards), facilitate this need. Table 1.20. Shell glob patterns shell glob pattern description of match rule
* . * ? [] [-] az [ ^]

filename (segment) not started with ". " filename (segment) started with ". " exactly one character exactly one character with any character enclosed in brackets exactly one character with any character between "a and "z " " exactly one character other than any character enclosed in brackets (excluding "^ ")

For example, try the following


$mdrjn;c jn;tuh1tt2tt3c4h..x .6tt ki uk d uk oc .x .x . . 5tt ..x $eh *tt co .x 1tt2tt .x .x $eh * co 1tt2tt3c4h .x .x . . $eh *[c co .h] 3c4h . . $eh . co * .. ..x .6tt . 5tt ..x $eh .[.* co *^] ..x .6tt 5tt ..x $eh [13* co ^-] 4h . $c .;r -fjn d . m r uk

See glob(7). Note Unlike normal filename expansion by the shell, the shell pattern "* tested in find(1) with " "- a e test etc., matches the initial ". of the filename. (New POSIX feature) nm" " Note BASH can be tweaked to change its glob behavior with its shopt builtin options such as "d t l b "n g o ", "n c s g o ", "n l g o ", "n c s g o ", "e t l b etc. o g o ", o l b oaelb ullb oaelb x g o ", See bash(1).

1.5.7. Return value of the command


Each command returns its exit status (variable: "$ ") as the return value. ?

Table 1.21. Command exit codes command exit status numeric return value logical return value success error zero, 0 non-zero, -1 TRUE FALSE

For example, try the following.


$[1=1];eh $ co ? 0 $[1=2];eh $ co ? 1

Note Please note that, in the logical context for the shell, success is treated as the logical TRUE which has 0 (zero) as its value. This is somewhat non-intuitive and needs to be reminded here.

1.5.8. Typical command sequences and shell redirection


Let's try to remember following shell command idioms typed in one line as a part of shell command. Table 1.22. Shell command idioms command idiom description
cmad& omn cmad | omn1 cmad omn2

background execution of c m a din the subshell omn pipe the standard output of c m a d to the standard input of c m a d (concurrent omn1 omn2 execution) error of c m a d to the standard input of omn1

c m a d 2 & pipe both standard output and standard omn1 >1 |cmad omn2 c m a d (concurrent execution) omn2 cmad ; omn1 cmad omn2 cmad & omn1 & cmad omn2 cmad | omn1 | cmad omn2 cmad>fo omn o cmad2 omn > fo o cmad> omn > fo o cmad2> omn > fo o cmad>fo omn o 2& >1

execute c m a d and c m a d sequentially omn1 omn2 execute c m a d ; if successful, execute c m a d sequentially (return success if omn1 omn2 both c m a d and c m a d are successful) omn1 omn2 execute c m a d ; if not successful, execute c m a d sequentially (return success if omn1 omn2 c m a d or c m a d are successful) omn1 omn2 redirect standard output of c m a dto a file f o(overwrite) omn o redirect standard error of c m a dto a file f o(overwrite) omn o redirect standard output of c m a dto a file f o(append) omn o redirect standard error of c m a dto a file f o(append) omn o redirect both standard output and standard error of c m a dto a file "f o omn o"

cmad<fo omn o cmad< omn < dlmtr eiie cmad<omn < dlmtr eiie

redirect standard input of c m a dto a file f o omn o redirect standard input of c m a dto the following lines until "d l m t r is met (here omn eiie" document) redirect standard input of c m a dto the following lines until "d l m t r is met (here omn eiie" document, the leading tab characters are stripped from input lines)

The Debian system is a multi-tasking system. Background jobs allow users to run multiple programs in a single shell. The management of the background process involves the shell builtins: j b , f , b , and k l . os g g il Please read sections of bash(1) under "SIGNALS", and "JOB CONTROL", and builtins(1). For example, try the following
$<ecmt pgr /t/od ae $pgr<ecmt ae /t/od $pgr/t/od ae ecmt $ct/t/od|pgr a ecmt ae

Although all 4 examples of shell redirections display the same thing, the last example runs an extra c t a command and wastes resources with no reason. The shell allows you to open files using the e e builtin with an arbitrary file descriptor. xc
$eh Hlo>o co el fo $ee 3fo4br #oe fls xc <o >a pn ie $ct<3>4 a & & #rdrc sdnt 3 sdu t 4 eiet ti o , tot o $ee 3& 4& xc <- >#coefls ls ie $ctbr a a Hlo el

Here, "n & " and "n & " mean to close the file descriptor "n <>". The file descriptor 0-2 are predefined. Table 1.23. Predefined file descriptors device description
sdn ti s d u standard tot s d r standard ter

file descriptor

standard input 0 output 1 error 2

1.5.9. Command alias


You can set an alias for the frequently used command. For example, try the following
$aisl=l -a la a's l'

Now, "l " works as a short hand for "l - a which lists all files in the long listing format. a s l" You can list any existing aliases by a i s(see bash(1) under "SHELL BUILTIN COMMANDS"). la
$ais la .. . aisl=l -a la a's l'

You can identity exact path or identity of the command by t p (see bash(1) under "SHELL BUILTIN ye COMMANDS"). For example, try the following
$tp l ye s l i hse (bnl) s s ahd /i/s $tp l ye a l i aisdt l -a a s lae o s l $tp eh ye co eh i aselbitn co s hl uli $tp fl ye ie fl i /s/i/ie ie s urbnfl

Here l was recently searched while "f l " was not, thus "l " is "hashed", i.e., the shell has an internal s ie s record for the quick access to the location of the "l " command. s Tip See Section 9.2.7, Colorized commands.

1.6. Unix-like text processing


In Unix-like work environment, text processing is done by piping text through chains of standard text processing tools. This was another crucial Unix innovation.

1.6.1. Unix text tools


There are few standard text processing tools which are used very often on the Unix-like system. No regular expression is used: cat(1) concatenates files and outputs the whole content. tac(1) concatenates files and outputs in reverse. cut(1) selects parts of lines and outputs. head(1) outputs the first part of files. tail(1) outputs the last part of files. sort(1) sorts lines of text files. uniq(1) removes duplicate lines from a sorted file.

tr(1) translates or deletes characters. diff(1) compares files line by line. Basic regular expression (BRE) is used: grep(1) matches text with patterns. ed(1) is a primitive line editor. sed(1) is a stream editor. vim(1) is a screen editor. emacs(1) is a screen editor. (somewhat extended BRE) Extended regular expression (ERE) is used: egrep(1) matches text with patterns. awk(1) does simple text processing. tcl(3tcl) can do every conceivable text processing: re_syntax(3). Often used with tk(3tk). perl(1) can do every conceivable text processing. perlre(1). pcregrep(1) from the p r g e package matches text with Perl Compatible Regular cerp Expressions (PCRE) pattern. python(1) with the r module can do every conceivable text processing. See e "/ s / h r / o / y h n h m / n e . t l u r s a e d c p t o / t l i d x h m ". If you are not sure what exactly these commands do, please use "m n c m a d to figure it out by yourself. a omn" Note Sort order and range expression are locale dependent. If you wish to obtain traditional behavior for a command, use C locale instead of UTF-8 ones by prepnding command with "L N = " (see Section 1.5.2, "$ A G variable and Section 8.3, The locale). AGC LN" Note Perl regular expressions (perlre(1)), Perl Compatible Regular Expressions (PCRE), and Python regular expressions offered by the r module have many common extensions to e the normal ERE.

1.6.2. Regular expressions


Regular expressions are used in many text processing tools. They are analogous to the shell globs, but they are more complicated and powerful. The regular expression describes the matching pattern and is made up of text characters and metacharacters.

The metacharacter is just a character with a special meaning. There are 2 major styles, BRE and ERE, depending on the text tools as described above. Table 1.24. Metacharacters for BRE and ERE BRE
\.[]^$* \ \ \ \ \ + ? ( ) {\ \ } | +?() {}| c \ c . ^ $ \ < \ > \ac\ [b] \^b] [ac\ r * r+ \ r? \ r\r 1|2 \r\r\ (1|2) c \ c . ^ $ \ < \ > [b ac] [ac] ^b r * r + r ? r|2 1r (1r) r|2

ERE
\.[] ^$*

description of the regular expression common metacharacters BRE only "\ escaped metacharacters " ERE only non-"\ escaped metacharacters " match non-metacharacter "c " match a literal character "c even if "c is metacharacter by itself " " match any character including newline position at the beginning of a string position at the end of a string position at the beginning of a word position at the end of a word match any characters in "a c " b match any characters except in "a c " b match zero or more regular expressions identified by "r " match one or more regular expressions identified by "r " match zero or one regular expressions identified by "r " match one of the regular expressions identified by "r " or "r " 1 2 match one of the regular expressions identified by "r " or "r " and treat it 1 2 as a bracketed regular expression

The regular expression of e a sis basically BRE but has been extended to treat "+ mc "and "? as the " metacharacters as in ERE. Thus, there are no needs to escape them with "\ in the regular expression of " eas mc. grep(1) can be used to perform the text search using the regular expression. For example, try the following
$erp'N.LCNEYydn'/s/hr/omnlcne/P ge GU*IES|ooye ursaecmo-iessGL GUGNRLPBI LCNE N EEA ULC IES GUGNRLPBI LCNE N EEA ULC IES Yydn,Ic,hrb dslisalcprgtitrs i teporm ooye n. eey icam l oyih neet n h rga

Tip See Section 9.2.7, Colorized commands.

1.6.3. Replacement expressions

For the replacement expression, some characters have special meanings. Table 1.25. The replacement expression replacement expression description of the text to replace the replacement expression
& \ n

what the regular expression matched (use \ in e a s & mc) what the n-th bracketed regular expression matched ("n" being number)

For Perl replacement string, "$ " is used instead of "\ " and "& has no special meaning. n n " For example, try the following
$eh zzaceghj |\ co z1b2f3i4 sd- '/([-]\[-]\.\$==' e e s\1az*)09*(*)/&/ zz1b2f3i4 z=aceghj= $eh zzaceghj |\ co z1b2f3i4 sd- '/([-]\[-]\.\$\==1' e e s\1az*)09*(*)/2=\/ zzf3i4=1b zeghj==ac $eh zzaceghj |\ co z1b2f3i4 pr -e'/1az*[-](*$$==1' el p s([-])09*.)/2=$/ zzf3i4=1b zeghj==ac $eh zzaceghj |\ co z1b2f3i4 pr -e'/1az*[-](*$==' el p s([-])09*.)/&/ zz& z==

Here please pay extra attention to the style of the bracketed regular expression and how the matched strings are used in the text replacement process on different tools. These regular expressions can be used for cursor movements and text replacement actions in some editors too. The back slash "\ at the end of line in the shell commandline escapes newline as a white space character and " continues shell command line input to the next line. Please read all the related manual pages to learn these commands.

1.6.4. Global substitution with regular expressions


The ed(1) command can replace all instances of "F O _ E E " with "T _ E T in "f l ". RMRGX OTX" ie
$e fl <EF d ie <O ,/RMRGXT_ETg sFO_EE/OTX/ w q EF O

The sed(1) command can replace all instances of "F O _ E E " with "T _ E T in "f l ". RMRGX OTX" ie
$sd-e'/RMRGXT_ETg fl e i sFO_EE/OTX/' ie

The vim(1) command can replace all instances of "F O _ E E " with "T _ E T in "f l " by using ex(1) RMRGX OTX" ie commands.

$vm'%/RMRGXT_ETg''w 'q fl i +sFO_EE/OTX/c +' +' ie

Tip The "c flag in the above ensures interactive confirmation for each substitution. " Multiple files ("f l 1 "f l 2 and "f l 3 can be processed with regular expressions similarly with i e ", i e ", i e ") vim(1) or perl(1).
$vm'ago%/RMRGXT_ETg|pae 'q fl1fl2fl3 i +rd sFO_EE/OTX/eudt' +' ie ie ie

Tip The "e flag in the above prevents the "No match" error from breaking a mapping. "
$pr - - - '/RMRGXT_ETg'fl1fl2fl3 el i p e sFO_EE/OTX/; ie ie ie

In the perl(1) example, "- " is for in-place editing, "- " is for implicit loop over files. i p Tip Use of argument "- . a " instead of "- " keeps each original file by adding ". a " to ibk i bk its filename. This makes recovery from errors easier for complex substitutions. Note ed(1) and vim(1) are BRE; perl(1) is ERE.

1.6.5. Extracting data from text file table


Let's consider a text file called "D L in which some pre-2004 Debian project leader's names and their P" initiation days are listed in a space-separated format.
In a Mrok Ags 19 udc uut 93 Bue Prn rc ees Arl 19 pi 96 In a Jcsn Jnay19 ako aur 98 WcetAkra Jnay19 ihr kemn aur 99 Bn e Clis Arl 20 oln pi 01 Bae Gre dl abe Arl 20 pi 02 Mri MclarMrh 20 atn ihmy ac 03

Tip See "A Brief History of Debian" for the latest Debian leadership history. Awk is frequently used to extract data from these types of files. For example, try the following
$ak' pit$ } <P w { rn 3 ' DL Ags uut Arl pi Jnay aur Jnay aur Arl pi Arl pi Mrh ac $ak'$="a" {pit} <P w (1=In) rn ' DL In a Mrok Ags 19 udc uut 93 #mnhsatd ot tre

#DLcle In P ald a

In a Jcsn Jnay19 ako aur 98 $ak'$="ees){pit$,4} <P #We Prn satd w (2=Prn" rn 3$ ' DL hn ees tre Arl19 pi 96

Shells such as Bash can be also used to parse this kind of file. For example, try the following
$wiera frtls mnhya;d hl ed is at ot er o eh $ot co mnh dn <P oe DL ..sm otu a tefrtAkeape . ae upt s h is w xml

Here, the r a builtin command uses characters in "$ F " (internal field separators) to split lines into words. ed IS If you change "$ F " to ": you can parse "/ t / a s d with shell nicely. IS ", ecpsw"
$odF=$F" #sv odvle lIS"IS ae l au $IS'' F=: $wiera ue pswr udgdrs_fln;d hl ed sr asod i i eto_ie o i ["ue"="oo ] te f $sr bz" ; hn eh "ue' I i $i" co $srs D s ud f i dn </t/asd oe ecpsw bz' I i 10 oos D s 00 $IS"odF" #rsoeodvle F=$lIS etr l au

(If Awk is used to do the equivalent, use "F = : " to set the field separator.) S'' IFS is also used by the shell to split results of parameter expansion, command substitution, and arithmetic expansion. These do not occur within double or single quoted words. The default value of IFS is <space>, <tab>, and <newline> combined. Be careful about using this shell IFS tricks. Strange things may happen, when shell interprets some parts of the script as its input.
$IS", F=:" $eh IS$F, IS"IS co F=IS F=$F" IS ,IS: F= F=, $dt ae R St 2 Ag20 0:01 +20 a, 3 u 03 83:5 00 $eh $dt -) co (ae R St 2 Ag20 0 3 3 +20 a 3 u 03 8 0 6 00 $ustIS ne F $eh $dt -) co (ae R St 2 Ag20 0:05 +20 a, 3 u 03 83:0 00 #ue""ad""a IS s : n , s F #eh i aBs bitn co s ah uli #js acmadotu ut omn upt #sbsel->iptt mi sel u hl - nu o an hl #rstISt tedfut ee F o h eal

1.6.6. Script snippets for piping commands


The following scripts do nice things as a part of a pipe. Table 1.26. List of script snippets for piping commands script snippet (type in one line)
fn /s -rn id ur pit

effect of command find all files under "/ s " ur

sq110 e 0 |xrs- 1<omn> ag n cmad |xrs- 1eh ag n co |xrseh ag co |ge - <ee_atr> rp e rgxpten

print 1 to 100 run command repeatedly with each item from pipe as its argument split white-space-separated items from pipe into lines merge all lines from pipe into a line extract lines from pipe containing <regex_pattern> extract third field from pipe separated by ": (passwd file etc.) " extract third field from pipe separated by whitespaces extract third field from pipe separated by tab remove backspace and expand tabs to spaces expand tabs sort and remove duplicates convert uppercase to lowercase concatenate lines into one line remove CR add "# to the start of each line " remove ". x " et print the second line print the first 2 lines print the last 2 lines

| g e - - < e e _ a t r > extract lines from pipe not containing <regex_pattern> rp v e rgxpten |ct-:-3u d f |ak' pit$ } w { rn 3 ' |ak-'t ' pit$ } w F\' { rn 3 ' |cl-x o b |epn xad |sr|ui ot nq |t '-''-' r AZ az |t - 'n r d \' |t - 'r r d \' |sd'// / e s^# ' |sd'/.x/g e s\et/' |sd- - 2 e n e p |ha - 2ed n |ti - 2al n

One-line shell script can loop over many files using find(1) and xargs(1) to perform quite complicated tasks. See Section 10.1.5, Idioms for the selection of files and Section 9.5.9, Repeating a command looping over files. When using the shell interactive mode becomes too complicated, please consider to write a shell script (see Section 12.1, The shell script).

Preface

Chapter 2. Debian package management

Anda mungkin juga menyukai