Linux Fun
Linux Fun
Linux Fun
Paul Cobbaut
Linux Fundamentals
Paul Cobbaut
lt-0.970.452
Abstract
This book is meant to be used in an instructor-led training. For self-study, the intent is to read this book next to a
working Linux computer so you can immediately do every subject, practicing each command.
This book is aimed at novice Linux system administrators (and might be interesting and useful for home users that
want to know a bit more about their Linux system). However, this book is not meant as an introduction to Linux
desktop applications like text editors, browsers, mail clients, multimedia or office applications.
• Serge van Ginderachter: [email protected], docbook xml and pdf build scripts; svn hosting
iii
Linux Fundamentals
iv
Linux Fundamentals
v
Linux Fundamentals
vi
Linux Fundamentals
6.2.7. wc ................................................................................................ 99
6.2.8. sort ............................................................................................. 100
6.2.9. uniq ............................................................................................ 101
6.2.10. comm ....................................................................................... 101
6.2.11. od ............................................................................................. 102
6.2.12. sed ........................................................................................... 102
6.3. some pipeline examples ....................................................................... 103
6.3.1. who | wc .................................................................................... 103
6.3.2. who | cut | sort .......................................................................... 103
6.3.3. grep | cut ................................................................................... 103
6.4. practice : pipes and filters .................................................................... 104
6.5. solution : pipes and filters .................................................................... 105
7. Basic Unix tools ............................................................................................. 107
7.1. common tools ....................................................................................... 107
7.1.1. find ............................................................................................ 107
7.1.2. locate ......................................................................................... 107
7.1.3. date ............................................................................................ 108
7.1.4. cal .............................................................................................. 108
7.1.5. sleep .......................................................................................... 109
7.1.6. time ............................................................................................ 109
7.2. compression tools ................................................................................. 110
7.2.1. gzip - gunzip ............................................................................. 110
7.2.2. zcat - zmore .............................................................................. 110
7.2.3. bzip2 - bunzip2 ......................................................................... 110
7.2.4. bzcat - bzmore .......................................................................... 111
7.3. practice : basic Unix tools ................................................................... 112
7.4. solution : basic Unix tools ................................................................... 113
8. Introduction to vi .......................................................................................... 115
8.1. about vi(m) ........................................................................................... 115
8.2. introduction to using vi(m) .................................................................. 115
8.2.1. command mode and insert mode .............................................. 115
8.2.2. start typing (a A i I o O) ........................................................... 115
8.2.3. replace and delete a character (r x X) ....................................... 116
8.2.4. undo and repeat (u .) ................................................................. 116
8.2.5. cut, copy and paste a line (dd yy p P) ....................................... 116
8.2.6. cut, copy and paste lines (3dd 2yy) .......................................... 117
8.2.7. start and end of a line (0 or ^ and $) ........................................ 117
8.2.8. join two lines (J) and more ....................................................... 117
8.2.9. words (w b) ............................................................................... 118
8.2.10. save (or not) and exit (:w :q :q! ) ............................................ 118
8.2.11. Searching (/ ?) ......................................................................... 119
8.2.12. Replace all ( :1,$ s/foo/bar/g ) ................................................. 119
8.2.13. Reading files (:r :r !cmd) ......................................................... 119
8.2.14. text buffers .............................................................................. 119
8.2.15. multiple files ........................................................................... 120
8.2.16. abbreviations ........................................................................... 120
8.2.17. key mappings .......................................................................... 120
8.2.18. setting options ......................................................................... 120
vii
Linux Fundamentals
viii
Linux Fundamentals
ix
Linux Fundamentals
x
Linux Fundamentals
xi
Linux Fundamentals
xii
List of Tables
1.1. Early Unix Timeline ........................................................................................ 1
1.2. Eighties Unix Timeline .................................................................................... 2
1.3. Current BSD Timeline ..................................................................................... 2
8.1. getting to command mode ........................................................................... 115
8.2. switch to insert mode ................................................................................... 115
8.3. replace and delete ........................................................................................ 116
8.4. undo and repeat ............................................................................................ 116
8.5. cut, copy and paste a line ............................................................................ 116
8.6. cut, copy and paste lines .............................................................................. 117
8.7. start and end of line ..................................................................................... 117
8.8. join two lines ............................................................................................... 117
8.9. words ............................................................................................................ 118
8.10. save and exit vi .......................................................................................... 118
8.11. searching .................................................................................................... 119
8.12. replace ........................................................................................................ 119
8.13. read files and input .................................................................................... 119
8.14. text buffers ................................................................................................. 120
8.15. multiple files .............................................................................................. 120
8.16. abbreviations .............................................................................................. 120
10.1. Debian User Environment .......................................................................... 155
10.2. Red Hat User Environment ........................................................................ 155
12.1. Unix special files ....................................................................................... 162
12.2. standard Unix file permissions .................................................................. 162
12.3. Unix file permissions position ................................................................... 163
12.4. Octal permissions ....................................................................................... 165
xiii
Chapter 1. Introduction to Unix and Linux
4.1BSD
BSD 4.1BSD
SunOS 1.0
UNIX Time Sharing System
Unix
Unix
System III
1
Introduction to Unix and Linux
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
4.3BSD BSD Net/2
4.1BSD
4.3BSD NeXTSTEP
SunOS1.0 SunOS3.2 Solaris
SystemVr4
System V UnixWare
System V AIX
III + V HP-UX
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000-2008
FreeBSD
BSD Net/2 NetBSD
NetBSD OpenBSD
NeXTSTEP Mac OS X
Solaris
2
Introduction to Unix and Linux
1.1.5. Linux
Where GNU/Hurd failed, the Linux kernel succeeded! In 1991 a Finnish student
named Linus Torvalds started writing his own operating system for his intel 80386
computer. In January 1992, Linus decided to release Linux under the GNU GPL.
Thanks to this, thousands of developers are now working on the Linux kernel. Linus
Torvalds is in charge of the kernel developers.
Contrary to popular belief, they are not all volunteers. Today big companies like
Red Hat, Novell, IBM, Intel, SGI, Oracle, Montavista, Google, HP, NetApp, Cisco,
Fujitsu, Broadcom, and others are actively paying developers to work on the Linux
kernel. According to the Linux Foundation "over 3700 individual developers from
over 200 different companies have contributed to the kernel between 2005 and april
2008". 1057 developers from 186 different companies contributed code to make
kernel version 2.6.23 into 2.6.24.
1.2. Licensing
1.2.1. Proprietary
Some flavors of Unix, like HP-UX, IBM AIX, and Sun Solaris 9 are delivered in
binary form after purchase. You are not authorized to install or use these without
paying a licensing fee. You are not authorized to distribute these copies to other
people and you are not authorized to look at or change the closed source code of
the operating system. This software is usually protected by copyright, patents, and
extensive software licensing.
1.2.2. BSD
BSD style licenses are close to the public domain. They essentially state that you
can copy the software, but you have to leave the copyright notice that refers to BSD.
This license gives a lot of freedom but offers few protection to someone copying and
selling your work.
3
Introduction to Unix and Linux
free software translates to vrije software (Dutch) or Logiciel Libre (French) whereas
the free from free beer translates to gratis.
Briefly explained, the GPL allows you to copy software, the GPL allows you to
distribute (sell or give away) that software, and the GPL grants you the right to read
and change the source code. But the person receiving or buying the software from
you has the same rights. And should you decide to distribute modified versions of
GPL software, then you are obligated to put the same license on the modifications
(and provide the source code of your modifications).
1.2.4. Others...
There are many other licenses on software. You should read and understand them
before using any software.
The /etc/redhat-release file contains the Red Hat version on most of the Red Hat and
Red Hat derived systems. Debian and Ubuntu systems contain /etc/debian-version.
Note that Ubuntu was originally derived from Debian.
4
Introduction to Unix and Linux
The /etc/lsb-release file can be found on distributions that follow the Linux Standard
Base. Other variations to these files are /etc/slackware-version, /etc/SuSE-release,
/etc/gentoo-release and /etc/mandrake-release.
Red Hat
Redhat has been a company since 1993. They distribute Red Hat Enterprise
Linux (RHEL) to companies and manage the Fedora project. RHEL is probably
the most popular Linux-based distro on servers. Fedora is a very popular and user
friendly Linux-based distro, aimed towards home users. The company makes a profit
of around one hundred million dollars a year selling support contracts. Red Hat
contributes a lot to the Linux kernel and other free software projects.
Red Hat Linux was distributed from 1994 until 2003. It was one of the oldest common
Linux distributions. Red Hat Linux was the first distro to use the rpm package format.
Many other distros are originally derived from Red Hat Linux. The company Red
Hat, Inc. decided to split Red Hat Linux into Fedora and Red Hat Enterprise
Linux.
Fedora
Fedora is sponsored by Red Hat which is aimed toward home users. There is no
official support from Red Hat. Every six to eight months, there is a new version
of Fedora. Fedora usually has more recent versions of kernel and applications than
RHEL. Fedora 9 was released May 2008.
Since 2005 Red Hat has distributed four different RHEL4 variants. RHEL AS is
for mission-critical computer systems. RHEL ES is for small to mid-range servers.
RHEL WS is for technical power user desktops and critical design. Red Hat Desktop
is for multiple deployments of single user desktops. Red Hat does not give an
5
Introduction to Unix and Linux
explanation for the meaning of AS, ES and WS, but it might be Advanced Server,
Entry-level Server, and Workstation.
Red Hat Enterprise Linux version 5 has been available since March 2007. One of the
notable new features is the inclusion of Xen. Xen is a free virtual machine application
that allows NetBSD and Linux to serve as host for guest operating systems. Besides
virtualization, RHEL 5 also has better SELinux support, clustering, network storage
and smart card integration.
Both CentOS and Oracle's Unbreakable Linux are directly derived from RHEL,
but all references to Red Hat trademarks are removed. Companies are allowed to do
this (GPL), and are hoping to make a profit selling support (without having the cost
of developing and maintaining their own distribution). Red Hat is not really worried
about this since they develop a lot on Linux and thus can offer much better support.
The Oracle offering is still very recent, so let's wait and see how many organizations
will buy a complete solution from Oracle.
Ubuntu
Ubuntu is a rather new distribution, based on Debian, and funded by South African
developer and billionaire astronaut Mark Shuttleworth. Ubuntu is giving away free
(as in beer and speech) CDs with Ubuntu, Linux for Human Beings. Many people
consider Ubuntu to be the most user friendly Linux distribution. The company behind
Ubuntu is Canonical which intends to make a profit of selling support soon. Ubuntu
is probably the most popular Unix-like distribution on personal desktops.
Novell Suse
A couple of years ago, Novell bought the German company Suse. They are seen as
the main competitor to Red Hat with their SLES (Suse Linux Enterprise Server) and
6
Introduction to Unix and Linux
SLED (Suse Linux Enterprise Desktop) versions of Suse Linux. Similar to Fedora,
Novell hosts the OpenSUSE project as a testbed for upcoming SLED and SLES
releases.
Novell has signed a very controversial deal with Microsoft. Some high-profile open
source developers have left the company because of this agreement and many
people from the open source community are actively advocating to abandon Novell
completely.
Debian
Debian is one of the most secure Linux distros. It is known to be stable and reliable.
The Debian people also have a strong focus towards freedom. You will not find
patented technologies or non-free software in the standard Debian repositories. A lot
of distributions (Ubuntu, Knoppix, ...) are derived from the Debian codebase. Debian
has aptitude, which is considered the best package management system.
Mandriva
Mandriva is the unification of the Brazilian distro Conectiva with the French distro
Mandrake. They are considered a user friendly distro with support from the French
government.
FreeBSD
FreeBSD is a complete operating system. The kernel and all of the utilities are held in
the same source code tree. FreeBSD runs on many architectures and is considered to
be reliable and robust. Millions of websites are running on FreeBSD, including some
large ones like yahoo.com, apache.org, sony.co.jp, netcraft, php.net, and freebsd.org.
Apple's MacOSX contains the FreeBSD virtual file system, network stack, and more.
NetBSD
NetBSD development started around the same time (1993) as FreeBSD. NetBSD
aims for maximum portability and thus runs on many architectures. NetBSD is often
used in embedded devices.
OpenBSD
Co-founder Theo De Raadt from NetBSD founded the OpenBSD project in
1994. OpenBSD aims for maximum security. Over the past ten years, only two
7
Introduction to Unix and Linux
vulnerabilities have been found in the default install of OpenBSD. All source code
is thoroughly checked. OpenBSD runs on sixteen different architectures and is
commonly used for firewalls and IDS. The OpenBSD people also bring us OpenSSH.
1.3.5. Solaris
Solaris 10
Solaris 10 is the officially supported Sun distribution. It is a free (as in beer)
download. Sun releases binary patches and updates. Sun would like a community
built around the Solaris kernel, similar to the Linux community. Sun released the
Solaris kernel under the CDDL, a license similar to the GPL, hoping this will happen.
8
Introduction to Unix and Linux
1.4. Certification
LPIC Level 1
This is the junior level certification. You need to pass exams 101 and 102 to
achieve LPIC 1 certification. To pass level one, you will need Linux command
line, user management, backup and restore, installation, networking, and basic system
administration skills.
LPIC Level 2
This is the advanced level certification. You need to be LPIC 1 certified and pass
exams 201 and 202 to achieve LPIC 2 certification. To pass level two, you will need
to be able to administer medium sized Linux networks, including Samba, mail, news,
proxy, firewall, web, and ftp servers.
LPIC Level 3
This is the senior level certification. It contains one core exam (301) which tests
advanced skills mainly about ldap. To achieve this level you also need LPIC Level
2 and pass a specialty exam (302 or 303). Exam 302 mainly focuses on Samba, and
303 on advanced security. More info on http://www.lpi.org.
Ubuntu
When you are LPIC Level 1 certified, you can take a LPI Ubuntu exam (199) and
become Ubuntu certified.
1.4.3. MySQL
There are two tracks for MySQL certification; Certified MySQL 5.0 Developer
(CMDEV) and Certified MySQL 5.0 DBA (CMDBA). The CMDEV is focused
9
Introduction to Unix and Linux
10
Chapter 2. Getting help
11
Getting help
2.1.5. whatis
To see just the description of a manual page, use whatis followed by a string.
2.1.6. whereis
The location of a manpage can be revealed with whereis.
12
Getting help
2.1.10. mandb
Should you be convinced that a man page exists, but you can't access it, then try
running mandb.
root@laika:~# mandb
0 man subdirectories contained newer manual pages.
0 manual pages were added.
0 stray cats were added.
0 old database entries were purged.
2.2.1. Google
Google is a powerful tool to find help about Unix, or anything else. Here are some
tricks.
Search only pages from the .be TLD (or substitute .be for any other Top Level
Domain). You can also use "country:be" to search only pages from Belgium (based
on ip rather than TLD).
13
Getting help
2.2.2. Wikipedia
Wikipedia is a web-based, free-content encyclopedia. Its growth over the past two
years has been astonishing. You have a good chance of finding a clear explanation
by typing your search term behind http://en.wikipedia.org/wiki/ like this example
shows.
2.2.5. Ubuntu
Help for every Ubuntu release is available at https://help.ubuntu.com. Ubuntu also
has video of how to perform tasks on Ubuntu at http://screencasts.ubuntu.com.
2.2.6. www.linux-training.be
This book is available for free in .pdf format. Download it at http://www.linux-
training.be and learn more about Linux fundamentals, system administration,
networking, storage, security and more.
14
Chapter 3. First steps
3.1.1. pwd
The you are here sign can be displayed with the pwd command (Print Working
Directory). Go ahead, try it: Open a command line interface (like gnome-terminal,
konsole, xterm, or a tty) and type pwd. The tool displays your current directory.
paul@laika:~$ pwd
/home/paul
3.1.2. cd
You can change your current directory with the cd command (Change Directory).
paul@laika$ cd /etc
paul@laika$ pwd
/etc
paul@laika$ cd /bin
paul@laika$ pwd
/bin
paul@laika$ cd /home/paul/
paul@laika$ pwd
/home/paul
cd ~
You can pull off a trick with cd. Just typing cd without a target directory, will put
you in your home directory. Typing cd ~ has the same effect.
paul@laika$ cd /etc
paul@laika$ pwd
/etc
paul@laika$ cd
paul@laika$ pwd
/home/paul
paul@laika$ cd ~
paul@laika$ pwd
/home/paul
15
First steps
cd ..
To go to the parent directory (the one just above your current directory in the
directory tree), type cd .. .
paul@laika$ pwd
/usr/share/games
paul@laika$ cd ..
paul@laika$ pwd
/usr/share
paul@laika$ cd ..
paul@laika$ cd ..
paul@laika$ pwd
/
cd -
Another useful shortcut with cd is to just type cd - to go to the previous directory.
paul@laika$ pwd
/home/paul
paul@laika$ cd /etc
paul@laika$ pwd
/etc
paul@laika$ cd -
/home/paul
paul@laika$ cd -
/etc
The screenshot below first shows the current directory (/home/paul). From within this
directory, you have to type cd /home instead of cd home to go to the /home directory.
paul@laika$ pwd
/home/paul
paul@laika$ cd home
bash: cd: home: No such file or directory
paul@laika$ cd /home
paul@laika$ pwd
/home
16
First steps
When inside /home, you have to type cd paul instead of cd /paul to enter the
subdirectory paul of the current directory /home.
paul@laika$ pwd
/home
paul@laika$ cd /paul
bash: cd: /paul: No such file or directory
paul@laika$ cd paul
paul@laika$ pwd
/home/paul
In case your current directory is the root directory, then both cd /home and cd home
will get you in the /home directory.
paul@laika$ cd /
paul@laika$ pwd
/
paul@laika$ cd home
paul@laika$ pwd
/home
paul@laika$ cd /
paul@laika$ pwd
/
paul@laika$ cd /home
paul@laika$ pwd
/home
This was the last screenshot with pwd statements. From now on, the current directory
will often be displayed in the prompt. Later in this book we will explain how the shell
variable $PS1 can be configured to show this.
You will need fewer key strokes when using the tab key, and you will be sure your
typed path is correct!
3.1.5. ls
You can list the contents of a directory with ls.
paul@pasha:~$ ls
allfiles.txt dmesg.txt httpd.conf stuff summer.txt
paul@pasha:~$
17
First steps
ls -a
A frequently used option with ls is -a to show all files. Showing all files means
including the hidden files. When a filename on a Unix file system starts with a dot,
it is considered a hidden file and it doesn't show up in regular file listings.
paul@pasha:~$ ls
allfiles.txt dmesg.txt httpd.conf stuff summer.txt
paul@pasha:~$ ls -a
. allfiles.txt .bash_profile dmesg.txt .lesshst stuff
.. .bash_history .bashrc httpd.conf .ssh summer.txt
paul@pasha:~$
ls -l
Many times you will be using options with ls to display the contents of the directory
in different formats or to display different parts of the directory. Typing just ls gives
you a list of files in the directory. Typing ls -l (that is a letter L, not the number 1)
gives you a long listing (more information on the contents).
paul@pasha:~$ ls -l
total 23992
-rw-r--r-- 1 paul paul 24506857 2006-03-30 22:53 allfiles.txt
-rw-r--r-- 1 paul paul 14744 2006-09-27 11:45 dmesg.txt
-rw-r--r-- 1 paul paul 8189 2006-03-31 14:01 httpd.conf
drwxr-xr-x 2 paul paul 4096 2007-01-08 12:22 stuff
-rw-r--r-- 1 paul paul 0 2006-03-30 22:45 summer.txt
ls -lh
Another frequently used ls option is -h. It shows the numbers (file sizes) in a more
human readable format. Also shown below is some variation in the way you can give
the options to ls. We will explain the details of the output later in this book.
paul@pasha:~$ ls -l -h
total 24M
-rw-r--r-- 1 paul paul 24M 2006-03-30 22:53 allfiles.txt
-rw-r--r-- 1 paul paul 15K 2006-09-27 11:45 dmesg.txt
-rw-r--r-- 1 paul paul 8.0K 2006-03-31 14:01 httpd.conf
drwxr-xr-x 2 paul paul 4.0K 2007-01-08 12:22 stuff
-rw-r--r-- 1 paul paul 0 2006-03-30 22:45 summer.txt
paul@pasha:~$ ls -lh
total 24M
-rw-r--r-- 1 paul paul 24M 2006-03-30 22:53 allfiles.txt
-rw-r--r-- 1 paul paul 15K 2006-09-27 11:45 dmesg.txt
-rw-r--r-- 1 paul paul 8.0K 2006-03-31 14:01 httpd.conf
drwxr-xr-x 2 paul paul 4.0K 2007-01-08 12:22 stuff
-rw-r--r-- 1 paul paul 0 2006-03-30 22:45 summer.txt
paul@pasha:~$ ls -hl
total 24M
-rw-r--r-- 1 paul paul 24M 2006-03-30 22:53 allfiles.txt
-rw-r--r-- 1 paul paul 15K 2006-09-27 11:45 dmesg.txt
18
First steps
3.1.6. mkdir
Walking around the Unix file tree is fun, but it is even more fun to create your own
directories with mkdir. You have to give at least one parameter to mkdir, the name
of the new directory to be created. Think before you type a leading / .
mkdir -p
When given the option -p, then mkdir will create parent directories as needed.
3.1.7. rmdir
When a directory is empty, you can use rmdir to remove the directory.
19
First steps
rmdir -p
And similar to the mkdir -p option, you can also use rmdir to recursively remove
directories.
20
First steps
3. Now change to your home directory using only three key presses.
10. Stay where you are, and list the contents of /bin and /sbin.
12. List all the files (including hidden files) in your home directory.
15. Change to the /etc directory, stay here and create a directory newdir in your home
directory.
18. If time permits (or if you are waiting for other students to finish this practice),
use and understand pushd and popd. Use the man page of bash to find information
about pushd, popd and dirs.
21
First steps
3. Now change to your home directory using only three key presses.
cd (and the enter key)
10. Stay where you are, and list the contents of /bin and /sbin.
ls /bin /sbin
12. List all the files (including hidden files) in your home directory.
ls -al ~
15. Change to the /etc directory, stay here and create a directory newdir in your home
directory.
22
First steps
18. If time permits (or if you are waiting for other students to finish this practice),
use and understand pushd and popd. Use the man page of bash to find information
about pushd, popd and dirs.
man bash
The Bash shell has two built-in commands called pushd and popd. Both commands
work with a common stack of previous directories. Pushd adds a directory to the stack
and changes to a new current directory, popd removes a directory from the stack and
sets the current directory.
paul@laika:/etc$ cd /bin
paul@laika:/bin$ pushd /lib
/lib /bin
paul@laika:/lib$ pushd /proc
/proc /lib /bin
paul@laika:/proc$
paul@laika:/proc$ popd
/lib /bin
paul@laika:/lib$
paul@laika:/lib$
paul@laika:/lib$ popd
/bin
paul@laika:/bin$
23
First steps
3.4.1. file
The file utility determines the file type. Linux does not use extensions to determine
the file type. Your editor does not care whether a file ends in .TXT or .DOC. As a
system administrator, you should use the file command to determine the file type.
Here are some examples on a typical Linux system.
Here's another example of the file utility. It shows different type of binaries on
different architectures.
# Solaris 9 on Intel
bash-2.05$ file /bin/date
/bin/date: ELF 32-bit LSB executable 80386 Version 1, dynamically \
linked, stripped
The file command uses a magic file that contains patterns to recognize filetypes.
The magic file is located in /usr/share/file/magic. Type man 5 magic for more
information.
3.4.2. touch
One easy way to create a file is with touch. (We will see many other ways for creating
files later in this book.)
24
First steps
touch -t
Of course, touch can do more than just create files. Can you determine what by
looking at the next screenshot? If not, check the manual for touch.
3.4.3. rm
When you no longer need a file, use rm to remove it. Unlike some graphical user
interfaces, the command line in general does not have a waste bin or trashcan to
recover files. When you use rm to remove a file, the file is gone. Therefore, be careful
when removing files!
paul@laika:~/test$ ls
BigBattle SinkoDeMayo
paul@laika:~/test$ rm BigBattle
paul@laika:~/test$ ls
SinkoDeMayo
rm -i
To prevent yourself from accidentally removing a file, you can type rm -i.
rm -rf
By default, rm will not remove non-empty directories. However rm accepts several
options that will allow you to remove any directory. The rm -rf statement is famous
because it will erase anything (providing that you have the permissions to do so).
When you are logged on as root, be very careful with rm -rf (the f means force and
the r means recursive) since being root implies that permissions don't apply to you,
so you can literally erase your entire file system by accident.
25
First steps
paul@laika:~$ ls test
SinkoDeMayo
paul@laika:~$ rm test
rm: cannot remove `test': Is a directory
paul@laika:~$ rm -rf test
paul@laika:~$ ls test
ls: test: No such file or directory
3.4.4. cp
To copy a file, use cp with a source and a target argument. If the target is a directory,
then the source files are copied to that target directory.
cp -r
To copy complete directories, use cp -r (the -r option forces recursive copying of
all files in all subdirectories).
paul@laika:~/test$ ls
FileA FileB MyDir
paul@laika:~/test$ ls MyDir/
FileA
paul@laika:~/test$ cp -r MyDir MyDirB
paul@laika:~/test$ ls
FileA FileB MyDir MyDirB
paul@laika:~/test$ ls MyDirB
FileA
cp -i
To prevent cp from overwriting existing files, use the -i (for interactive) option.
26
First steps
cp -p
To preserve permissions and time stamps from source files, use cp -p.
paul@laika:~/perms$ cp file* cp
paul@laika:~/perms$ cp -p file* cpp
paul@laika:~/perms$ ll *
-rwx------ 1 paul paul 0 2008-08-25 13:26 file33
-rwxr-x--- 1 paul paul 0 2008-08-25 13:26 file42
cp:
total 0
-rwx------ 1 paul paul 0 2008-08-25 13:34 file33
-rwxr-x--- 1 paul paul 0 2008-08-25 13:34 file42
cpp:
total 0
-rwx------ 1 paul paul 0 2008-08-25 13:26 file33
-rwxr-x--- 1 paul paul 0 2008-08-25 13:26 file42
3.4.5. mv
Use mv to rename a file or to move the file to another directory.
When you need to rename only one file then mv is the preferred command to use.
3.4.6. rename
The rename command can also be used but it has a more complex syntax to enable
renaming of many files at once. Below are two examples, the first switches all
occurrences of txt to png for all filenames ending in .txt. The second example switches
all occurrences of uppercase ABC in lowercase abc for all filenames ending in .png .
The following syntax will work on debian and ubuntu (prior to Ubuntu 7.10).
paul@laika:~/test$ ls
123.txt ABC.txt
27
First steps
On Red Hat Enterprise Linux (and many other Linux distributions like Ubuntu 8.04),
the syntax of rename is a bit different. The first example below renames all *.conf
files replacing any occurrence of conf with bak. The second example renames all (*)
files replacing one with ONE.
[paul@RHEL4a test]$ ls
one.conf two.conf
[paul@RHEL4a test]$ rename conf bak *.conf
[paul@RHEL4a test]$ ls
one.bak two.bak
[paul@RHEL4a test]$ rename one ONE *
[paul@RHEL4a test]$ ls
ONE.bak two.bak
[paul@RHEL4a test]$
28
First steps
9. Create a directory called ~/testbackup and copy all files from ~/touched in it.
10. Use one command to remove the directory ~/testbackup and all files in it.
11. Create a directory ~/etcbackup and copy all *.conf files from /etc in it. Did you
include all subdirectories of /etc ?
12. Use rename to rename all *.conf files to *.backup . (if you have more than one
distro available, try it on all!)
29
First steps
wget http://www.linux-training.be/studentfiles/book.pdf
9. Create a directory called ~/testbackup and copy all files from ~/touched in it.
mkdir ~/testbackup ; cp -r ~/touched ~/testbackup/
10. Use one command to remove the directory ~/testbackup and all files in it.
rm -rf ~/testbackup
11. Create a directory ~/etcbackup and copy all *.conf files from /etc in it. Did you
include all subdirectories of /etc ?
30
First steps
cp -r /etc/*.conf ~/etcbackup
12. Use rename to rename all *.conf files to *.backup . (if you have more than one
distro available, try it on all!)
On RHEL: touch 1.conf 2.conf ; rename conf backup *.conf
31
First steps
3.7.1. head
You can use head to display the first ten lines of a file.
The head command can also display the first n lines of a file.
3.7.2. tail
Similar to head, the tail command will display the last ten lines of a file.
# Local services
paul@laika:~$
The tail command has other useful options, some of which we will use some of them
during this course.
32
First steps
3.7.3. cat
The cat command is one of the most universal tools. All it does is copy standard
input to standard output. In combination with the shell this can be very powerful and
diverse. Some examples will give a glimpse into the possibilities. The first example
is simple, you can use cat to display a file on the screen. If the file is longer than the
screen, it will scroll to the end.
concatenate
cat is short for concatenate. One of the basic uses of cat is to concatenate files into
a bigger (or complete) file.
create files
You can use cat to create files with one or more lines of text. Type the command as
shown in the screenshot below. Then type one or more lines, finishing each line with
the enter key. After the last line, type and hold the Control (Ctrl) key and press d.
The Ctrl d key combination will send an EOF (End of File) to the running process
ending the cat command.
You can choose this end marker for cat with << as is shown in this screenshot.
33
First steps
paul@laika:~/test$
copy files
In the third example you will see that cat can be used to copy files. We will explain
in detail what happens here in the bash shell chapter.
3.7.4. tac
Just one example will show you the purpose of tac (as the opposite of cat).
3.7.6. strings
With the strings command you can display readable ascii strings found in (binary)
files. This example locates the ls binary then displays readable strings in the binary
file (output is truncated).
paul@laika:~$ which ls
/bin/ls
paul@laika:~$ strings /bin/ls
/lib/ld-linux.so.2
librt.so.1
34
First steps
__gmon_start__
_Jv_RegisterClasses
clock_gettime
libacl.so.1
...
35
First steps
3. Use cat to create a file named count.txt that looks like this:
One
Two
Three
Four
Five
6. Display catcnt.txt, but with all lines in reverse order (the last line first).
36
First steps
3. Use cat to create a file named count.txt that looks like this:
One
Two
Three
Four
Five
6. Display catcnt.txt, but with all lines in reverse order (the last line first).
tac catcnt.txt
37
Chapter 4. The Linux file system tree
This screenshot shows the difference between two files, one with uppercase W, the
other with lowercase w.
paul@laika:~/Linux$ ls
winter.txt Winter.txt
paul@laika:~/Linux$ cat winter.txt
It is cold.
paul@laika:~/Linux$ cat Winter.txt
It is very cold!
[paul@RHELv4u3 ~]$ ls /
bin dev home media mnt proc sbin srv tftpboot usr
boot etc lib misc opt root selinux sys tmp var
[paul@RHELv4u3 ~]$
38
The Linux file system tree
paul@laika:~$ ls /bin
archdetect egrep mt setupcon
autopartition false mt-gnu sh
bash fgconsole mv sh.distrib
bunzip2 fgrep nano sleep
bzcat fuser nc stralign
bzcmp fusermount nc.traditional stty
bzdiff get_mountoptions netcat su
bzegrep grep netstat sync
bzexe gunzip ntfs-3g sysfs
bzfgrep gzexe ntfs-3g.probe tailf
bzgrep gzip parted_devices tar
bzip2 hostname parted_server tempfile
bzip2recover hw-detect partman touch
bzless ip partman-commit true
bzmore kbd_mode perform_recipe ulockmgr
cat kill pidof umount
...
39
The Linux file system tree
#
# SATA or SCSI
#
paul@laika:~$ ls /dev/sd*
/dev/sda /dev/sda1 /dev/sda2 /dev/sda3 /dev/sdb /dev/sdb1 /dev/sdb2
#
# IDE or ATAPI
#
paul@barry:~$ ls /dev/hd*
/dev/hda /dev/hda1 /dev/hda2 /dev/hdb /dev/hdb1 /dev/hdb2 /dev/hdc
Besides representing physical hardware, some device files are special. These special
devices can be very useful.
/dev/null
On Linux you will find other special devices such as /dev/null which can be
considered a black hole; it has unlimited storage, but nothing can be retrieved from
it. Technically speaking, anything written to /dev/null will be discarded. /dev/null
can be useful to discard unwanted output from commands. /dev/null is not a good
location to store your backups ;-).
40
The Linux file system tree
paul@laika:~$ ls /etc/*.conf
/etc/adduser.conf /etc/ld.so.conf /etc/scrollkeeper.conf
/etc/brltty.conf /etc/lftp.conf /etc/sysctl.conf
/etc/ccertificates.conf /etc/libao.conf /etc/syslog.conf
/etc/cvs-cron.conf /etc/logrotate.conf /etc/ucf.conf
/etc/ddclient.conf /etc/ltrace.conf /etc/uniconf.conf
/etc/debconf.conf /etc/mke2fs.conf /etc/updatedb.conf
/etc/deluser.conf /etc/netscsid.conf /etc/usplash.conf
/etc/fdmount.conf /etc/nsswitch.conf /etc/uswsusp.conf
/etc/hdparm.conf /etc/pam.conf /etc/vnc.conf
/etc/host.conf /etc/pnm2ppa.conf /etc/wodim.conf
/etc/inetd.conf /etc/povray.conf /etc/wvdial.conf
/etc/kernel-img.conf /etc/resolv.conf
paul@laika:~$
/etc/X11/
The graphical display (aka X Window System or just X) is driven by software from
the X.org foundation. The configuration file for your graphical display is /etc/X11/
xorg.conf.
/etc/skel/
The skeleton directory /etc/skel is copied to the home directory of a newly created
user. It usually contains hidden files like a .bashrc script.
/etc/sysconfig/
This directory, which is not mentioned in the FHS, contains a lot of Red Hat
Enterprise Linux configuration files. We will discuss some of them in greater
detail. The screenshot below is the /etc/sysconfig directory from RHELv4u4 with
everything installed.
paul@RHELv4u4:~$ ls /etc/sysconfig/
apmd firstboot irda network saslauthd
apm-scripts grub irqbalance networking selinux
authconfig hidd keyboard ntpd spamassassin
autofs httpd kudzu openib.conf squid
bluetooth hwconf lm_sensors pand syslog
clock i18n mouse pcmcia sys-config-sec
console init mouse.B pgsql sys-config-users
crond installinfo named prelink sys-logviewer
desktop ipmi netdump rawdevices tux
diskdump iptables netdump_id_dsa rhn vncservers
dund iptables-cfg netdump_id_dsa.p samba xinetd
paul@RHELv4u4:~$
The file /etc/sysconfig/firstboot tells the Red Hat Setup Agent not to run at boot time.
If you want to run the Red Hat Setup Agent at the next reboot, then simply remove
this file, and run chkconfig --level 5 firstboot on. The Red Hat Setup Agent allows
41
The Linux file system tree
you to install the latest updates, create a user account, join the Red Hat Network and
more. It will then create the /etc/sysconfig/firstboot file again.
The /etc/sysconfig/harddisks file contains some parameters to tune the hard disks.
The file explains itself.
The keyboard type and keymap table are set in the /etc/sysconfig/keyboard file.
For more console keyboard information, check the manual pages of keymaps(5),
dumpkeys(1), loadkeys(1) and the directory /lib/kbd/keymaps/.
paul@pasha:~$ ls /home
geert guillaume maria paul tom
Besides giving every user (or every project or group) a location to store personal
files, the home directory of a user also serves as a location to store the user profile. A
typical Unix user profile contains many hidden files (files whose filename starts with
a dot). The hidden files of the Unix user profiles contain settings specific for that user.
paul@pasha:~$ ls -d /home/paul/.*
/home/paul/. /home/paul/.bash_profile /home/paul/.ssh
/home/paul/.. /home/paul/.bashrc /home/paul/.viminfo
/home/paul/.bash_history /home/paul/.lesshst /home/paul/.Xauthority
4.6.6. /initrd
This empty directory is used as a mount point by Red Hat Enterprise Linux during
boot time. Do not remove this directory, doing so causes a kernel panic during the
next boot.
42
The Linux file system tree
paul@laika:~$ ls /lib/libc*
/lib/libc-2.5.so /lib/libcfont.so.0.0.0 /lib/libcom_err.so.2.1
/lib/libcap.so.1 /lib/libcidn-2.5.so /lib/libconsole.so.0
/lib/libcap.so.1.10 /lib/libcidn.so.1 /lib/libconsole.so.0.0.0
/lib/libcfont.so.0 /lib/libcom_err.so.2 /lib/libcrypt-2.5.so
/lib/modules
We currently are in a transition between 32-bit and 64-bit systems. Therefore, you
may encounter directories named /lib32 and /lib64 which clarify the register size used
during compilation time of the libraries. My current 64-bit laptop has some older 32-
bit binaries and libraries for compatibility with legacy applications. This screenshot
uses the file utility to demonstrate the difference.
The ELF (Executable and Linkable Format) is used in almost every Unix-like
operating system since System V.
paul@laika:~$ ls /media/
cdrom cdrom0 usbdisk
43
The Linux file system tree
When listing the /proc directory, you will see many numbers (on any Unix), and some
interesting files (on Linux)
mul@laika:~$ ls /proc
1 2339 4724 5418 6587 7201 cmdline mounts
10175 2523 4729 5421 6596 7204 cpuinfo mtrr
10211 2783 4741 5658 6599 7206 crypto net
10239 2975 4873 5661 6638 7214 devices pagetypeinfo
141 29775 4874 5665 6652 7216 diskstats partitions
15045 29792 4878 5927 6719 7218 dma sched_debug
1519 2997 4879 6 6736 7223 driver scsi
1548 3 4881 6032 6737 7224 execdomains self
1551 30228 4882 6033 6755 7227 fb slabinfo
1554 3069 5 6145 6762 7260 filesystems stat
1557 31422 5073 6298 6774 7267 fs swaps
1606 3149 5147 6414 6816 7275 ide sys
180 31507 5203 6418 6991 7282 interrupts sysrq-trigger
181 3189 5206 6419 6993 7298 iomem sysvipc
182 3193 5228 6420 6996 7319 ioports timer_list
18898 3246 5272 6421 7157 7330 irq timer_stats
19799 3248 5291 6422 7163 7345 kallsyms tty
19803 3253 5294 6423 7164 7513 kcore uptime
19804 3372 5356 6424 7171 7525 key-users version
1987 4 5370 6425 7175 7529 kmsg version_signature
1989 42 5379 6426 7188 9964 loadavg vmcore
44
The Linux file system tree
Let's investigate the file properties inside /proc. Looking at the date and time will
display the current date and time showing the files are constantly updated (a view
on the kernel).
paul@RHELv4u4:~$ date
Mon Jan 29 18:06:32 EST 2007
paul@RHELv4u4:~$ ls -al /proc/cpuinfo
-r--r--r-- 1 root root 0 Jan 29 18:06 /proc/cpuinfo
paul@RHELv4u4:~$
paul@RHELv4u4:~$ ...time passes...
paul@RHELv4u4:~$
paul@RHELv4u4:~$ date
Mon Jan 29 18:10:00 EST 2007
paul@RHELv4u4:~$ ls -al /proc/cpuinfo
-r--r--r-- 1 root root 0 Jan 29 18:10 /proc/cpuinfo
Most files in /proc are 0 bytes, yet they contain data--sometimes a lot of data. You
can see this by executing cat on files like /proc/cpuinfo, which contains information
about the CPU.
45
The Linux file system tree
ncpus active : 2
Cpu0Bogo : 498.68
Cpu0ClkTck : 000000002cb41780
Cpu1Bogo : 498.68
Cpu1ClkTck : 000000002cb41780
MMU Type : Cheetah
State:
CPU0: online
CPU1: online
processor : 1
cpu : Cell Broadband Engine, altivec supported
clock : 3192.000000MHz
revision : 5.1 (pvr 0070 0501)
timebase : 79800000
platform : PS3
machine : PS3
Most of the files in /proc are read only, some require root privileges, some files are
writable, and many files in /proc/sys are writable. Let's discuss some of the files in /
proc.
/proc/filesystems
The /proc/filesystems file displays a list of supported file systems. When you mount
a file system without explicitly defining one, then mount will first try to probe /
etc/filesystems and then probe /proc/filesystems for all the filesystems without the
nodev label. If /etc/filesystems ends with a line containing only an asterisk (*) then
both files are probed.
46
The Linux file system tree
nodev devpts
ext2
nodev ramfs
nodev hugetlbfs
iso9660
nodev relayfs
nodev mqueue
nodev selinuxfs
ext3
nodev rpc_pipefs
nodev vmware-hgfs
nodev autofs
paul@RHELv4u4:~$
/proc/interrupts
On the x86 architecture, /proc/interrupts displays the interrupts.
47
The Linux file system tree
/proc/kcore
The physical memory is represented in /proc/kcore. Do not try to cat this file, instead
use a debugger. The size of /proc/kcore is the same as your physical memory, plus
four bytes.
/proc/swaps
You can find information about swap partition(s) in /proc/swaps.
paul@RHELv4u4:~$ cat /proc/swaps
Filename Type Size Used Priority
/dev/mapper/VolGroup00-LogVol01 partition 1048568 0 -1
paul@RHELv4u4:~$
paul@RHELv4u4:~$ ls /sys/*
/sys/block:
48
The Linux file system tree
dm-0 fd0 hdb md0 ram1 ram11 ram13 ram15 ram3 ram5 ram7 ram9
dm-1 hda hdc ram0 ram10 ram12 ram14 ram2 ram4 ram6 ram8 sda
/sys/bus:
i2c ide pci platform pnp scsi serio usb
/sys/class:
firmware i2c-adapter input misc netlink printer scsi_device tty
graphics i2c-dev mem net pci_bus raw scsi_host usb
/sys/devices:
pci0000:00 platform system
/sys/firmware:
acpi
/sys/module:
ac dm_mirror ext3 ip_conntrack ipt_state md5
autofs4 dm_mod floppy iptable_filter ipv6 mii
battery dm_snapshot i2c_core ip_tables jbd mptbase
button dm_zero i2c_dev ipt_REJECT lp mptfc
/sys/power:
state
paul@RHELv4u4:~$
/var/lib/rpm
Red Hat Enterprise Linux keeps files pertaining to RPM in /var/lib/rpm/.
49
The Linux file system tree
/var/spool/up2date
The Red Hat Update Agent uses files in /var/spool/up2date. This location is also
used when files are downloaded from the Red Hat Network.
50
The Linux file system tree
od zeroes.txt
dd will copy one times (count=1) a block of size 100 bytes (bs=100) from the file /
dev/zero to ~/test/zeroes.txt. Can you describe the functionality of /dev/zero ?
dd will copy one times (count=1) a block of size 100 bytes (bs=100) from the file /
dev/random to ~/test/random.txt. Can you describe the functionality of /dev/random ?
5. Issue the following two commands, and look at the first character of each output
line.
ls -l /dev/sd* /dev/hd*
ls -l /dev/tty* /dev/input/mou*
The first ls will show block(b) devices, the second ls shows character(c) devices. Can
you tell the difference between block and character devices ?
6. Use cat to display /etc/hosts and /etc/resolv.conf. What is your idea about the
purpose of these files ?
7. Are there any files in /etc/skel/ ? Check also for hidden files.
9. Display /proc/interrupts. What is the size of this file ? Where is this file stored ?
10. Can you enter the /root directory ? Are there (hidden) files ?
11. Are ifconfig, fdisk, parted, shutdown and grub-install present in /sbin ? Why are
these binaries in /sbin and not in /bin ?
51
The Linux file system tree
14. Read the man page of random and explain the difference between /dev/random
and /dev/urandom.
52
The Linux file system tree
od zeroes.txt
dd will copy one times (count=1) a block of size 100 bytes (bs=100) from the file /
dev/zero to ~/test/zeroes.txt. Can you describe the functionality of /dev/zero ?
dd will copy one times (count=1) a block of size 100 bytes (bs=100) from the file /
dev/random to ~/test/random.txt. Can you describe the functionality of /dev/random ?
5. Issue the following two commands, and look at the first character of each output
line.
ls -l /dev/sd* /dev/hd*
ls -l /dev/tty* /dev/input/mou*
The first ls will show block(b) devices, the second ls shows character(c) devices. Can
you tell the difference between block and character devices ?
Block devices are always written to (or read from) in blocks. For hard disks, blocks
of 512 bytes are common. Character devices act as a stream of characters (or bytes).
Mouse and keyboard are typical character devices.
6. Use cat to display /etc/hosts and /etc/resolv.conf. What is your idea about the
purpose of these files ?
/etc/hosts contains hostnames with their ip address
53
The Linux file system tree
7. Are there any files in /etc/skel/ ? Check also for hidden files.
Issue "ls -al /etc/skel/". Yes, there should be hidden files there.
9. Display /proc/interrupts. What is the size of this file ? Where is this file stored ?
The size is zero, yet the file contains data. It is not stored anywhere because /proc is
a virtual file system that allows you to talk with the kernel. (If you answered "stored
in RAM-memory, that is also correct...).
10. Can you enter the /root directory ? Are there (hidden) files ?
Try "cd /root". Yes there are (hidden) files there.
11. Are ifconfig, fdisk, parted, shutdown and grub-install present in /sbin ? Why are
these binaries in /sbin and not in /bin ?
Because those files are only meant for system administrators.
14. Read the man page of random and explain the difference between /dev/random
and /dev/urandom.
man 4 random
54
Chapter 5. Introduction to the shell
This chapter will explain general features of a shell mainly using the /bin/bash shell.
Important differences in /bin/ksh will be mentioned separately.
5.1.3. type
To find out whether a command given to the shell will be executed as an external
command or as a built-in command, use the type command.
paul@laika:~$ type cd
cd is a shell builtin
paul@laika:~$ type cat
cat is /bin/cat
You can also use this command to show you whether the command is aliased or not.
paul@laika:~$ type ls
ls is aliased to `ls --color=auto'
55
Introduction to the shell
5.1.5. which
The which command will search for binaries in the PATH environment variable.
(Variables will be explained later.) In the screenshot below, it is determined that cd
is built-in, and ls, cp, rm, mv, mkdir, pwd, and which are external commands.
5.1.6. alias
create an alias
The shell allows you to create aliases. Aliases are often used to create an easier to
remember name for an existing command or to easily supply parameters.
abbreviate commands
An alias can also be useful to abbreviate an existing command.
56
Introduction to the shell
default options
Aliases can be used to supply commands with default options. The example below
shows how to set the -i option default when typing rm.
Some distributions enable default aliases to protect users from accidentally erasing
files ('rm -i', 'mv -i', 'cp -i')
viewing aliases
You can provide one or more aliases as arguments to the alias command to get their
definitions. Providing no arguments gives a complete list of current aliases.
paul@laika:~$ alias c ll
alias c='clear'
alias ll='ls -lh --color=auto'
unalias
You can undo an alias with the unalias command.
5.1.7. echo
This book frequently uses the echo command to demonstrate shell features. The echo
command echoes the input that it receives.
57
Introduction to the shell
One of the primary features of a shell is to perform a command line scan. When
you enter a command at the shell's command prompt and press the enter key, then
the shell will start scanning that line. While scanning the line, the shell may make
many changes to the command line you typed. This process is called shell expansion.
After the shell has finished scanning and modifying that line, it will be executed.
Shell expansion is influenced by the following topics: control operators, white space
removal, filename generation, variables, escaping, embedding, and shell aliases. All
of these topics are discussed in the next sections.
58
Introduction to the shell
3. Read the man page of rm, make sure you understand the -i option of rm. Create
and remove a file to test the -i option.
4. Execute: alias rm='rm -i' . Test your alias with a test file. Does this work as
expected ?
12. What is the location of the cat and the passwd commands ?
/bin/echo
echo -n Hello
59
Introduction to the shell
3. Read the man page of rm, make sure you understand the -i option of rm. Create
and remove a file to test the -i option.
man rm
touch testfile
rm -i testfile
4. Execute: alias rm='rm -i' . Test your alias with a test file. Does this work as
expected ?
touch testfile
paul@deb503:~$ set -x
paul@deb503:~$ city
+ echo antwerp
antwerp
12. What is the location of the cat and the passwd commands ?
60
Introduction to the shell
/bin/echo
The echo command will be interpreted by the shell as the built-in echo command.
The /bin/echo command will make the shell execute the echo binary located in the
/bin directory.
echo -n Hello
The -n option of the echo command will prevent echo from echoing a trailing newline.
echo Hello will echo six characters in total, echo -n hello only echoes five characters.
61
Introduction to the shell
5.4.1. ; semicolon
You can put two or more commands on the same line separated by a semicolon ; .
The shell will scan the line until it reaches the semicolon. All the arguments before
this semicolon will be considered a separate command from all the arguments after
the semicolon. Both series will be executed sequentially with the shell waiting for
each command to finish before starting the next one.
The technical explanation of what happens in this case is explained in the chapter
about processes.
62
Introduction to the shell
Another example of the same logical AND principle. This example starts with a
working cd followed by ls, then a non-working cd which is not followed by ls.
63
Introduction to the shell
64
Introduction to the shell
8. Use echo to display "Hello World with strange' characters \ * [ } ~ \\ ." (including
all quotes)
10. Echo it worked when touch test42 works, and echo it failed when the touch
failed. All on one command line as a normal user (not root). Test this line in your
home directory and in /bin/ .
65
Introduction to the shell
8. Use echo to display "Hello World with strange' characters \ * [ } ~ \\ ." (including
all quotes)
echo \"Hello World with strange\' characters \\ \* \[ \} \~ \\\\ \. \"
or
10. Echo it worked when touch test42 works, and echo it failed when the touch
failed. All on one command line as a normal user (not root). Test this line in your
home directory and in /bin/ .
paul@deb503:~$ cd ; touch test42 && echo it worked || echo it failed
it worked
paul@deb503:~$ cd /bin; touch test42 && echo it worked || echo it failed
touch: cannot touch `test42': Permission denied
it failed
66
Introduction to the shell
These are some examples using $HOSTNAME, $USER, $UID, $SHELL, and
$HOME.
5.7.3. $PS1
The $PS1 variable determines your shell prompt. You can use backslash escaped
special characters like \u for the username or \w for the working directory. The bash
manual has a complete reference.
paul@deb503:~$ PS1=prompt
prompt
promptPS1='prompt '
prompt
prompt PS1='> '
>
> PS1='\u@\h$ '
paul@deb503$
paul@deb503$ PS1='\u@\h:\W$'
paul@deb503:~$
67
Introduction to the shell
5.7.4. $PATH
The $PATH variable is very important, it determines where the shell is looking for
commands to execute (unless the command is built-in). The shell will not look in the
current directory for commands to execute! (Looking for executables in the current
directory provided an easy way to crack DOS computers). If you want the shell to
look in the current directory, then add a . to your path.
Your path might be different when using su instead of su - because the latter will take
on the environment of the target user. The root user will have some sbin directories
added to the PATH variable.
[paul@RHEL3 ~]$ su
Password:
[root@RHEL3 paul]# echo $PATH
/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin
[root@RHEL3 paul]# exit
[paul@RHEL3 ~]$ su -
Password:
[root@RHEL3 ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:
[root@RHEL3 ~]#
68
Introduction to the shell
[paul@RHELv4u3 gen]$
There is, however, the nounset shell attribute that you can use to generate an error
when a variable does not exist.
paul@laika:~$ set -u
paul@laika:~$ echo $Myvar
bash: Myvar: unbound variable
paul@laika:~$ set +u
paul@laika:~$ echo $Myvar
paul@laika:~$
In the bash shell set -u is identical to set -o nounset and likewise set +u is identical
to set +o nounset.
5.7.8. set
You can use the set command to display a list of environment variables. On Ubuntu
and Debian systems, the set command will also list shell functions after the shell
variables. Use set | more to see the variables then.
5.7.9. unset
Use the unset command to remove a variable from your shell environment.
[paul@RHEL4b ~]$
5.7.10. env
The env command can also be useful for other neat things, such as starting a clean
shell (a shell without any inherited environment). The env -i command clears the
69
Introduction to the shell
environment for the subshell. Notice that bash will set the $SHELL variable on
startup.
You can also use the env command to set the $LANG, or any other, variable for just
one instance of bash with one command. The example below uses this to show the
influence of the $LANG variable on file globbing.
But it will not export to the parent shell (previous screenshot continued).
70
Introduction to the shell
underscore. In some situations, this can be a problem. This issue can be resolved with
curly braces like in this example.
The bash shell will replace variables with their value in double quoted lines, but not
in single quoted lines.
paul@laika:~$ city=Burtonville
paul@laika:~$ echo "We are in $city today."
We are in Burtonville today.
paul@laika:~$ echo 'We are in $city today.'
We are in $city today.
71
Introduction to the shell
7. Find the list of shell options in the man page of bash. What is the difference between
"set -u" and "set -o nounset" ?
10. Create a variable, give it the value 'Dumb', create another variable with value 'do'.
Use echo and the two variables to echo Dumbledore.
11. Activate nounset in your shell. Test that it shows an error message when using
non-existing variables.
13. Find the list of backslash escaped characters in the manual of bash. Add the time
to your PS1 prompt.
72
Introduction to the shell
set|more on Ubuntu/Debian
You will notice that set displays all variables, whereas env does not.
7. Find the list of shell options in the man page of bash. What is the difference between
"set -u" and "set -o nounset" ?
read the manual of bash (man bash), search for nounset -- both mean the same thing.
echo $var2
10. Create a variable, give it the value 'Dumb', create another variable with value 'do'.
Use echo and the two variables to echo Dumbledore.
varx=Dumb; vary=do
echo ${varx}le${vary}re
11. Activate nounset in your shell. Test that it shows an error message when using
non-existing variables.
set -u
set -o nounset
73
Introduction to the shell
Both these lines have the same effect (read the manual of bash, search for nounset).
set +o nounset
13. Find the list of backslash escaped characters in the manual of bash. Add the time
to your PS1 prompt.
PS1='\t \u@\h$ '
74
Introduction to the shell
This explains why the following four different command lines are the same after shell
expansion.
The echo command will display each argument it receives from the shell. The echo
command will also add a new whitespace between the arguments it received.
It is important for troubleshooting any script to know that the shell cuts your
command line in distinct arguments.
75
Introduction to the shell
The only difference between single and double quotes is the parsing of shell
variables. You can already see the difference in this screenshot.
The echo command can generate more than white spaces, tabs and newlines. Look
in the man page for a list of options (and remember that echo may be both built-in
and external).
[paul@RHELv4u3 gen]$
You can embed a shell in an embedded shell, this is called nested embedding of
shells.
76
Introduction to the shell
paul@deb503:~$ A=shell
paul@deb503:~$ echo $C$B$A $(B=sub;echo $C$B$A; echo $(A=sub;echo $C$B$A))
shell subshell subsub
77
Introduction to the shell
2. Complete the following command (do not use spaces) to display exactly the
following output:
echo -e "4+4=8" ; echo -e "10+14=24"
4+4 =8
10+14 =24
6. Create the variable embvar in an embedded shell and echo it. Does the variable
exist in your current shell now ?
8. Given the following screenshot, add exactly four characters to that command line
so that the total output is FirstMiddleLast.
9. Display the type of the passwd command using the which command inside back
ticks.
78
Introduction to the shell
2. Complete the following command (do not use spaces) to display exactly the
following output:
4+4 =8
10+14 =24
The echo command is only needed to show the result of the ls command. Omitting
will result in the shell trying to execute the first file as a command.
6. Create the variable embvar in an embedded shell and echo it. Does the variable
exist in your current shell now ?
$(embvar=emb;echo $embvar) ; echo $embvar (the last echo fails).
8. Given the following screenshot, add exactly four characters to that command line
so that the total output is FirstMiddleLast.
9. Display the type of the passwd command using the which command inside back
ticks.
type `which passwd`
79
Introduction to the shell
5.13.1. * asterisk
The shell is also responsible for file globbing (or dynamic filename generation). The
asterisk * is interpreted by the shell as a sign to generate filenames, matching the
asterisk to any combination of characters (even none). When no path is given, the
shell will use filenames in the current directory. See the man page of glob(7) for more
information. (This is part of LPI topic 1.103.3.)
[paul@RHELv4u3 gen]$ ls
file1 file2 file3 File4 File55 FileA fileab Fileab FileAB fileabc
[paul@RHELv4u3 gen]$ ls File*
File4 File55 FileA Fileab FileAB
[paul@RHELv4u3 gen]$ ls file*
file1 file2 file3 fileab fileabc
[paul@RHELv4u3 gen]$ ls *ile55
File55
[paul@RHELv4u3 gen]$ ls F*ile55
File55
[paul@RHELv4u3 gen]$ ls F*55
File55
[paul@RHELv4u3 gen]$
[paul@RHELv4u3 gen]$ ls
file1 file2 file3 File4 File55 FileA fileab Fileab FileAB fileabc
[paul@RHELv4u3 gen]$ ls File?
File4 FileA
[paul@RHELv4u3 gen]$ ls Fil?4
File4
[paul@RHELv4u3 gen]$ ls Fil??
File4 FileA
[paul@RHELv4u3 gen]$ ls File??
File55 Fileab FileAB
[paul@RHELv4u3 gen]$
80
Introduction to the shell
[paul@RHELv4u3 gen]$ ls
file1 file2 file3 File4 File55 FileA fileab Fileab FileAB fileabc
[paul@RHELv4u3 gen]$ ls File[5A]
FileA
[paul@RHELv4u3 gen]$ ls File[A5]
FileA
[paul@RHELv4u3 gen]$ ls File[A5][5b]
File55
[paul@RHELv4u3 gen]$ ls File[a5][5b]
File55 Fileab
[paul@RHELv4u3 gen]$ ls File[a5][5b][abcdefghijklm]
ls: File[a5][5b][abcdefghijklm]: No such file or directory
[paul@RHELv4u3 gen]$ ls file[a5][5b][abcdefghijklm]
fileabc
[paul@RHELv4u3 gen]$
You can also exclude characters from a list between square brackets with the
exclamation mark !. And you are allowed to make combinations of these wild cards.
[paul@RHELv4u3 gen]$ ls
file1 file2 file3 File4 File55 FileA fileab Fileab FileAB fileabc
[paul@RHELv4u3 gen]$ ls file[a5][!Z]
fileab
[paul@RHELv4u3 gen]$ ls file[!5]*
file1 file2 file3 fileab fileabc
[paul@RHELv4u3 gen]$ ls file[!5]?
fileab
[paul@RHELv4u3 gen]$
[paul@RHELv4u3 gen]$ ls
file1 file3 File55 fileab FileAB fileabc
file2 File4 FileA Fileab fileab2
[paul@RHELv4u3 gen]$ ls file[a-z]*
fileab fileab2 fileabc
[paul@RHELv4u3 gen]$ ls file[0-9]
file1 file2 file3
[paul@RHELv4u3 gen]$ ls file[a-z][a-z][0-9]*
fileab2
[paul@RHELv4u3 gen]$
paul@RHELv4u4:~/test$ ls [A-Z]ile?
file1 file2 file3 File4
paul@RHELv4u4:~/test$ ls [a-z]ile?
file1 file2 file3 File4
81
Introduction to the shell
[paul@RHEL4b ~]$
To list all the set options for your Bash shell, use echo $-. The noclobber option will
be explained later in this book (in the I/O redirection chapter).
82
Introduction to the shell
be remembered in your current shell session, and $HISTFILESIZE is the limit of the
number of commands that will be kept in the history file. The file will be truncated
when this limit is exceeded. Your shell session history is written to the file when
exiting the shell. This screenshot lists some history variables in bash.
You can also use bang followed by one or more characters, bash will then repeat the
last command that started with those characters. But this can be very dangerous, you
have to be certain that the last command in your current shell history that starts with
those characters is the command you wish to execute.
You can also use a colon followed by a regular expression to manipulate the previous
command.
83
Introduction to the shell
The history command can also receive a value indicating the number of the most
recent history lines to display.
This screenshot shows the history command. Note the different meaning of the
parameter.
$ history 17
17 clear
18 echo hoi
19 history 12
20 echo world
21 history 17
Repeating with r can be combined with the line numbers given by the history
command, or with the first few letters of the command.
$ r e
echo world
world
$ cd /etc
$ r
cd /etc
$
84
Introduction to the shell
2. Create files file1 file10 file11 file2 File2 File3 file33 fileAB filea fileA fileAAA
file( file 2 (the last one has 6 characters including a space)
5. List (with ls) all files starting with file and ending in a number.
6. List (with ls) all files starting with file and ending with a letter
7. List (with ls) all files starting with File and having a digit as fifth character.
8. List (with ls) all files starting with File and having a digit as fifth character and
nothing else.
9. List (with ls) all files starting with a letter and ending in a number.
10. List (with ls) all files that have exactly five characters.
11. List (with ls) all files that start with f or F and end with 3 or A.
12. List (with ls) all files that start with f have i or R as second character and end
in a number.
13. List all files that do not start with the letter F.
16. Write a command line that executes 'rm file55'. Your command line should print
'success' if file55 is removed, and print 'failed' if there was a problem.
17. You receive information that one of your servers was cracked, the cracker
probably replaced the ls command. You know that the echo command is safe to use.
Can echo replace ls ? How can you list the files in the current directory with echo ?
18. The cd command is also compromised, can echo be used to list files in other
directories ? Explain how this works (list the contents of /etc and /bin without ls).
20. Make sure bash remembers the last 5000 commands you typed.
85
Introduction to the shell
21. Open more than one console (press Ctrl-shift-t in gnome terminal) with the same
user account. When is command history written to the history file ?
22. Issue the date command. Now display the date in YYYY/MM/DD format.
23. Issue the cal command. Display a calendar of 1582 and 1752. Notice anything
special ?
86
Introduction to the shell
2. Create files file1 file10 file11 file2 File2 File3 file33 fileAB filea fileA fileAAA
file( file 2 (the last one has 6 characters including a space)
touch file1 file10 file11 file2 File2 File3 file33 fileAB filea fileA fileAAA
touch "file("
5. List (with ls) all files starting with file and ending in a number.
ls file*[0-9]
6. List (with ls) all files starting with file and ending with a letter
ls file*[a-z]
7. List (with ls) all files starting with File and having a digit as fifth character.
ls File[0-9]*
8. List (with ls) all files starting with File and having a digit as fifth character and
nothing else.
ls File[0-9]
9. List (with ls) all files starting with a letter and ending in a number.
ls [a-z]*[0-9]
10. List (with ls) all files that have exactly five characters.
ls ?????
11. List (with ls) all files that start with f or F and end with 3 or A.
ls [fF]*[3A]
12. List (with ls) all files that start with f have i or R as second character and end
in a number.
ls f[iR]*[0-9]
87
Introduction to the shell
13. List all files that do not start with the letter F.
ls [!F]*
16. Write a command line that executes 'rm file55'. Your command line should print
'success' if file55 is removed, and print 'failed' if there was a problem.
rm file55 && echo success || echo failed
17. You receive information that one of your servers was cracked, the cracker
probably replaced the ls command. You know that the echo command is safe to use.
Can echo replace ls ? How can you list the files in the current directory with echo ?
echo *
18. The cd command is also compromised, can echo be used to list files in other
directories ? Explain how this works (list the contents of /etc and /bin without ls).
echo /etc/* # the shell expands the directory for you
echo /bin/*
20. Make sure bash remembers the last 5000 commands you typed.
HISTSIZE=5000
21. Open more than one console (press Ctrl-shift-t in gnome terminal) with the same
user account. When is command history written to the history file ?
when you type exit
22. Issue the date command. Now display the date in YYYY/MM/DD format.
date +%Y/%m/%d
23. Issue the cal command. Display a calendar of 1582 and 1752. Notice anything
special ?
cal 1582
88
Introduction to the shell
The keyboard often server as stdin, stdout and stderr both go to the disply. The shell
allows you to redirect these streams.
Let me repeat myself here: While scanning the line, the shell will see the > sign and
will clear the file! This means that even when the command fails, the file will be
cleared!
Note that the > notation is in fact the abbreviation of 1> (stdout being referred to
as stream 1.
5.18.3. noclobber
Erasing a file while using > can be prevented by setting the noclobber option.
89
Introduction to the shell
5.18.6. 2>&1
To redirect both stdout and stderr to the same file, use 2>&1.
Note that the order of redirections is significant. For example, the command
ls > dirlist 2>&1
directs both standard output (file descriptor 1) and standard error (file descriptor 2)
to the file dirlist, while the command
90
Introduction to the shell
directs only the standard output to file dirlist, because the standard error was made a
copy of the standard output before the standard output was redirected to dirlist.
91
Introduction to the shell
And what is the quickest way to clear a file when the noclobber option is set ?
>|bar
This Tower Of Hanoi like construction uses a temporary stream 3, to be able to swap
stdout (1) and stderr (2). The following is an example of how to filter out all lines
in the stderr stream, containing $uninterestingerror.
/usr/bin/$somecommand 3>&1 1>&2 2>&3 | grep -v $uninterestingerror 3>&1 1>&2 2>&3
But in this example, it can be done in a much shorter way, by using a pipe on
STDERR:
/usr/bin/$somecommand |& grep -v $uninterestingerror
92
Introduction to the shell
4. When listing all shell options, which character represents the noclobber option ?
6. Make sure you have two shells open on the same computer. Create an empty
tailing.txt file. Then type tail -f tailing.txt. Use the second shell to append a line of
text to that file. Verify that the first shell displays this line.
7. Create a file that contains the names of five people. Use cat and output redirection
to create the file and use a here document to end the input.
93
Introduction to the shell
4. When listing all shell options, which character represents the noclobber option ?
set $- (noclobber is visible as C)
6. Make sure you have two shells open on the same computer. Create an empty
tailing.txt file. Then type tail -f tailing.txt. Use the second shell to append a line of
text to that file. Verify that the first shell displays this line.
paul@deb503:~$ > tailing.txt
paul@deb503:~$ tail -f tailing.txt
hello
world
7. Create a file that contains the names of five people. Use cat and output redirection
to create the file and use a here document to end the input.
paul@deb503:~$ cat > tennis.txt << ace
> Justine Henin
> Venus Williams
> Serena Williams
> Martina Hingis
> Kim Clijsters
> ace
paul@deb503:~$ cat tennis.txt
Justine Henin
Venus Williams
Serena Williams
Martina Hingis
Kim Clijsters
paul@deb503:~$
94
Chapter 6. Pipes and filters
6.1. pipes
A pipe takes stdout from the previous command and sends it as stdin to the next
command. All commands in a pipe run simultaneously.
6.2. filters
95
Pipes and filters
6.2.3. tee
Writing long pipes in Unix is fun, but sometimes you might want intermediate results.
This is were tee comes in handy. The tee filter puts stdin on stdout and also into a
file. So tee is almost the same as cat, except that it has two identical outputs.
[paul@RHEL4b pipes]$ tac count.txt | tee temp.txt | tac
one
two
three
four
five
[paul@RHEL4b pipes]$ cat temp.txt
five
four
three
two
one
[paul@RHEL4b pipes]$
6.2.4. grep
The grep filter is famous among Unix users. The most common use of grep is to
filter lines of text containing (or not containing) a certain string.
[paul@RHEL4b pipes]$ cat tennis.txt
Amelie Mauresmo, Fra
Kim Clijsters, BEL
Justine Henin, Bel
Serena Williams, usa
Venus Williams, USA
[paul@RHEL4b pipes]$ cat tennis.txt | grep Williams
Serena Williams, usa
Venus Williams, USA
96
Pipes and filters
One of the most useful options of grep is grep -i which filters in a case insensitive
way.
Another very useful option is grep -v which outputs lines not matching the string.
And of course, both options can be combined to filter all lines not containing a case
insensitive string.
With grep -A1 one line after the result is also displayed.
With grep -B1 one line before the result is also displayed.
With grep -C1 (context) one line before and one after are also displayed. All three
options (A,B, and C) can display any number of lines (using e.g. A2, B4 or C20).
97
Pipes and filters
6.2.5. cut
The cut filter can select columns from files, depending on a delimiter or a count of
bytes. The screenshot below uses cut to filter for the username and userid in the /etc/
passwd file. It uses the colon as a delimiter, and selects fields 1 and 3.
[[paul@RHEL4b pipes]$ cut -d: -f1,3 /etc/passwd | tail -4
Figo:510
Pfaff:511
Harry:516
Hermione:517
[paul@RHEL4b pipes]$
When using a space as the delimiter for cut, you have to quote the space.
This example uses cut to display the second to the seventh character of /etc/passwd.
6.2.6. tr
You can translate characters with tr. The screenshot shows the translation of all
occurrences of e to E.
98
Pipes and filters
The tr -s filter can also be used to squeeze multiple occurrences of a character to one.
6.2.7. wc
Counting words, lines and characters is easy with wc.
99
Pipes and filters
6.2.8. sort
The sort filter will default to an alphabetical sort.
But the sort filter has many options to tweak its usage. This example shows sorting
different columns (column 1 or column 2).
The screenshot below shows the difference between an alphabetical sort and a
numerical sort (both on the third column).
100
Pipes and filters
Iran, Teheran, 70
Germany, Berlin, 100
6.2.9. uniq
With uniq you can remove duplicates from a sorted list.
6.2.10. comm
Comparing streams (or files) can be done with the comm. By default comm will
output three columns. In this example, Abba, Cure and Queen are in both lists, Bowie
and Sweet are only in the first file, Turner is only in the second.
101
Pipes and filters
The output of comm can be easier to read when outputting only a single column. The
digits point out which output columns should not be displayed.
6.2.11. od
European humans like to work with ascii characters, but computers store files in bytes.
The example below creates a simple file, and then uses od to show the contents of
the file in hexadecimal bytes, in octal bytes and in ascii (or backslashed) characters.
6.2.12. sed
The stream editor sed can perform editing functions in the stream, using regular
expressions.
Add g for global replacements (all occurrences of the string per line).
102
Pipes and filters
6.3.1. who | wc
How many users are logged on to this system ?
Display a sorted list of logged on users, but every user only once.
103
Pipes and filters
3. Make a list of all files in /etc that contain the string samba.
4. Make a sorted list of all files in /etc that contain the case insensitive string samba.
5. Look at the output of /sbin/ifconfig. Write a line that displays only ip address and
the subnet mask.
7. Write a line that receives a textfile, and outputs all words on a separate line.
8. Write a spell checker on the command line. (There might be a dictionary in /usr/
share/dict/ .)
104
Pipes and filters
3. Make a list of all files in /etc that contain the string samba.
ls /etc | grep samba
4. Make a sorted list of all files in /etc that contain the case insensitive string samba.
ls /etc | grep -i samba | sort
5. Look at the output of /sbin/ifconfig. Write a line that displays only ip address and
the subnet mask.
/sbin/ifconfig | head -2 | grep 'inet ' | tr -s ' ' | cut -d' ' -f3,5
7. Write a line that receives a textfile, and outputs all words on a separate line.
8. Write a spell checker on the command line. (There might be a dictionary in /usr/
share/dict/ .)
105
Pipes and filters
paul@rhel ~$ cat text | tr 'A-Z ' 'a-z\n' | sort | uniq | comm -23 - DICT
zun
You could also add the solution from question number 6 to remove non-letters, and
tr -s ' ' to remove redundant spaces.
106
Chapter 7. Basic Unix tools
7.1.1. find
The find command can be very useful at the start of a pipe to search for files. Here are
some examples. You might want to add 2>/dev/null to the command lines to avoid
cluttering your screen with error messages.
Find all files of the entire system and put the list in allfiles.txt
find / > allfiles.txt
Find files that end in .conf in the current directory (and all subdirs).
find . -name "*.conf"
Find files of type file (not directory, pipe or etc.) that end in .conf.
find . -type f -name "*.conf"
Find can also execute another command on every file found. This example will look
for *.odf files and copy them to /backup/.
find "/data/*.odf" -exec cp {} /backup/ \;
Find can also execute, after your confirmation, another command on every file found.
This example will remove *.odf files if you approve of it for every file found.
find "/data/*.odf" -ok rm {} \;
7.1.2. locate
The locate tool is very different from find in that it uses an index to locate files. This
is a lot faster than traversing all the directories, but it also means that it is always
outdated. If the index does not exist yet, then you have to create it (as root on Red
Hat Enterprise Linux) with the updatedb command.
107
Basic Unix tools
Most Linux distributions will schedule the updatedb to run once every day.
7.1.3. date
The date command can display the date, time, timezone and more.
paul@rhel55 ~$ date
Sat Apr 17 12:44:30 CEST 2010
A date string can be customized to display the format of your choice. Check the man
page for more options.
paul@rhel55 ~$ date +'%A %d-%m-%Y'
Saturday 17-04-2010
Time on any Unix is calculated in number of seconds since 1969 (the first second
being the first second of the first of January 1970). Use date +%s to display Unix
time in seconds.
paul@rhel55 ~$ date +%s
1271501080
7.1.4. cal
The cal command displays the current month, with the current day highlighted.
paul@rhel55 ~$ cal
April 2010
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
108
Basic Unix tools
25 26 27 28 29 30
7.1.5. sleep
The sleep command is sometimes used in scripts to wait a number of seconds. This
example shows a five second sleep.
paul@rhel55 ~$ sleep 5
paul@rhel55 ~$
7.1.6. time
The time command can display how long it takes to execute a command. The date
command takes only a little time.
real 0m0.014s
user 0m0.008s
sys 0m0.006s
The sleep 5 command takes five real seconds to execute, but consumes little cpu
time.
real 0m5.018s
user 0m0.005s
sys 0m0.011s
This bzip2 command compresses a file and uses a lot of cpu time.
real 0m2.368s
user 0m0.847s
sys 0m0.539s
109
Basic Unix tools
110
Basic Unix tools
111
Basic Unix tools
2. Explain the difference between these two statements. Will they both work when
there are 200 .odf files in /data ? How about when there are 2 million .odf files ?
find /data -name "*.odf" > data_odf.txt
3. Write a find command that finds all files created after January 30th 2010.
4. Write a find command that finds all *.odf files created in September 2009.
5. Count the number of *.conf files in /etc and all its subdirs.
6. Two commands that do the same thing: copy *.odf files to /backup/ . What would
be a reason to replace the first command with the second ? Again, this is an important
question.
cp -r /data/*.odf /backup/
7. Create a file called loctest.txt. Can you find this file with locate ? Why not ? How
do you make locate find this file ?
112
Basic Unix tools
When *.txt is quoted then the shell will not touch it. The find tool will look in the
/data for all files ending in .txt.
When *.txt is not quoted then the shell might expand this (when one or more files
that ends in .txt exist in the current directory). The find might show a different result,
or can result in a syntax error.
2. Explain the difference between these two statements. Will they both work when
there are 200 .odf files in /data ? How about when there are 2 million .odf files ?
find /data -name "*.odf" > data_odf.txt
The first find will output all .odf filenames in /data and all subdirectories. The shell
will redirect this to a file.
The second find will output all files named .odf in /data and will also output all files
that exist in directories named *.odf (in /data).
With two million files the command line would be expanded beyond the maximum
that the shell can accept. The last part of the command line would be lost.
3. Write a find command that finds all files created after January 30th 2010.
touch -t 201001302359 marker_date
find . -type f -newer marker_date
4. Write a find command that finds all *.odf files created in September 2009.
touch -t 200908312359 marker_start
touch -t 200910010000 marker_end
find . -type f -name "*.odf" -newer marker_start ! -newer marker_end
5. Count the number of *.conf files in /etc and all its subdirs.
find /etc -type f -name '*.conf' | wc -l
6. Two commands that do the same thing: copy *.odf files to /backup/ . What would
be a reason to replace the first command with the second ? Again, this is an important
question.
cp -r /data/*.odf /backup/
The first might fail when there are too many files to fit on one command line.
113
Basic Unix tools
7. Create a file called loctest.txt. Can you find this file with locate ? Why not ? How
do you make locate find this file ?
You cannot locate this with locate because it is not yet in the index.
updatedb
114
Chapter 8. Introduction to vi
The vi editor is not intuitive, but once you get to know it, vi becomes a very powerful
application. Most Linux distributions will include the vimtutor which is a 45 minute
lesson in vi(m).
115
Introduction to vi
command action
x delete the character below the cursor
X delete the character before the cursor
r replace the character below the cursor
p paste after the cursor (here the last deleted character)
xp switch two characters
command action
u undo the last action
. repeat the last action
command action
dd cut the current line
yy (yank yank) copy the current line
p paste after the current line
P paste before the current line
116
Introduction to vi
command action
3dd cut three lines
4yy copy four lines
command action
0 jump to start of current line
^ jump to start of current line
$ jump to end of current line
d0 delete until start of line
d$ delete until end of line
command action
J join two lines
yyp duplicate a line
ddp switch two lines
117
Introduction to vi
8.2.9. words (w b)
When in command mode, w will jump to the next word and b will move to the
previous word. w and b can also be combined with d and y to copy and cut words
(dw db yw yb).
command action
w forward one word
b back one word
3w forward three words
dw delete one word
yw yank (copy) one word
5yb yank five words back
7dw delete seven words
command action
:w save (write)
:w fname save as fname
:q quit
:wq save and quit
ZZ save and quit
:q! quit (discarding your changes)
:w! save (and write to non-writable file!)
The last one is a bit special. With :w! vi will try to chmod the file to get write
permission (this works when you are the owner) and will chmod it back when the
write succeeds. This should always work when you are root (and the file system is
writable).
118
Introduction to vi
8.2.11. Searching (/ ?)
When in command mode typing / will allow you to search in vi for strings (can be
a regular expression). Typing /foo will do a forward search for the string foo and
typing ?bar will do a backward search for bar.
119
Introduction to vi
8.2.16. abbreviations
With :ab you can put abbreviations in vi. Use :una to undo the abbreviation.
This example shows how to set the F6 function key to toggle between set number
and set nonumber. The <bar> seperates the two commands, set number! toggles
the state and set number? reports the current state.
:map <F6> :set number!<bar>set number?<CR>
120
Introduction to vi
You can set these options (and much more) in ~/.vimrc for vim or in ~/.exrc for
standard vi.
121
Introduction to vi
2. What 3 key combination in command mode will duplicate the current line.
3. What 3 key combination in command mode will switch two lines' place (line five
becomes line six and line six becomes line five).
4. What 2 key combination in command mode will switch a character's place with
the next one.
5. vi can understand macro's. A macro can be recorded with q followed by the name
of the macro. So qa will record the macro named a. Pressing q again will end the
recording. You can recall the macro with @ followed by the name of the macro. Try
this example: i 1 'Escape Key' qa yyp 'Ctrl a' q 5@a (Ctrl a will increase the number
with one).
6. Copy /etc/passwd to your ~/passwd. Open the last one in vi and press Ctrl v. Use
the arrow keys to select a Visual Block, you can copy this with y or delete it with
d. Try pasting it.
7. What does dwwP do when you are at the beginning of a word in a sentence ?
122
Introduction to vi
2. What 3 key combination in command mode will duplicate the current line.
yyp
3. What 3 key combination in command mode will switch two lines' place (line five
becomes line six and line six becomes line five).
ddp
4. What 2 key combination in command mode will switch a character's place with
the next one.
xp
5. vi can understand macro's. A macro can be recorded with q followed by the name
of the macro. So qa will record the macro named a. Pressing q again will end the
recording. You can recall the macro with @ followed by the name of the macro. Try
this example: i 1 'Escape Key' qa yyp 'Ctrl a' q 5@a (Ctrl a will increase the number
with one).
6. Copy /etc/passwd to your ~/passwd. Open the last one in vi and press Ctrl v. Use
the arrow keys to select a Visual Block, you can copy this with y or delete it with
d. Try pasting it.
cp /etc/passwd ~
vi passwd
(press Ctrl-V)
7. What does dwwP do when you are at the beginning of a word in a sentence ?
dwwP can switch the current word with the next word.
123
Chapter 9. Introduction to scripting
This means that system administrators also need basic knowledge of scripting to
understand how their servers and their applications are started, updated, upgraded,
patched, maintained, configured and removed, and also to understand how a user
environment is built.
After creating this simple script in vi, you'll have to chmod +x hello_world to make
it executable. And unless you add the scripts directory to your path, you'll have to
type the path to the script for the shell to be able to find it.
9.3. she-bang
Let's expand our example a little further by putting #!/bin/bash on the first line of
the script. The #! is called a she-bang, where the she-bang is the first two characters
of the script.
#!/bin/bash
echo Hello World
9.4. comment
Let's expand our example a little further.
124
Introduction to scripting
#!/bin/bash
# Hello World Script
echo Hello World
9.5. Variables
#!/bin/bash
var1=4
echo var1 = $var1
Scripts can contain variables, but since scripts are run in their own shell, the variables
do not survive the end of the script.
[paul@RHEL4a ~]$
Luckily, you can force a script to run in the same shell; this is called sourcing a script.
9.6. Shell
You can never be sure which shell a user is running. A script that works flawlessly
in bash might not work in ksh, csh, or dash. To instruct a shell to run your script
in a certain shell, you can start your script with a shebang followed by the shell it is
supposed to run in. This script will run in a bash shell.
#!/bin/bash
echo -n hello
echo A bash subshell `echo -n hello`
125
Introduction to scripting
This script will run in a Korn shell (unless /bin/ksh is a link to /bin/bash). The /etc/
shells file contains a list of shells on your system.
#!/bin/ksh
echo -n hello
echo a Korn subshell `echo -n hello`
Some user may try to perform setuid based script root spoofing. This is a rare but
possible attack. To improve script security and to avoid interpreter spoofing, you need
to add -- after the #!/bin/bash, which disables further option processing so bash will
not accept any options.
#!/bin/bash -
or
#!/bin/bash --
Any arguments after the -- are treated as filenames and arguments. An argument of
- is equivalent to --.
for i in 1 2 4
do
echo $i
done
An example of a for loop combined with an embedded shell to generate the list.
let i=100;
while [ $i -ge 0 ] ;
do
echo Counting down, from 100 to 0, now at $i;
let i--;
126
Introduction to scripting
done
let i=100;
until [ $i -le 0 ] ;
do
echo Counting down, from 100 to 1, now at $i;
let i--;
done
9.10. parameters
A bash shell script can have parameters. The numbering you see in the script below
continues if you have more parameters. You also have special parameters containing
the number of parameters, a string of all of them, and also the process id, and the last
error code. The man page of bash has a full list.
#!/bin/bash
echo The first argument is $1
echo The second argument is $2
echo The third argument is $3
127
Introduction to scripting
9.11. test [ ]
The test command can test whether something is true or false. Let's start by testing
whether 10 is greater than 55.
The test command returns 1 if the test fails. And as you see in the next screenshot,
test returns 0 when a test succeeds.
If you prefer true and false, then write the test like this.
The test command can also be written as square brackets, the screenshot below is
identical to the one above.
Below are some example tests. Take a look at man test to see more options for tests.
128
Introduction to scripting
[paul@RHEL4b ~]$ [ 66 -gt 55 -a 66 -lt 500 ] && echo true || echo false
true
[paul@RHEL4b ~]$ [ 66 -gt 55 -a 660 -lt 500 ] && echo true || echo false
false
[paul@RHEL4b ~]$ [ 66 -gt 55 -o 660 -lt 500 ] && echo true || echo false
true
#!/bin/bash
if [ -f isit.txt ]
then echo isit.txt exists!
else echo isit.txt not found!
fi
9.13. let
The let built-in shell function instructs the shell to perform an evaluation of arithmetic
expressions. It will return 0 unless the last arithmetic expression evaluates to 0.
129
Introduction to scripting
#!/bin/bash
echo -n Enter a number:
read number
. ./myApp.conf
9.16. case
You can sometimes simplify nested if statements with a case construct.
130
Introduction to scripting
9.17. shopt
You can toggle the values of variables controlling optional shell behavior with the
shopt built-in shell command. The example below first verifies whether the cdspell
option is set; it is not. The next shopt command sets the value, and the third shopt
command verifies that the option really is set. You can now use minor spelling
mistakes in the cd command. The man page of bash has a complete list of options.
131
Introduction to scripting
1. Write a script that receives four parameters, and outputs them in reverse order.
2. Write a script that receives two parameters (two filenames) and outputs whether
those files exist.
3. Write a script that counts the number of files ending in .txt in the current directory.
4. Write a script that asks for two numbers, and outputs the sum and product (as
shown here).
Enter a number: 5
Enter another number: 2
Sum: 5 + 2 = 7
Product: 5 x 2 = 10
5. Improve the previous script to test that the numbers are between 1 and 100, exit
with an error if necessary.
6. Improve the previous script to congratulate the user if the sum equals the product.
7. Improve the script from question 2. to complain if it does not receive exactly two
parameters.
8. Write a script that counts from 3 to 7 and then from 7 to 3, and all this three times,
once with a for loop, once with a while loop and once with a until loop. Show the
teacher that it works!
9. Write a script that asks for a filename. Verify existence of the file, then verify that
you own the file, and whether it is writable. If not, then make it writable.
10. Make a configuration file for the previous script. Put a logging switch in the
config file, logging means writing detailed output of everything the script does to a
log file in /tmp.
11. Make the case statement in "Wild Animals Helpdesk Advice" case insensitive.
Use shopt (with the correct toggled option) for this, but reset the value back to it's
original after the end of the case statement. (A solution is available in appendix 1,
but try to find it yourself.)
12. If time permits (or if you are waiting for other students to finish this practice),
take a look at linux system scripts in /etc/init.d and /etc/rc.d and try to understand
them. Where does execution of a script start in /etc/init.d/samba ? There are also some
hidden scripts in ~, we will discuss them later.
9.19. Solutions
1. Write a script that receives four parameters, and outputs them in reverse order.
132
Introduction to scripting
echo $4 $3 $2 $1
2. Write a script that receives two parameters (two filenames) and outputs whether
those files exist.
#!/bin/bash
if [ -f $1 ]
then echo $1 exists!
else echo $1 not found!
fi
if [ -f $2 ]
then echo $2 exists!
else echo $2 not found!
fi
3. Write a script that counts the number of files ending in .txt in the current directory.
#!/bin/bash
4. Write a script that asks for two numbers, and outputs the sum and product (as
shown here).
Enter a number: 5
Enter another number: 2
Sum: 5 + 2 = 7
Product: 5 x 2 = 10
#!/bin/bash
let sum="$n1+$n2"
let pro="$n1*$n2"
133
Introduction to scripting
5. Improve the previous script to test that the numbers are between 1 and 100, exit
with an error if necessary.
6. Improve the previous script to congratulate the user if the sum equals the product.
7. Improve the script from question 2. to complain if it does not receive exactly two
parameters.
if [ $# -ne 2 ]
then
echo Must get two parameters...
exit 1
fi
8. Write a script that counts from 3 to 7 and then from 7 to 3, and all this three times,
once with a for loop, once with a while loop and once with a until loop. Show the
teacher that it works!
9. Write a script that asks for a filename. Verify existance of the file, then verify that
you own the file, and whether it is writable. If not, then make it writable.
10. Make a configuration file for the previous script. Put a logging switch in the
config file, logging means writing detailed output of everything the script does to a
log file in /tmp.
11. A script with a case insensitive case statement, using the shopt nocasematch
option. The nocasematch option is reset to the value it had before the scripts started.
#!/bin/bash
#
# Wild Animals Case Insensitive Helpdesk Advice
#
134
Introduction to scripting
fi
case $animal in
"lion" | "tiger")
echo "You better start running fast!"
;;
"cat")
echo "Let that mouse go..."
;;
"dog")
echo "Don't worry, give it a cookie."
;;
"chicken" | "goose" | "duck" )
echo "Eggs for breakfast!"
;;
"liger")
echo "Approach and say 'Ah you big fluffy kitty.'"
;;
"babelfish")
echo "Did it fall out your ear ?"
;;
*)
echo "You discovered an unknown animal, name it!"
;;
esac
12. If time permits (or if you are waiting for other students to finish this practice),
take a look at linux system scripts in /etc/init.d and /etc/rc.d and try to understand
them. Where does execution of a script start in /etc/init.d/samba ? There are also some
hidden scripts in ~, we will discuss them later.
Always take time to properly document every script that you write!
135
Chapter 10. Introduction to users
10.1.1. whoami
The whoami command tells you your username.
10.1.2. who
The who command will give you information about who is logged on the system.
10.1.3. who am i
With who am i the who command will display only the line pointing to your current
session.
10.1.4. w
The w command shows you who is logged on and what they are doing.
$ w
05:13:36 up 3 min, 4 users, load average: 0.48, 0.72, 0.33
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root tty1 - 05:11 2.00s 0.32s 0.27s find / -name shad
inge pts/0 192.168.1.33 05:12 0.00s 0.02s 0.02s -ksh
laura pts/1 192.168.1.34 05:12 46.00s 0.03s 0.03s -bash
paul pts/2 192.168.1.34 05:13 25.00s 0.07s 0.04s top
136
Introduction to users
10.1.5. id
The id command will give you your user id, primary group id, and a list of the groups
that you belong to.
root@laika:~# id
uid=0(root) gid=0(root) groups=0(root)
root@laika:~# su - brel
brel@laika:~$ id
uid=1001(brel) gid=1001(brel) groups=1001(brel),1008(chanson),11578(wolf)
137
Introduction to users
10.2. users
Another option is to use command line tools like useradd, usermod, gpasswd, passwd
and others. Server administrators are likely to use these tools, since they are familiar
and very similar accross many different distributions. This chapter will focus on these
command line tools.
A third and rather extremist way is to edit the local configuration files directly using
vi (or vipw/vigr). Do not attempt this as a novice on production systems!
10.2.2. /etc/passwd
The local user database on Linux (and on most Unixes) is /etc/passwd.
As you can see, this file contains seven columns separated by a colon. The columns
contain the username, an x, the user id, the primary group id, a description, the name
of the home directory, and the login shell.
10.2.3. root
The root user also called the superuser is the most powerful account on your Linux
system. This user can do almost anything, including the creation of other users. The
root user always has userid 0 (regardless of the name of the account).
138
Introduction to users
10.2.4. useradd
You can add users with the useradd command. The example below shows how to
add a user named yanina (last parameter) and at the same time forcing the creation
of the home directory (-m), setting the name of the home directory (-d), and setting
a description (-c).
The user named yanina received userid 529 and primary group id 529.
10.2.5. /etc/default/useradd
Both Red Hat Enterprise Linux and Debian/Ubuntu have a file called /etc/default/
useradd that contains some default user options. Besides using cat to display this
file, you can also use useradd -D.
10.2.6. userdel
You can delete the user yanina with userdel. The -r option of userdel will also remove
the home directory.
10.2.7. usermod
You can modify the properties of a user with the usermod command. This example
uses usermod to change the description of the user harry.
139
Introduction to users
10.3. passwords
10.3.1. passwd
Passwords of users can be set with the passwd command. Users will have to provide
their old password before twice entering the new one.
As you can see, the passwd tool will do some basic verification to prevent users
from using too simple passwords. The root user does not have to follow these rules
(there will be a warning though). The root user also does not have to provide the old
password before entering the new password twice.
10.3.2. /etc/shadow
User passwords are encrypted and kept in /etc/shadow. The /etc/shadow file is read
only and can only be read by root. We will see in the file permissions section how it
is possible for users to change their password. For now, you will have to know that
users can change their password with the /usr/bin/passwd command.
The /etc/shadow file contains nine colon separated columns. The nine fields contain
(from left to right) the user name, the encrypted password (note that only inge and
laura have an encrypted password), the day the password was last changed (day 1 is
January 1, 1970), number of days the password must be left unchanged, password
expiry day, warning number of days before password expiry, number of days after
expiry before disabling the account, and the day the account was disabled (again,
since 1970). The last field has no meaning yet.
140
Introduction to users
141
Introduction to users
To use it, we need to give two parameters to MyCript. The first is the unencrypted
password, the second is the salt. The salt is used to perturb the encryption algorithm in
one of 4096 different ways. This variation prevents two users with the same password
from having the same entry in /etc/shadow.
Did you notice that the first two characters of the password are the salt ?
The standard output of the crypt function is using the DES algorithm which is old
and can be cracked in minutes. A better method is to use MD5 passwords which can
be recognized by a salt starting with $1$.
The MD5 salt can be up to eight characters long. The salt is displayed in /etc/shadow
between the second and third $, so never use the password as the salt!
/etc/login.defs
The /etc/login.defs file contains some default settings for user passwords like
password aging and length settings. (You will also find the numerical limits of user
ids and group ids and whether or not a home directory should be created by default).
142
Introduction to users
chage
The chage command can be used to set an expiration date for a user account (-E),
set a mimimum (-m) and maximum (-M) password age, a password expiration date,
and set the number of warning days before the password expiration date. Much of
this functionality is also available from the passwd command. The -l option of chage
will list these settings for a user.
Using this feature is often called locking, disabling, or suspending a user account.
Besides vi (or vipw) you can also accomplish this with usermod.
The first line in the next screenshot will disable the password of user harry, making
it impossible for harry to authenticate using this password.
The root user (and users with sudo rights on su) still will be able to su to harry
(because the password is not needed here). Also note that harry will still be able to
login if he has set up passwordless ssh!
143
Introduction to users
Watch out for tiny differences in the command line options of passwd, usermod,
and useradd on different distributions! Verify the local files when using features like
"disabling, suspending, or locking" users and passwords!
144
Introduction to users
A less easy way is to create a home directory manually with mkdir which also
requires setting the owner and the permissions on the directory with chmod and
chown (both commands are discussed in detail in another chapter).
10.4.2. /etc/skel/
When using useradd with the -m option, the /etc/skel/ directory is copied to
the newly created home directory. The /etc/skel/ directory contains some (usually
hidden) files that contain profile settings and default values for applications. In this
way /etc/skel/ serves as a default home directory and as a default user profile.
145
Introduction to users
You can use the usermod command to change the shell for a user.
10.5.2. chsh
Users can change their login shell with the chsh command. First, user harry obtains
a list of available shells (he could also have done a cat /etc/shells) and then changes
his login shell to the Korn shell (/bin/ksh). At the next login, harry will default into
ksh instead of bash.
146
Introduction to users
10.6.2. su to root
Yes you can alsu su to become root, when you know the root password.
[harry@RHEL4b paul]$ su root
Password:
[root@RHEL4b paul]#
10.6.3. su as root
Uness you are logged in as root, running a shell as another user requires that you
know the password of that user. The root user can become any user without knowing
the user's password.
[root@RHEL4b paul]# su serena
[serena@RHEL4b paul]$
10.6.4. su - $username
By default, the su command maintains the same shell environment. To become
another user and also get the target user's environment, issue the su - command
followed by the target username.
[paul@RHEL4b ~]$ su - harry
Password:
[harry@RHEL4b ~]$
10.6.5. su -
When no username is provided to su or su -, the command will assume root is the
target.
[harry@RHEL4b ~]$ su -
Password:
[root@RHEL4b ~]#
147
Introduction to users
The screenshot below shows the usage of sudo. User paul received the right to run
useradd with the credentials of root. This allows paul to create new users on the
system without becoming root and without knowing the root password.
148
Introduction to users
10.7.3. visudo
Check the man page of visudo before playing with the /etc/sudoers file.
10.7.4. sudo su
On some linux systems like Ubuntu and Kubuntu, the root user does not have a
password set. This means that it is not possible to login as root (extra security). To
perform tasks as root, the first user is given all sudo rights via the /etc/sudoers. In
fact all users that are members of the admin group can use sudo to run all commands
as root.
The end result of this is that the user can type sudo su - and become root without
having to enter the root password. The sudo command does require you to enter your
own password. Thus the password prompt in the screenshot below is for sudo, not
for su.
paul@laika:~$ sudo su -
Password:
root@laika:~#
149
Introduction to users
2. Create a user called kornuser, give him the Korn shell (/bin/ksh) as his default
shell. Log on with this user (on a command line or in a tty).
3. Create a user named einstime without home directory, give him /bin/date as his
default logon shell. What happens when you log on with this user ? Can you think of
a useful real world example for changing a user's login shell to an application ?
4. Try the commands who, whoami, who am i, w, id, echo $USER $UID .
5b. Use passwd -d to disable the serena password. Verify the serena line in /etc/
shadow before and after disabling.
5c. What is the difference between locking a user account and disabling a user
account's password ?
8. Make sure every new user needs to change his password every 10 days.
10a. Set the password of two separate users to stargate. Look at the encrypted
stargate's in /etc/shadow and explain.
11. Put a file in the skeleton directory and check whether it is copied to user's home
directory. When is the skeleton directory copied ?
12. Why use vipw instead of vi ? What could be the problem when using vi or vim ?
13. Use chsh to list all shells, and compare to cat /etc/shells. Change your login shell
to the Korn shell, log out and back in. Now change back to bash.
15. How can you see whether the password of user harry is locked or unlocked ? Give
a solution with grep and a solution with passwd.
150
Introduction to users
2. Create a user called kornuser, give him the Korn shell (/bin/ksh) as his default
shell. Log on with this user (on a command line or in a tty).
useradd -s /bin/ksh kornuser ; passwd kornuser
3. Create a user named einstime without home directory, give him /bin/date as his
default logon shell. What happens when you log on with this user ? Can you think of
a useful real world example for changing a user's login shell to an application ?
useradd -s /bin/date einstime ; passwd einstime
It can be useful when users need to access only one application on the server. Just
logging on opens the application for them, and closing the application automatically
logs them off.
4. Try the commands who, whoami, who am i, w, id, echo $USER $UID .
who ; whoami ; who am i ; w ; id ; echo $USER $UID
5b. Use passwd -d to disable the serena password. Verify the serena line in /etc/
shadow before and after disabling.
grep serena /etc/shadow; passwd -d serena ; grep serena /etc/shadow
5c. What is the difference between locking a user account and disabling a user
account's password ?
Locking will prevent the user from logging on to the system with his password (by
putting a ! in front of the password in /etc/shadow). Disbling with passwd will erase
the password from /etc/shadow.
151
Introduction to users
8. Make sure every new user needs to change his password every 10 days.
For an existing user: chage -M 10 serena
10a. Set the password of two separate users to stargate. Look at the encrypted
stargate's in /etc/shadow and explain.
If you used passwd, then the salt will be different for the two encrypted passwords.
11. Put a file in the skeleton directory and check whether it is copied to user's home
directory. When is the skeleton directory copied ?
When you create a user account with a new home directory.
12. Why use vipw instead of vi ? What could be the problem when using vi or vim ?
vipw will give a warning when someone else is already using vipw on that file.
13. Use chsh to list all shells, and compare to cat /etc/shells. Change your login shell
to the Korn shell, log out and back in. Now change back to bash.
On Red Hat Enterprise Linux: chsh -l
15. How can you see whether the password of user harry is locked or unlocked ? Give
a solution with grep and a solution with passwd.
grep harry /etc/shadow
passwd -S harry
152
Introduction to users
10.10.1. /etc/profile
Both the bash and the ksh shell will verify the existence of /etc/profile and execute
it if it exists.
When reading this script, you might notice (at least on Debian Lenny and on Red Hat
Enterprise Linux 5) that it builds the PATH environment variable. The script might
also change the PS1 variable, set the HOSTNAME and execute even more scripts
like /etc/inputrc
You can use this script to set aliases and variables for every user on the system.
10.10.2. ~/.bash_profile
When this file exists in the users home directory, then bash will execute it. On Debian
Linux it does not exist by default.
RHEL5 uses a brief ~/.bash_profile where it checks for the existence of ~/.bashrc
and then executes it. It also adds $HOME/bin to the $PATH variable.
PATH=$PATH:$HOME/bin
export PATH
10.10.3. ~/.bash_login
When .bash_profile does not exist, then bash will check for ~/.bash_login and
execute it.
153
Introduction to users
10.10.4. ~/.profile
When neither ~/.bash_profile and ~/.bash_login exist, then bash will verify the
existence of ~/.profile and execute it. This file does not exist by default on Red Hat.
On Debian this script can execute ~/.bashrc and will add $HOME/bin to the $PATH
variable.
10.10.5. ~/.bashrc
As seen in the previous points, the ~/.bashrc script might be executed by other scripts.
Let us take a look at what it does by default.
Red Hat uses a very simple ~/.bashrc, checking for /etc/bashrc and executing it. It
also leaves room for custom aliases and functions.
On Debian this script is quite a bit longer and configures $PS1, some history variables
and a number af active and inactive aliases.
serena@deb503:~$ ls -l .bashrc
-rw-r--r-- 1 serena serena 3116 2008-05-12 21:02 .bashrc
10.10.6. ~/.bash_logout
When exiting bash, it can execute ~/.bash_logout. Debian and Red Hat both use this
opportunity to clear the screen.
154
Introduction to users
if [ "$SHLVL" = 1 ]; then
[ -x /usr/bin/clear_console ] && /usr/bin/clear_console -q
fi
/usr/bin/clear
155
Chapter 11. Introduction to groups
11.2. groupadd
Groups can be created with the groupadd command. The example below shows the
creation of five (empty) groups.
11.3. /etc/group
Users can be a member of several groups. Group membership is defined by the /etc/
group file.
The first field is the group's name. The second field is the group's (encrypted)
password (can be empty). The third field is the group identification or GID. The
fourth field is the list of members, these groups have no members.
11.4. usermod
Group membership can be modified with the useradd or usermod command.
156
Introduction to groups
Be careful when using usermod to add users to groups. By default, the usermod
command will remove the user from every group of which he is a member if the group
is not listed in the command! Using the -a (append) switch prevents this behaviour.
11.5. groupmod
You can change the group name with the groupmod command.
11.6. groupdel
You can permanently remove a group with the groupdel command.
11.7. groups
A user can type the groups command to see a list of groups where the user belongs to.
11.8. gpasswd
You can delegate control of group membership to another user with the gpasswd
command. In the example below we delegate permissions to add and remove group
157
Introduction to groups
members to serena for the sports group. Then we su to serena and add harry to the
sports group.
Group administrators do not have to be a member of the group. They can remove
themselves from a group, but this does not influence their ability to add or remove
members.
To remove all group administrators from a group, use the gpasswd command to set
an empty administrators list.
11.9. vigr
Similar to vipw, the vigr command can be used to manually edit the /etc/group file,
since it will do proper locking of the file. Only experienced senior administrators
should use vi or vigr to manage groups.
158
Introduction to groups
6. Make someone responsible for managing group membership of foot and sports.
Test that it works.
159
Introduction to groups
6. Make someone responsible for managing group membership of foot and sports.
Test that it works.
gpasswd -A (to make manager)
160
Chapter 12. Standard file permissions
paul@RHELv4u4:~/test$ ls -l
total 24
-rw-rw-r-- 1 paul paul 17 Feb 7 11:53 file1
-rw-rw-r-- 1 paul paul 106 Feb 5 17:04 file2
-rw-rw-r-- 1 paul proj 984 Feb 5 15:38 data.odt
-rw-r--r-- 1 root root 0 Feb 7 16:07 stuff.txt
paul@RHELv4u4:~/test$
User paul owns three files, two of those are also owned by the group paul; data.odt is
owned by the group proj. The root user owns the file stuff.txt, as does the group root.
12.1.2. chgrp
You can change the group owner of a file using the chgrp command.
12.1.3. chown
The user owner of a file can be changed with chown command.
root@laika:/home/paul# ls -l FileForPaul
-rw-r--r-- 1 root paul 0 2008-08-06 14:11 FileForPaul
root@laika:/home/paul# chown paul FileForPaul
root@laika:/home/paul# ls -l FileForPaul
-rw-r--r-- 1 paul paul 0 2008-08-06 14:11 FileForPaul
You can also use chown to change both the user owner and the group owner.
161
Standard file permissions
root@laika:/home/paul# ls -l FileForPaul
-rw-r--r-- 1 paul paul 0 2008-08-06 14:11 FileForPaul
root@laika:/home/paul# chown root:project42 FileForPaul
root@laika:/home/paul# ls -l FileForPaul
-rw-r--r-- 1 root project42 0 2008-08-06 14:11 FileForPaul
12.3. permissions
12.3.1. rwx
The nine characters following the file type denote the permissions in three triplets. A
permission can be r for read access, w for write access, and x for execute. You need
the r permission to list (ls) the contents of a directory. You need the x permission to
enter (cd) a directory. You need the w permission to create files in or remove files
from a directory.
162
Standard file permissions
paul@RHELv4u4:~/test$ ls -l proc42.bash
-rwxr-xr-- 1 paul proj 984 Feb 6 12:01 proc42.bash
When you are the user owner of a file, then the user owner permissions apply to
you. The rest of the permissions have no influence on your access to the file.
When you belong to the group that is the group owner of a file, then the group
owner permissions apply to you. The rest of the permissions have no influence on
your access to the file.
When you are not the user owner of a file and you do not belong to the group
owner, then the others permissions apply to you. The rest of the permissions have
no influence on your access to the file.
paul@laika:~/perms$ ls -lh
total 12K
drwxr-xr-x 2 paul paul 4.0K 2007-02-07 22:26 AllEnter_UserCreateDelete
-rwxrwxrwx 1 paul paul 0 2007-02-07 22:21 EveryoneFullControl.txt
-r--r----- 1 paul paul 0 2007-02-07 22:21 OnlyOwnersRead.txt
-rwxrwx--- 1 paul paul 0 2007-02-07 22:21 OwnersAll_RestNothing.txt
dr-xr-x--- 2 paul paul 4.0K 2007-02-07 22:25 UserAndGroupEnter
dr-x------ 2 paul paul 4.0K 2007-02-07 22:25 OnlyUserEnter
paul@laika:~/perms$
To summarize, the first rwx triplet represents the permissions for the user owner.
The second triplet corresponds to the group owner; it specifies permissions for all
members of that group. The third triplet defines permissions for all other users that
are not the user owner and are not a member of the group owner.
163
Standard file permissions
paul@laika:~/perms$ ls -l permissions.txt
-rw-r--r-- 1 paul paul 0 2007-02-07 22:34 permissions.txt
paul@laika:~/perms$ chmod u+x permissions.txt
paul@laika:~/perms$ ls -l permissions.txt
-rwxr--r-- 1 paul paul 0 2007-02-07 22:34 permissions.txt
164
Standard file permissions
This makes 777 equal to rwxrwxrwx and by the same logic, 654 mean rw-r-xr-- . The
chmod command will accept these numbers.
12.3.6. umask
When creating a file or directory, a set of default permissions are applied. These
default permissions are determined by the umask. The umask specifies permissions
that you do not want set on by default. You can display the umask with the umask
command.
165
Standard file permissions
[Harry@RHEL4b ~]$
As you can also see, the file is also not executable by default. This is a general security
feature among Unixes; newly created files are never executable by default. You have
to explicitly do a chmod +x to make a file executable. This also means that the 1 bit
in the umask has no meaning--a umask of 0022 is the same as 0033.
166
Standard file permissions
2. Copy a file owned by root from /etc/ to your permissions dir, who owns this file
now ?
6. Make sure you have all rights to these files, and others can only read.
11b. Set the umask to 077, but use the symbolic format to set it. Verify that this works.
12. Create a file as root, give only read to others. Can a normal user read this file ?
Test writing to this file with vi.
13a. Create a file as normal user, give only read to others. Can another normal user
read this file ? Test writing to this file with vi.
13b. Can root read this file ? Can root write to this file with vi ?
14. Create a directory that belongs to a group, where every member of that group
can read and write to files, and create files. Make sure that people can only delete
their own files.
167
Standard file permissions
2. Copy a file owned by root from /etc/ to your permissions dir, who owns this file
now ?
cp /etc/hosts ~/permissions/
6. Make sure you have all rights to these files, and others can only read.
chmod 644 (on files)
yes
No
yes
no
168
Standard file permissions
11b. Set the umask to 077, but use the symbolic format to set it. Verify that this works.
umask -S u=rwx,go=
12. Create a file as root, give only read to others. Can a normal user read this file ?
Test writing to this file with vi.
(become root)
(become user)
vi ~/root.txt
13a. Create a file as normal user, give only read to others. Can another normal user
read this file ? Test writing to this file with vi.
echo hello > file ; chmod 744 file
13b. Can root read this file ? Can root write to this file with vi ?
Yes, root can read and write to this file. Permissions do not apply to root.
14. Create a directory that belongs to a group, where every member of that group
can read and write to files, and create files. Make sure that people can only delete
their own files.
mkdir /home/project42 ; groupadd project42
169
Standard file permissions
The sticky bit can also be set with octal permissions, it is binary 1 in the first of four
triplets.
You will typically find the sticky bit on the /tmp directory.
170
Standard file permissions
root@RHELv4u4:~#
You can use the find command to find all setgid directories.
Take the example of passwords; they are stored in /etc/shadow which is only readable
by root. (The root user never needs permissions anyway.)
root@RHELv4u4:~# ls -l /etc/shadow
-r-------- 1 root root 1260 Jan 21 07:49 /etc/shadow
Changing your password requires an update of this file, so how can normal non-root
users do this? Let's take a look at the permissions on the /usr/bin/passwd.
root@RHELv4u4:~# ls -l /usr/bin/passwd
-r-s--x--x 1 root root 21200 Jun 17 2005 /usr/bin/passwd
When running the passwd program, you are executing it with root credentials.
You can use the find command to find all setuid programs.
In most cases, setting the setuid bit on executables is sufficient. Setting the setgid bit
will result in these programs to run with the credentials of their group owner.
171
Standard file permissions
1b. Members of the sports group should be able to create files in this directory.
1c. All files created in this directory should be group-owned by the sports group.
1d. Users should be able to delete only their own user-owned files.
2. Verify the permissions on /usr/bin/passwd. Remove the setuid, then try changing
your password as a normal user. Reset the permissions back and try again.
3. If time permits (or if you are waiting for other students to finish this practice), read
about file attributes in the man page of chattr and lsattr. Try setting the i attribute on
a file and test that it works.
172
Standard file permissions
mkdir /home/sports
1b. Members of the sports group should be able to create files in this directory.
chmod 770 /home/sports
1c. All files created in this directory should be group-owned by the sports group.
chmod 2770 /home/sports
1d. Users should be able to delete only their own user-owned files.
chmod +t /home/sports
Log in with different users (group members and others and root), create files and
watch the permissions. Try changing and deleting files...
2. Verify the permissions on /usr/bin/passwd. Remove the setuid, then try changing
your password as a normal user. Reset the permissions back and try again.
root@deb503:~# ls -l /usr/bin/passwd
-rwsr-xr-x 1 root root 31704 2009-11-14 15:41 /usr/bin/passwd
root@deb503:~# chmod 755 /usr/bin/passwd
root@deb503:~# ls -l /usr/bin/passwd
-rwxr-xr-x 1 root root 31704 2009-11-14 15:41 /usr/bin/passwd
3. If time permits (or if you are waiting for other students to finish this practice), read
about file attributes in the man page of chattr and lsattr. Try setting the i attribute on
a file and test that it works.
paul@laika:~$ sudo su -
[sudo] password for paul:
root@laika:~# mkdir attr
root@laika:~# cd attr/
root@laika:~/attr# touch file42
root@laika:~/attr# lsattr
------------------ ./file42
root@laika:~/attr# chattr +i file42
root@laika:~/attr# lsattr
173
Standard file permissions
----i------------- ./file42
root@laika:~/attr# rm -rf file42
rm: cannot remove `file42': Operation not permitted
root@laika:~/attr# chattr -i file42
root@laika:~/attr# rm -rf file42
root@laika:~/attr#
12.9.2. getfacl
Reading acls can be done with /usr/bin/getfacl. This screenshot shows how to read
the acl of file33 with getfacl.
12.9.3. setfacl
Writing or changing acls can be done with /usr/bin/setfacl. These screenshots show
how to change the acl of file33 with setfacl.
174
Standard file permissions
Then we add the group tennis with octal permission 6 to the acl of the same file.
Note that omitting the u or g when defining the acl for an account will default it to
a user account.
175
Standard file permissions
12.9.7. eiciel
Desktop users might want to use eiciel to manage acls with a graphical tool.
You will need to install eiciel and nautilus-actions to have an extra tab in nautilus
to manage acls.
176
Chapter 13. File links
13.1. inodes
To understand links in a file system, you first have to understand what an inode is.
The ls -l command will display some of the inode contents, as seen in this screenshot.
oot@rhel53 ~# df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/mapper/VolGroup00-LogVol00
4947968 115326 4832642 3% /
/dev/hda1 26104 45 26059 1% /boot
tmpfs 64417 1 64416 1% /dev/shm
/dev/sda1 262144 2207 259937 1% /home/project42
/dev/sdb1 74400 5519 68881 8% /home/project33
/dev/sdb5 0 0 0 - /home/sales
/dev/sdb6 100744 11 100733 1% /home/research
In the df -i screenshot above you can see the inode usage for several mounted file
systems. You don't see numbers for /dev/sdb5 because it is a fat file system.
177
File links
These three files were created one after the other and got three different inodes (the
first column). All the information you see with this ls command resides in the inode,
except for the filename (which is contained in the directory).
paul@RHELv4u4:~/test$ ls -li
total 16
817266 -rw-rw-r-- 1 paul paul 0 Feb 5 15:38 file1
817270 -rw-rw-r-- 1 paul paul 92 Feb 5 15:42 file2
817268 -rw-rw-r-- 1 paul paul 0 Feb 5 15:38 file3
paul@RHELv4u4:~/test$ cat file2
It is winter now and it is very cold.
We do not like the cold, we prefer hot summer nights.
paul@RHELv4u4:~/test$
The data that is displayed by the cat command is not in the inode, but somewhere
else on the disk. The inode contains a pointer to that data.
paul@RHELv4u4:~/test$ ls -ali
total 32
817262 drwxrwxr-x 2 paul paul 4096 Feb 5 15:42 .
800768 drwx------ 16 paul paul 4096 Feb 5 15:42 ..
817266 -rw-rw-r-- 1 paul paul 0 Feb 5 15:38 file1
817270 -rw-rw-r-- 1 paul paul 92 Feb 5 15:42 file2
817268 -rw-rw-r-- 1 paul paul 0 Feb 5 15:38 file3
paul@RHELv4u4:~/test$
178
File links
13.2.2. . and ..
You can see five names, and the mapping to their five inodes. The dot . is a mapping
to itself, and the dotdot .. is a mapping to the parent directory. The three other names
are mappings to different inodes.
Both files have the same inode, so they will always have the same permissions and
the same owner. Both files will have the same content. Actually, both files are equal
now, meaning you can safely remove the original file, the hardlinked file will remain.
The inode contains a counter, counting the number of hard links to itself. When the
counter drops to zero, then the inode is emptied.
179
File links
Permissions on a symbolic link have no meaning, since the permissions of the target
apply. Hard links are limited to their own partition (because they point to an inode),
symbolic links can link anywhere (other file systems, even networked).
180
File links
3. Display the inode numbers of these three files, the hard links should have the same
inode.
5. Everything about a file is in the inode, except two things : name them!
7. Find all files with inode number 2. What does this information tell you ?
8. Look at the directories /etc/init.d/ /etc/rc.d/ /etc/rc3.d/ ... do you see the links ?
10. Use find to look in your home directory for regular files that do not(!) have one
hard link.
181
File links
3. Display the inode numbers of these three files, the hard links should have the same
inode.
ls -li winter.txt summer.txt hlwinter.txt
5. Everything about a file is in the inode, except two things : name them!
The name of the file is in a directory, and the contents is somewhere on the disk.
7. Find all files with inode number 2. What does this information tell you ?
It tells you there is more than one inode table (one for every formatted partition +
virtual file systems)
8. Look at the directories /etc/init.d/ /etc/rc.d/ /etc/rc3.d/ ... do you see the links ?
ls -l /etc/init.d
ls -l /etc/rc.d
ls -l /etc/rc3.d
10. Use find to look in your home directory for regular files that do not(!) have one
hard link.
find ~ ! -links 1 -type f
182
Chapter 14. Process management
14.1. terminology
14.1.1. process
A process is compiled source code that is currently running on the system.
14.1.2. PID
All processes have a process id or PID.
14.1.3. PPID
Every process has a parent process (with a PPID). The child process is often started
by the parent process.
14.1.4. init
The init process always has process ID 1. The init process is started by the kernel
itself so technically it does not have a parent process. init serves as a foster parent
for orphaned processes.
14.1.5. kill
When a process stops running, the process dies, when you want a process to die, you
kill it.
14.1.6. daemon
Processes that start at system startup and keep running forever are called daemon
processes or daemons. These daemons never die.
14.1.7. zombie
When a process is killed, but it still shows up on the system, then the process is
referred to as zombie. You cannot kill zombies, because they are already dead.
183
Process management
14.2.2. pidof
You can find all process id's by name using the pidof command.
When starting a new bash you can use echo to verify that the pid from before is the
ppid of the new shell. The child process from above is now the parent process.
Typing exit will end the current process and brings us back to our original values
for $$ and $PPID.
184
Process management
14.2.5. exec
With the exec command, you can execute a process without forking a new process.
In the following screenshot a Korn shell (ksh) is started and is being replaced with a
bash shell using the exec command. The pid of the bash shell is the same as the pid
of the Korn shell. Exiting the child bash shell will get me back to the parent bash,
not to the Korn shell (which does not exist anymore).
14.2.6. ps
One of the most common tools on Linux to look at processes is ps. The following
screenshot shows the parent child relationship between three bash processes.
185
Process management
On Linux, ps fax is often used. On Solaris ps -ef (which also works on Linux) is
common. Here is a partial output from ps fax.
...
14.2.7. pgrep
Similar to the ps -C, you can also use pgrep to search for a process by its command
name.
You can also list the command name of the process with pgrep.
186
Process management
14.2.8. top
Another popular tool on Linux is top. The top tool can order processes according to
cpu usage or other properties. You can also kill processes from within top. Press h
inside top for help.
In case of trouble, top is often the first tool to fire up, since it also provides you
memory and swap space information.
187
Process management
14.3.1. kill
The kill command will kill (or stop) a process. The screenshot shows how to use a
standard kill to stop the process with pid 1942.
root@deb503:~# kill -1 1
root@deb503:~#
It is up to the developer of the process to decide whether the process can do this
running, or whether it needs to stop and start. It is up to the user to read the
documentation of the program.
188
Process management
14.3.6. killall
The killall command will also default to sending a signal 15 to the processes.
This command and its SysV counterpart killall5 can by used when shutting down
the system. This screenshot shows how Red Hat Enterprise Linux 5.3 uses killall5
when halting the system.
14.3.7. pkill
You can use the pkill command to kill a process by its command name.
14.3.8. top
Inside top the k key allows you to select a signal and pid to kill. Below is a partial
screenshot of the line just below the summary in top after pressing k.
189
Process management
A suspended process does not use any cpu cycles, but it stays in memory and can be
re-animated with a SIGCONT signal (kill -18 on Linux).
190
Process management
4. Using your terminal name from above, use ps to find all processes associated with
your terminal.
9. Display only those two sleep processes in top. Then quit top.
191
Process management
root@rhel53 ~# ps -C init
PID TTY TIME CMD
1 ? 00:00:04 init
root@rhel53 ~# who am i
paul pts/0 2010-04-12 17:44 (192.168.1.38)
4. Using your terminal name from above, use ps to find all processes associated with
your terminal.
or also
in this example the PPID is from the su - command, but when inside gnome then for
example gnome-terminal can be the parent process
192
Process management
9. Display only those two sleep processes in top. Then quit top.
top -p pidx,pidy (replace pidx pidy with the actual numbers)
193
Process management
14.6.1. introduction
All processes have a priority and a nice value. Higher priority processes will get
more cpu time than lower priority processes. You can influence this with the nice
and renice commands.
The screenshots shows the creation of four distinct pipes (in a new directory).
The cat is copied with a distinct name to the current directory. (This enables us to
easily recognize the processes within top. You could do the same exercise without
copying the cat command, but using different users. Or you could just look at the pid
of each process.)
The commands you see above will create two proj33 processes that use cat to bounce
the x character between pipe33a and pipe33b. And ditto for the z character and
proj42.
194
Process management
14.6.4. top
Just running top without options or arguments will display all processes and an
overview of innformation. The top of the top screen might look something like this.
Notice the cpu idle time (0.0%id) is zero. This is because our cat processes are
consuming the whole cpu. Results can vary on systems with four or more cpu cores.
14.6.5. top -p
The top -p 1670,1671,1673,1674 screenshot below shows four processes, all of then
using approximately 25 percent of the cpu.
All four processes have an equal priority (PR), and are battling for cpu time. On
some systems the Linux kernel might attribute slightly varying priority values, but
the result will still be four processes fighting for cpu time.
14.6.6. renice
Since the processes are already running, we need to use the renice command to
change their nice value (NI).
The screenshot shows how to use renice on both the proj33 processes.
Normal users can attribute a nice value from zero to 20 to processes they own. Only
the root user can use negative nice values. Be very careful with negative nice values,
since they can make it impossible to use the keyboard or ssh to a system.
195
Process management
14.6.8. nice
The nice works identical to the renice but it is used when starting a command.
The screenshot shows how to start a script with a nice value of five.
196
Process management
3. Use top and ps to display information (pid, ppid, priority, nice value, ...) about
these two cat processes.
4. Bounce another character between two other pipes, but this time start the
commands nice. Verify that all cat processes are battling for the cpu. (Feel free to
fire up two more cats with the remaining pipes).
5. Use ps to verify that the two new cat processes have a nice value. Use the -o and
-C options of ps for this.
6. Use renice te increase the nice value from 10 to 15. Notice the difference with
the usual commands.
197
Process management
3. Use top and ps to display information (pid, ppid, priority, nice value, ...) about
these two cat processes.
top (probably the top two lines)
4. Bounce another character between two other pipes, but this time start the
commands nice. Verify that all cat processes are battling for the cpu. (Feel free to
fire up two more cats with the remaining pipes).
echo -n y | nice cat - p3 > p4 &
nice cat <p4 >p3 &
5. Use ps to verify that the two new cat processes have a nice value. Use the -o and
-C options of ps for this.
[paul@rhel53 pipes]$ ps -C cat -o pid,ppid,pri,ni,comm
PID PPID PRI NI COMMAND
4013 3947 14 0 cat
4016 3947 21 0 cat
4025 3947 13 10 cat
4026 3947 13 10 cat
6. Use renice te increase the nice value from 10 to 15. Notice the difference with
the usual commands.
[paul@rhel53 pipes]$ renice +15 4025
4025: old priority 10, new priority 15
[paul@rhel53 pipes]$ renice +15 4026
198
Process management
199
Process management
14.9.1. jobs
Stuff that runs in background of your current shell can be displayed with the jobs
command. By default you will not have any jobs running in background.
root@rhel53 ~# jobs
root@rhel53 ~#
14.9.2. control-Z
Some processes can be suspended with the Ctrl-Z key combination. This sends
a SIGSTOP signal to the Linux kernel, effectively freezing the operation of the
process.
When doing this in vi(m), then vi(m) goes to the background. The background vi(m)
can be seen with the jobs command.
14.9.4. jobs -p
An interesting option is jobs -p to see the process id of background processes.
200
Process management
[1] 4902
[paul@RHEL4b ~]$ sleep 400 &
[2] 4903
[paul@RHEL4b ~]$ jobs -p
4902
4903
[paul@RHEL4b ~]$ ps `jobs -p`
PID TTY STAT TIME COMMAND
4902 pts/0 S 0:00 sleep 500
4903 pts/0 S 0:00 sleep 400
[paul@RHEL4b ~]$
14.9.5. fg
Running the fg command will bring a background job to the foreground. The number
of the background job to bring forward is the parameter of fg.
14.9.6. bg
Jobs that are suspended in background can be started in background with bg. The
bg will send a SIGCONT signal.
Below an example of the sleep command (suspended with Ctrl-Z) being reactivated
in background with bg.
201
Process management
10. (if time permits, a general review question...) Explain in detail where the numbers
come from in the next screenshot. When are the variables replaced by their value ?
By which shell ?
202
Process management
10. (if time permits, a general review question...) Explain in detail where the numbers
come from in the next screenshot. When are the variables replaced by their value ?
By which shell ?
203
Process management
The current bash shell will replace the $$ and $PPID while scanning the line, and
before executing the echo command.
The variables are now double quoted, but the current bash shell will replace $$ and
$PPID while scanning the line, and before executing the bach -c command.
The variables are now single quoted. The current bash shell will not replace the $$
and the $PPID. The bash -c command will be executed before the variables replaced
with their value. This latter bash is the one replacing the $$ and $PPID with their
value.
With backticks the shell will still replace both variable before the embedded echo is
executed. The result of this echo is the two process id's. These are given as commands
to bash -c. But two numbers are not commands!
204
Appendix A. Keyboard settings
When in Gnome or KDE or any other graphical environment, look in the graphical
menu in preferences, there will be a keyboard section to choose your layout. Use the
graphical menu instead of editing xorg.conf.
205
Keyboard settings
206
Appendix B. Hardware Settings
B.1. buses
Older x86 computers often had isa buses, which can be confugred using jumpers or
dip switches.
B.1.2. /proc/bus
To list the buses recognized by the Linux kernel on your computer, look at the
contents of the /proc/bus/ directory (screenshot from Ubuntu 7.04 and RHEL4u4
below).
root@laika:~# ls /proc/bus/
input pccard pci usb
Can you guess which of these two screenshots was taken on a laptop ?
B.1.3. /usr/sbin/lsusb
To list all the usb devices connected to your system, you could read the contents
of /proc/bus/usb/devices (if it exists) or you could use the more readable output of
lsusb, which is executed here on a SPARC system with Ubuntu.
root@shaka:~# lsusb
Bus 001 Device 002: ID 0430:0100 Sun Microsystems, Inc. 3-button Mouse
Bus 001 Device 003: ID 0430:0005 Sun Microsystems, Inc. Type 6 Keyboard
Bus 001 Device 001: ID 04b0:0136 Nikon Corp. Coolpix 7900 (storage)
root@shaka:~#
B.1.4. /var/lib/usbutils/usb.ids
The /var/lib/usbutils/usb.ids file contains a gzipped list of all known usb devices.
207
Hardware Settings
B.1.5. /usr/sbin/lspci
To get a list of all pci devices connected, you could take a look at /proc/bus/pci or
run lspci (partial output below).
paul@laika:~$ lspci
...
00:06.0 FireWire (IEEE 1394): Texas Instruments TSB43AB22/A IEEE-139...
00:08.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL-816...
00:09.0 Multimedia controller: Philips Semiconductors SAA7133/SAA713...
00:0a.0 Network controller: RaLink RT2500 802.11g Cardbus/mini-PCI
00:0f.0 RAID bus controller: VIA Technologies, Inc. VIA VT6420 SATA ...
00:0f.1 IDE interface: VIA Technologies, Inc. VT82C586A/B/VT82C686/A...
00:10.0 USB Controller: VIA Technologies, Inc. VT82xxxxx UHCI USB 1....
00:10.1 USB Controller: VIA Technologies, Inc. VT82xxxxx UHCI USB 1....
...
B.2. interrupts
Interrupt 0 is always reserved for the timer, interrupt 1 for the keyboard. IRQ 2 is
used as a channel for IRQ's 8 to 15, and thus is the same as IRQ 9.
B.2.2. /proc/interrupts
You can see a listing of interrupts on your system in /proc/interrupts.
208
Hardware Settings
CPU0 CPU1
0: 1320048 555 IO-APIC-edge timer
1: 10224 7 IO-APIC-edge i8042
7: 0 0 IO-APIC-edge parport0
8: 2 1 IO-APIC-edge rtc
10: 3062 21 IO-APIC-fasteoi acpi
12: 131 2 IO-APIC-edge i8042
15: 47073 0 IO-APIC-edge ide1
18: 0 1 IO-APIC-fasteoi yenta
19: 31056 1 IO-APIC-fasteoi libata, ohci1394
20: 19042 1 IO-APIC-fasteoi eth0
21: 44052 1 IO-APIC-fasteoi uhci_hcd:usb1, uhci_hcd:usb2,...
22: 188352 1 IO-APIC-fasteoi ra0
23: 632444 1 IO-APIC-fasteoi nvidia
24: 1585 1 IO-APIC-fasteoi VIA82XX-MODEM, VIA8237
B.2.3. dmesg
You can also use dmesg to find irq's allocated at boot time.
B.3. io ports
B.3.2. /proc/ioports
You can see a listing of your system's IO ports via /proc/ioports.
209
Hardware Settings
...
B.4. dma
B.4.2. /proc/dma
Looking at /proc/dma might not give you the information that you want, since it only
contains currently assigned dma channels for isa devices.
pci devices that are using dma are not listed in /proc/dma, in this case dmesg can be
useful. The screenshot below shows that during boot the parallel port received dma
channel 1, and the Infrared port received dma channel 3.
210
/etc/slackware-version, 5
Index /etc/sudoers, 148, 149
/etc/SuSE-release, 5
Symbols /etc/sysconfig, 41
;, 62 /etc/sysconfig/firstboot, 41
!, 81, 83 /etc/sysconfig/harddisks, 42
!!, 83 /etc/sysconfig/hwconf, 42
? (file globbing), 80 /etc/sysconfig/keyboard, 42
/, 38 /etc/X11/xorg.conf, 41
/bin, 39, 55 /home, 42
/bin/bash, 55, 153 /lib, 43
/bin/csh, 55 /lib/kbd/keymaps/, 42
/bin/dash, 55 /lib/modules, 43
/bin/ksh, 55, 153 /lib32, 43
/bin/rm, 57 /lib64, 43
/bin/sh, 55 /media, 43
/boot, 39 /mnt, 44
/boot/grub, 39 /opt, 44
/boot/grub/grub.conf, 39 /proc, 44
/boot/grub/menu.lst, 39 /proc/bus, 207
/dev, 40 /proc/bus/pci, 208
/dev/null, 40, 90 /proc/bus/usb/devices, 207
/dev/pts/1, 40 /proc/cpuinfo, 45
/dev/random, 53 /proc/dma, 210
/dev/tty1, 40 /proc/filesystems, 46
/dev/urandom, 52, 54 /proc/interrupts, 47, 208
/dev/zero, 53 /proc/ioports, 209
/etc, 40 /proc/kcore, 48
/etc/bashrc, 154 /proc/swaps, 48
/etc/debian-version, 4 /proc/sys, 46
/etc/default/useradd, 139 /root, 48
/etc/filesystems, 46 /sbin, 48, 55
/etc/fstab, 174 /srv, 48
/etc/gentoo-release, 5 /sys, 48
/etc/group, 156, 161 /tmp, 49
/etc/gshadow, 158 /usr, 49
/etc/hosts, 53 /usr/bin/getfacl, 174
/etc/inputrc, 153 /usr/bin/passwd, 171
/etc/login.defs, 142 /usr/bin/setfacl, 174
/etc/lsb-release, 5 /var, 49
/etc/mandriva-release, 5 /var/cache, 49
/etc/passwd, 138, 146, 161 /var/lib/rpm, 49
/etc/profile, 153 /var/lib/usbutils/usb.ids, 207
/etc/redhat-release, 4 /var/log, 49
/etc/resolv.conf, 54 /var/run, 49
/etc/shadow, 140, 171 /var/spool, 49
/etc/shells, 126, 146 /var/spool/up2date, 50
/etc/skel, 41, 145 /var/tmp, 49
211
Index
., 179 B
.., 179 backticks, 77
.bash_login, 153 bash, 2
.bash_logout, 154 Belenix, 8
.bash_profile, 153 bg(1), 201
.bashrc, 153, 154 Bourne again shell, 55
.exrc, 121 BSD, 2
.vimrc, 121 BSD Net/2, 2
`(backtick), 77 bunzip2, 110
'(single quote), 77 bus, 207
[, 80 bzcat, 111
$? (shell variables), 68 bzip2, 110, 111
$ (shell variables), 67 bzmore, 111
$$, 184
$HISTFILE, 82 C
$HISTFILESIZE, 83 cal, 108
$HISTSIZE, 82 Canonical, 6
$LANG, 81 case sensitive, 38
$PATH, 56, 68 cat, 96
$PPID, 184 cat(1), 33
* (file globbing), 80 cd, 15
\, 64 cd -, 16
&, 62 cd .., 16
&&, 62 cd ~, 15
#!/bin/bash, 125 CentOS, 6
>, 89 chage(1), 143
>>, 90 chgrp(1), 161
>|, 90 chkconfig, 41
|, 95 chmod, 165
||, 63 chmod(1), 118, 164
1>, 90 chmod +x, 124, 166
2>, 90 chown(1), 161
2>&1, 90 chsh(1), 146
777, 165 CMDBA, 10
CMDEV, 9
A comm(1), 101
absolute and relative paths, 16 command line scan, 58
access control list, 174 command mode(vi), 115
acl, 176 cp(1), 26, 26
acls, 174 cpu, 207
agp, 207 crypt, 141
AIX, 8 Ctrl D, 33
alias(bash), 56, 56 Ctrl-Z, 200
apropos, 11 current directory, 15
aptitude, 8 cut(1), 98
aptitude(1), 7
D
daemon, 183
212
Index
213
Index
214
Index
RHEL ES, 5 T
RHEL WS, 5 tab key, 17
Richard Stallman, 2 tac(1), 34
rm(1), 25, 180 tail(1), 32
rmdir, 19 tee(1), 96
rm -rf, 25 test, 128
root, 138, 148 Theo De Raadt, 7
root directory, 38 time, 109
rpm, 5 top, 189
RPM, 49 top(1), 187
touch(1), 24
S tr, 99
set, 82 tr(1), 98
set(shell), 69 Tru64, 8
set +x, 58 type(shell), 55
setfacl, 174
setgid, 170, 171 U
setuid, 148, 171, 171 Ubuntu, 4, 6, 8
set -x, 58 Ubuntu, Linux for Human Beings, 6
shell, 153 umask(1), 165
shell comment, 64 unalias(bash), 57
shell escaping, 64 Unbreakable Linux, 6
shell expansion, 58, 75 UNICS, 1
shopt, 131 uniq(1), 101
SIGHUP, 188 Unix, 1, 1
SIGTERM, 189 unset, 82
skeleton, 41 unset(shell), 69
sleep, 109 until loop (bash), 127
soft link, 179 updatedb(1), 107
Solaris, 8 usb, 48, 207
sort(1), 100 useradd, 139, 145
stderr, 89 useradd(1), 141, 145
stdin, 89, 95, 96 useradd -D, 139
stdout, 89, 95, 96 userdel(1), 139
sticky bit, 170 usermod, 156
strings(1), 34 usermod(1), 139, 143, 144
su -, 68
su(1), 147, 147 V
sudo, 148 vi(1), 115
sudo(1), 149 vigr(1), 158
sudo su -, 149 vim(1), 115
SunOS, 8 vimtutor(1), 115
Sun Solaris, 8 vipw(1), 144
Suse, 6 visudo(1), 149
swap partition(s), 48 vrije software, 4
symbolic link, 179
sysfs, 48 W
w(1), 136
215
Index
wc(1), 99
whatis(1), 12
whereis(1), 12
which(1), 56
while loop (bash), 126
who(1), 136
who am i, 136
whoami(1), 136
wild cards, 81
X
X, 41
Xen, 6
X Window System, 41
Z
zcat, 110
zmore, 110
zombie, 183
216