Virtual Machines: Dr. N. Rakesh Vice Chair - Dept - of CSE Amrita School of Engineering, Bengaluru
Virtual Machines: Dr. N. Rakesh Vice Chair - Dept - of CSE Amrita School of Engineering, Bengaluru
Dr. N. Rakesh
Vice chair - Dept.of CSE
Amrita School of Engineering, Bengaluru
1
Virtual Machine
2
Description
3
Virtualization
• Virtualization is an abstraction layer that
decouples the physical hardware from the
operating system to deliver greater IT resource
utilization and flexibility.
• It allows multiple virtual machines, with
heterogeneous operating systems to run in
isolation, side-by-side on the same physical
machine.
4
Virtualization contd..
5
History
6
Virtual Machine Monitor
• The host software
that provides
virtualization is often
referred to as a
virtual machine
monitor (VMM) or
hypervisor.
• The VMM gives each
virtual machine an
illusion of a complete
computer to itself.
7
8
Architecture
9
Features
• Each virtual machine has its own set of virtual hardware (e.g.,
RAM, CPU, NIC, etc.) upon which an operating system and
applications are loaded.
• The operating system sees a consistent, normalized set of
hardware regardless of the actual physical hardware
components.
10
Benefits
1. Partitioning
- Multiple applications and operating
systems can be supported within a single
physical system.
- There is no overlap amongst
memory as each Virtual Memory has its
own memory space.
11
Benefits
2.Isolation
• Virtual machines are completely
isolated from the host machine and
other virtual machines.
• If a virtual machine crashes, all others
are unaffected.
• Data does not leak across virtual
machines.
12
Summary
13
VirtualBox
• Virtual x86 machine(s)
– install other operating systems (OSs) running inside a
window, we’ll install Ubuntu (Linux) as a Guest OS
• Free application at https://www.virtualbox.org
Skip the
donation
page …
VirtualBox
• The file ubuntu-14.04.3-desktop-amd64.iso takes considerable time to
download (size: about 1GB)
• We don’t boot off real cds anymore; the .iso file is a special file that
can be interpreted as a virtual cd
• ISO images:
– Macs can mount ISO images.
– Macs can’t boot off a multitrack ISO image; hence the special
adm64+mac version.
– some versions of Windows can’t mount an ISO image (without extra
software). Install Microsoft’s Virtual CD-ROM Control Panel.
dynamically allocated
VirtualBox Disk Image
VirtualBox
• Need to add your .iso file in Settings > Storage:
Select your
downloaded
.iso file
VirtualBox
• Dynamically allocated virtual hard drive:
VirtualBox
VirtualBox
• Created Virtual Machine:
VirtualBox
VirtualBox
VirtualBox
• Step 3: start your virtual machine, install Ubuntu:
Ubuntu
Ubuntu
Ubuntu
Ubuntu
Ubuntu
Ubuntu
Ubuntu
• Virtual Box > Devices > Insert Guest Additions CD
Image …
Ubuntu
• Guest Additions:
Ubuntu
restart
Ubuntu
• After restart, login, System Settings > Details
Ubuntu
Ubuntu
Ubuntu
• Ubuntu Software Center
– App store
– (full screen to see Search box)
• Software packages
– Terminal: sudo apt-get install <pkg-name>
– sudo prefix: means execute the apt-get command with superuser privileges
(typically needed for packages)
• How to find Terminal: use search
Lock to Launcher
Ubuntu
• Terminal:
The shell has a programming language
– runs a shell: bash
– enter commands: some are built-in to the shell, others are executable
files in specified directories ($PATH), still others will require apt-get
– simple commands:
• pwd print working directory
• ls (ls -a) list current directory (-a option: show . (dot) files too)
• cd change directory
• mkdir create a new directory
• which name the directory where command name is located
• man name display manual page for command name
• echo $SHELL prints the shell ($ prefixes a variable)
– pre-defined environment variables: env dpkg –get-selections
– lots of packages are pre-loaded: wish, python, perl, etc.
COMPUTER ESSENTIALS
Basic Linux commands
1) pwd COMMAND:
pwd - Print Working Directory. pwd command prints the full filename of
the current working directory.
SYNTAX:
The Syntax is
pwd [options]
2) cd COMMAND:
cd command is used to change the directory.
SYNTAX:
The Syntax is
cd [directory | ~ | ./ | ../ | - ]
3) ls COMMAND:
ls command lists the files and directories under current working directory.
SYNTAX:
The Syntax is
ls [OPTIONS]... [FILE]
OPTIONS:
-l Lists all the files, directories and their mode, Number of links,
owner of the file, file size, Modified date and time and filename.
-t Lists in order of last modification time.
-a Lists all entries including hidden files.
-d Lists directory files instead of contents.
-p Puts slash at the end of each directories.
-u List in order of last access time.
-i Display inode information.
4) rm COMMAND:
rm linux command is used to remove/delete the file from the directory.
SYNTAX:
The Syntax is
rm [options..] [file | directory]
OPTIONS:
5) mv COMMAND:
mv command which is short for move. It is used to move/rename file
from one directory to another. mv command is different from cp command
as it completely removes the file from the source and moves to the directory
specified, where cp command just copies the content from one file to
another.
SYNTAX:
The Syntax is
mv [-f] [-i] oldname newname
OPTIONS:
-f This will not prompt before overwriting (equivalent to --
reply=yes). mv -f will move the file(s) without prompting even
if it is writing over an existing target.
-I Prompts before overwriting another file.
6) cat COMMAND:
cat linux command concatenates files and print it on the standard output.
SYNTAX:
The Syntax is
cat [OPTIONS] [FILE]...
OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
7) cmp COMMAND:
cmp linux command compares two files and tells you which line numbers are
different.
SYNTAX:
The Syntax is
cmp [options..] file1 file2
OPTIONS:
-c Output differing bytes as characters.
-l Print the byte number (decimal) and the differing byte values
(octal) for each difference.
-s Prints nothing for differing files, return exit status only.
8) cp COMMAND:
cp command copy files from one location to another. If the
destination is an existing file, then the file is overwritten; if the destination is
an existing directory, the file is copied into the directory (the directory is not
overwritten).
SYNTAX:
The Syntax is
cp [OPTIONS]... SOURCE DEST
9) echo COMMAND:
echo command prints the given input string to standard output.
SYNTAX:
The Syntax is
echo [options..] [string]
10)mkdir COMMAND:
mkdir command is used to create one or more directories.
SYNTAX:
The Syntax is
mkdir [options] directories
OPTIONS:
11) paste COMMAND:
paste command is used to paste the content from one file to another file. It is
also used to set column format for each line.
SYNTAX:
The Syntax is
paste [options]
OPTIONS:
16)whoami command
This command reveals the user who is currently logged in.
17)clear command
18)help option
With almost every command, ‘--help’ option shows usage summary for that
command.
$ date --help
This command gives a one line description about the command. It can be
used as a quick reference for any command.
$ whatis date
date (1) - print or set the system date and time
20)Manual Pages
$ man date
21)Info pages
Info documents are sometimes more elaborate than the man pages. But for some
commands, info pages are just the same as man pages. These are like web
pages. Internal links are present within the info pages. These links are called
nodes. Info pages can be navigated from one page to another through these
nodes.
$ info date
22) The touch command is a standard command used in UNIX/Linux operating
system which is used to create, change and modify timestamps of a file.
Basically, there are two different commands to create a file in the Linux system
which is as follows:
• cat command: It is used to create the file with content.
• touch command: It is used to create a file without any content. The file
created using touch command is empty. This command can be used when
the user doesn’t have data to store at the time of file creation.
touch file_name
touch File1_name File2_name File3_name
touch -a: This command is used to change access time only. To change or
update the last access or modification times of a file touch -a command is used.
Syntax:
touch -a fileName
touch -c : This command is used to check whether a file is created or not. If not
created then don’t create it. This command avoids creating files.
Syntax:
touch -c fileName
23. whoami
The whoami command tells you your username.
[root@RHEL5 ~]# whoami
Root
24. who
The who command will give you information about who is logged on the
system.
[paul@RHEL5 ~]$ who
root tty1 2008-06-24 13:24
sandra pts/0 2008-06-24 14:05 (192.168.1.34)
paul pts/1 2008-06-24 16:23 (192.168.1.37)
25.who am i
With who am i the who command will display only the line pointing to your
current
session.
[paul@RHEL5 ~]$ who am i
paul pts/1 2008-06-24 16:23 (192.168.1.34)
1) pwd COMMAND:
pwd - Print Working Directory. pwd command prints the full filename of
the current working directory.
SYNTAX:
The Syntax is
pwd [options]
2) cd COMMAND:
cd command is used to change the directory.
SYNTAX:
The Syntax is
cd [directory | ~ | ./ | ../ | - ]
cd .. -----> Take one directory previous to the current directory
cd ----> Take tp the hokme directory from then current directory.
3) ls COMMAND:
ls command lists the files and directories under current working directory.
SYNTAX:
The Syntax is
ls [OPTIONS]... [FILE]
OPTIONS:
-l Lists all the files, directories and their mode, Number of links,
owner of the file, file size, Modified date and time and filename.
-t Lists in order of last modification time.
-a Lists all entries including hidden files.
-d Lists directory files instead of contents.
-p Puts slash at the end of each directories.
-u List in order of last access time.
-i Display inode information.
4) rm COMMAND:
rm linux command is used to remove/delete the file from the directory.
SYNTAX:
The Syntax is
rm [options..] [file | directory]
OPTIONS:
5) mv COMMAND:
mv command which is short for move. It is used to move/rename file
from one directory to another. mv command is different from cp command
as it completely removes the file from the source and moves to the directory
specified, where cp command just copies the content from one file to
another.
SYNTAX:
The Syntax is
mv [-f] [-i] oldname newname
OPTIONS:
-f This will not prompt before overwriting (equivalent to --
reply=yes). mv -f will move the file(s) without prompting even
if it is writing over an existing target.
-I Prompts before overwriting another file.
6) cat COMMAND:
cat linux command concatenates files and print it on the standard output.
SYNTAX:
The Syntax is
cat [OPTIONS] [FILE]...
OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
7) cmp COMMAND:
cmp linux command compares two files and tells you which line numbers are
different.
SYNTAX:
The Syntax is
cmp [options..] file1 file2
OPTIONS:
8) cp COMMAND:
cp command copy files from one location to another. If the
destination is an existing file, then the file is overwritten; if the destination is
an existing directory, the file is copied into the directory (the directory is not
overwritten).
SYNTAX:
The Syntax is
cp [OPTIONS]... SOURCE DEST
9) echo COMMAND:
echo command prints the given input string to standard output.
SYNTAX:
The Syntax is
echo [options..] [string]
10)mkdir COMMAND:
mkdir command is used to create one or more directories.
SYNTAX:
The Syntax is
mkdir [options] directories
OPTIONS:
11) paste COMMAND:
paste command is used to paste the content from one file to another file. It is
also used to set column format for each line.
SYNTAX:
The Syntax is
paste [options]
OPTIONS:
16)whoami command
17)clear command
18)help option
With almost every command, ‘--help’ option shows usage summary for that
command.
$ date --help
This command gives a one line description about the command. It can be
used as a quick reference for any command.
$ whatis date
date (1) - print or set the system date and time
20)Manual Pages
$ man date
21)Info pages
Info documents are sometimes more elaborate than the man pages. But for some
commands, info pages are just the same as man pages. These are like web
pages. Internal links are present within the info pages. These links are called
nodes. Info pages can be navigated from one page to another through these
nodes.
$ info date
22) The touch command is a standard command used in UNIX/Linux operating
system which is used to create, change and modify timestamps of a file.
Basically, there are two different commands to create a file in the Linux system
which is as follows:
• cat command: It is used to create the file with content.
• touch command: It is used to create a file without any content. The file
created using touch command is empty. This command can be used when
the user doesn’t have data to store at the time of file creation.
touch file_name
touch File1_name File2_name File3_name
touch -a: This command is used to change access time only. To change or
update the last access or modification times of a file touch -a command is used.
Syntax:
touch -a fileName
touch -c : This command is used to check whether a file is created or not. If not
created then don’t create it. This command avoids creating files.
Syntax:
touch -c fileName
23. whoami
The whoami command tells you your username.
[root@RHEL5 ~]# whoami
Root
24. who
The who command will give you information about who is logged on the
system.
[paul@RHEL5 ~]$ who
root tty1 2008-06-24 13:24
sandra pts/0 2008-06-24 14:05 (192.168.1.34)
paul pts/1 2008-06-24 16:23 (192.168.1.37)
25.who am i
With who am i the who command will display only the line pointing to your
current
session.
[paul@RHEL5 ~]$ who am i
paul pts/1 2008-06-24 16:23 (192.168.1.34)
by
J. Glenn Brookshear
Dennis Brylow
• Batch processing
• Interactive processing
– Requires real-time processing
• Time-sharing/Multitasking
– Implemented by Multiprogramming
• Multiprocessor machines
• Application software
– Performs specific tasks for users
• System software
– Provides infrastructure for application software
– Consists of operating system and utility
software
Preamble
The course gives students an overview of computer science: A foundation from which they can appreciate
the relevance and interrelationships of further courses in the field. Computer Networks deals with
components and principles of networks and its protocols. Operating System acts as a platform of
information exchange between a computer's hardware and the applications running on it. Database
Management Systems have become a part of all computer based systems automating real word
applications to handle data storage. This course provides an insight on the general structures of operating
systems, database management systems and computer networks.
Prerequisite(s): NIL
Syllabus
Unit 1
Unit 2
Querying a database using simple SQL commands. Writing simple SQL queries. Creating and editing tables.
Creating indexes to improve performance. Exporting and importing data from/to database tables to/from
Excel.
Unit 3
Obtaining essential system network information using system tools: network interfaces and their
addresses, routing table, active processes using network communication. Basic network debugging: using
traceroute to discover route to a remote computer, ping to check network connectivity, nslookup for DNS
lookup. Understanding basic HTTP client and server using netcat. Using ssh and sftp.
TEXTBOOK:
1. Silberschatz A, Gagne G, Galvin PB. Operating system concepts. Ninth Edition, Wiley; 2012.
2. Cobbaut P. Linux Fundamentals. Samurai Media Limited; 2016.
3. Silberschatz A, Korth HF, Sudarshan S. Database system concepts. Sixth Edition, McGraw
Hill;2010.
4. Kurose JF, Ross KW. Computer networking: a top-down approach. Sixth Edition, Pearson;2013.
Course Outcomes
CO Statement Level
CO01 Understand the basic components of computer systems and its functionality. L2
CO02 Demonstrate the functions of operating system and its role as a resource manager to L2
execute any application
CO03 Understand the need for database storage and learn to retrieve using SQL. L2
CO04 Implement the connection between operating systems, computer networks and database L3
management through a case study
CO-PO Mapping
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
CO1 3 1 2 2 2
CO2 3 2 2 2 2
CO3 3 2 2 2 2
CO4 3 2 2 2 2 2 2 2
Tanenbaum, “Computer-
Networks”,5th-edition,
Prentice Hall
Tanenbaum, “Computer-
Networks”,5th-edition,
Prentice Hall
Lab Work: -- An observation Note book to be maintained by each student for the lab work and all
evaluations to be graded in that note book.
Tentative Evaluation Pattern: 65:35 (Internal: End Semester)
• For example: When you visit any website, they might store you IP address, that is
data, in return they might add a cookie in your browser, marking you that you visited
the website, that is data, your name, it's data, your age, it's data.
• Like, based on the cookie data saved on user's browser, if a website can analyze that
generally men of age 20-25 visit us more, that is information, derived from the data
collected.
• It's Complexity
• Except MySQL, which is open source, licensed
DBMSs are generally costly.
• They are large in size.
◼ Hardware –
the physical computer system that allows physical access to data.
◼ Software –
the actual program that allows users to access, maintain, and update
physical data.
◼ Data – stored physically on the storage devices
◼ Users –
End users - Normal user and DBA (Database Administrator)
Application programs
◼ Procedures –
a set of rules that should be clearly defined and followed by the users.
19-09-2019 19cse101 Computer Essentials Unit-II 14
Database Schema
• A database table is a collection of rows and columns that is used to organize information
about a single topic or object. Each row within a table corresponds to a single record and
contains several different attributes that describe the row.
• A database table is the most common and simplest form of data storage in a relational
database.
• Entity
• Object comprised of various pieces of data.
• Attribute
• Piece of information (data) that describes an
entity.
◼ An unary operation.
◼ Insert a new tuple into the relation.
◼ An unary operation.
◼ Delete a tuple defined by a criterion from the relation.
◼ An unary operation.
◼ Changes the value of some attributes of a tuple.
◼ An unary operation.
◼ It is applied to one single relation and creates another
relation.
◼ The tuples in the resulting relation are a subset of the tuples
in the original relation.
◼ Use some criteria to select
What is a Partition?
Disk Partition
IDE Disk Partitions
/dev/hda (Primary Master Disk)
/dev/hda1 (First Primary Partition)
/dev/hda2 (Second Primary Partition)
/dev/hdb (Primary Slave Partition)
/dev/hdb1
/dev/hdc (Secondary Master/Slave Partition)
/dev/hdc1
SCSI Disk Partitions
/dev/sda1, /dev/sda2
/dev/sdb1, /dev/sdb2
/dev/sdc1, /dev/sdc2
Commands to check hard disk
partitions and disk space on Linux
1. Fdisk
2. Sfdisk
3. Cfdisk
4. Parted
5. Df
6. Pydf
7. Lsblk
8. Blkid
9. hwinfo
1. fdisk
$ sudo fdisk -l
cfdisk /dev/sda
parted
• $ sudo parted -l
df
2
Data Vs. Information
Data : Data in computer terminology mean raw facts and figures.
For example,’Mohan’,1977,A . Data are processed to form
information.
Information : It means what we get after processing data (meaningful
data).
For example, ’Mohan, whose roll number is 1977, has got grade A’ is
an information as it is conveying some meaning.
This process of turning data into information is also known as
information processing.
FUNCTIONING OF A COMPUTER :
Certain input is needed to accomplish a task, a process is carried out on the
input to obtain the output.
Every process follows this Input-Process-Output cycle (IPO cycle).
Ex: c=a+b a=10,b=5 & c=15(output) or Paytm example
MAIN MEMORY
• Computer can understand only two stages ON/OFF or High/Low voltage or the binary language
that uses just two symbols : 1 for ON and 0 for OFF.
The Memory :
• Def : A memory cell may be defined as a device which can store a symbol selected from a set of
symbols. Each of these cells is further broken down into smaller parts known as bits.
• A bit means a binary digit. i.e., either 0 or 1.
• A bit is an element unit of the memory.
• Def. A group of 8 bits is called a byte and a group of 4 bits is called
a nibble.
• One byte is the smallest unit which can represent a data item or a
character.
• One KB(Kilobyte) -> 2¹º -> 1024 bytes.
• One MB(Megabyte) -> 2¹º KB -> 1024 x 1024 bytes.
• One GB(Gigabyte) -> 2¹º MB -> 1024 x 1024 x 1024 bytes.
• One TB(Terabyte) -> 2¹º GB -> 1024 x 1024 x 1024 x 1024 bytes.
• Two types of memory : (i) Volatile - > Primary Memory
(ii) Non Volatile -> Secondary Memory
12
2- Accuracy
The degree of accuracy of computer is very high and every calculation is performed
with the same accuracy.
The accuracy level is determined on the basis of design of computer.
The errors in computer are due to human and inaccurate data.
3- Diligence
A computer is a lack of concentration.
It can work for hours without creating any error
Due to this capability it overpowers human being in routine type of work.
13
4- Versatility
It means the capacity to perform completely different type of work.
5-Power of Remembering
Any amount of information can be stored in computer and recalled as
long as you require it, for any numbers of years.
It depends entirely upon you how much data you want to store in a
computer and when to lose or retrieve these data.
14
6- No IQ (intelligence quotient)
Computer is a dumb machine and it cannot do any work without instruction
from the user and it cannot take its own decision as you can.
7- No Feeling
It does not have feelings , it does not get tired even after long hours of work.
8- Storage
The Computer has an in-built memory where it can store a large amount of
data.
You can also store data in secondary storage devices such as floppies, CDs Flash
Memory which can be kept outside your computer and can be carried to other
computers.
15
COMPUTER SCIENCE
0-20
Abstraction
0-21
EVOLUTION OF COMPUTERS :
Abacus :
• Around 3000 years before the birth of Jesus Christ, the Mesopotamians
quite unknowingly laid the foundation of the computer era.
They discovered the earliest form of a bead-and-wire
counting machine, which subsequently came to be known
as abacus.
• An abacus consists of beads divided into two parts which are movable on the rods of the two parts. Addition and
multiplication etc. of numbers is done by using the place value of the digits of the numbers and position of beads
in the abacus.
Napier’s ‘Logs’ and ‘Bones’ :
John Napier (1550-1617) developed the idea of Logarithm. He used ‘logs’ to transform multiplication problem to
addition problem.
Pascal’s Adding Machine :
Blaise Pascal, a French mathematician, invented a machine in 1642 made up of gears which was used for adding
numbers quickly. This machine was named as Adding Machine ( Pascaline ) and was capable of addition and
subtraction.
The adding machine
consisted of numbered
toothed wheels having
unique position values. The
rotation of wheels
controlled the addition and
subtraction operations.
Leibnitz’s Calculator :
Gottfried Leibnitz, a German Mathematician,
improved an adding machine and
constructed a new machine in 1671 that was
able to perform multiplication and division
as well. This machine performed
multiplication through repeated addition of
numbers.
• Leibnitz’z machine used stepped cylinder each with nine teeth of varying lengths instead of wheels
as was used by Pascal.
Jacquard’s Loom :
• Joseph Jacquard manufactured punched cards at the end of American revolution and
used them to control looms in 1801. Thus the entire control weaving process was
automatic.
• The entire operation was under a program’s control.
Intelligent robots
Intelligent system that could control the route of a missile and defense systems
that could fend off attacks
3. Minicomputers :
Also called mid range servers
More powerful than micro computers in terms of processing power and
capabilities.
Multiuser system (Multi users can work simultaneously)
Greater storage capacity and larger memories compared to micro
comp.
Capable of handling more i/p and o/p devices.
Examples : PDP-11, VAX, 7500 MAGNUM etc.
4. Mainframe Computers :
Designed to handle huge volumes of data and information.
Can support more than 100 users at same time
Large and expensive
Great processing speeds and very large storage capacity and
memory as compared to mini comp.
Possess and work with more than one processor at the same time
Very sophisticated operating systems are needed to control and
supervise their operations.
Examples : ICL 39, CDC 6600, VAX 8842, IBM 3090/600, IBM 4381
5. Super Computers :
Most powerful among the digital computers
Consist of several processors running together, so
very powerful and faster
Capable of handling huge amounts of calculations
It can perform billions of instructions per second
Today’s some super computers have the computing
capability equal to that of 40,000 micro computers
These computers cost in 15-20 million dollar range.
Used for weather forecasting, nuclear science
research, aerodynamic modelling, seismology,
metrology etc.
Examples : CRAY X-MP-14, CDC-205, ETA GF-10,
FUJITSU VP-400, NEC SX-2, PARAM, PACE
Fro general purpose applications, supercomputers
do not make the ideal choice.
It can process information of only a certain kind.
Super computers
Its power measured in flops (floating point operations per second)
Analog Computers :
As input continuous quantities are used
Computations are carried out with physical quantities such as voltage, length,
current, temperature etc.
Operate by measuring rather than counting
All calculations take place in parallel and hence are faster
Accuracy is poor as compared to digital comp.
Mostly used in engg. And sci. applications.
Example : An electronic weighing scale
Hybrid Computers :
Utilize the best qualities of both the digital and analog comp.
Some calculations take place in analog manner and rest of them take place in
digital manner
Best used in Hospitals, also used for weather forecasting
QUIZ
• One mega byte is equivalent to?
1. 210 bytes
2. 220 bytes
3. 230 bytes
4. None of these
• Which of the following are parts of the CPU?
1. ALU
2. Memory
3. CU
4. Input device
5. Main Memory
• Which of the following is not hardware?
1. Hard Disk
2. Printer
3. Keyboard
4. CPU
5. Assembler
6. Program to print table of 13
• Which of the following are parts of the CPU?
1. ALU
2. Memory
3. CU
4. Input device
5. Main Memory
• The modern age of data processing began with the competition of the computer?
1. Analytical Engine
2. ENIAC
3. MARK 1
4. UNIVAC I
• A Micro processor is
1. A solid state device
2. Capable of performing Arithmetic operations
3. Capable of performing Logical operations
4. All the above
• In computer science ,by information we mean
1. Any output coming out from computer
2. Processed data put out from computer
3. A report printed by computer
4. Plural of data
• The CPU
1. Is operated from the control panel
2. Is controlled by the input data entering the system
3. Controls the storage unit
4. Controls all input , output, processing
• A data is a collection of-
1. Raw facts
2. Processing
3. Transformations
4. None of these
• Which of the following are software and hardware?
1. Transistor
2. FORTON
3. Compiler
4. Integrated Circuit
• Who invented the punched card?
1. Charles Babbage
2. Herman Hollerith
3. Both 1 and 2
4. None of these
• Define each of the following-
1. Nibble
2. Byte
3. Kilobyte
4. Megabyte
5. Gigabyte
6. Tetra byte
• Which of the following does not represent an I/O device?
1. Speaker which beeps
2. Plotter
3. Joystick
4. ALU
• Storage of 1 KB means the following number of bytes-
1. 1000
2. 964
3. 1024
4. 1064
Linux Fundamentals
Paul Cobbaut
Linux Fundamentals
Paul Cobbaut
lt-2.0
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.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free
Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no
Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section
entitled 'GNU Free Documentation License'.
Table of Contents
I. introduction to Linux ........................................................................................ 1
1. Linux history ............................................................................................... 2
2. distributions ................................................................................................. 4
3. licensing ...................................................................................................... 6
4. getting Linux at home ............................................................................... 10
II. first steps on the command line .................................................................... 21
5. man pages ................................................................................................. 22
6. working with directories ........................................................................... 26
7. working with files ..................................................................................... 35
8. working with file contents ........................................................................ 44
9. the Linux file tree ..................................................................................... 51
III. shell expansion .............................................................................................. 72
10. commands and arguments ....................................................................... 73
11. control operators ..................................................................................... 83
12. variables .................................................................................................. 89
13. shell history ........................................................................................... 100
14. file globbing .......................................................................................... 106
IV. pipes and commands .................................................................................. 113
15. redirection and pipes ............................................................................. 114
16. filters ..................................................................................................... 123
17. basic Unix tools .................................................................................... 136
V. vi ..................................................................................................................... 145
18. Introduction to vi .................................................................................. 146
VI. scripting ....................................................................................................... 156
19. scripting introduction ............................................................................ 157
20. scripting loops ....................................................................................... 163
21. scripting parameters .............................................................................. 170
22. more scripting ....................................................................................... 178
VII. local user management ............................................................................. 186
23. users ...................................................................................................... 187
24. groups .................................................................................................... 207
VIII. file security ............................................................................................... 213
25. standard file permissions ...................................................................... 214
26. advanced file permissions ..................................................................... 225
27. access control lists ................................................................................ 231
28. file links ................................................................................................ 235
IX. Appendices ................................................................................................... 242
A. certifications ........................................................................................... 243
B. keyboard settings .................................................................................... 245
C. hardware ................................................................................................. 247
Index .................................................................................................................... 251
iii
List of Tables
18.1. getting to command mode ......................................................................... 147
18.2. switch to insert mode ................................................................................. 147
18.3. replace and delete ...................................................................................... 148
18.4. undo and repeat .......................................................................................... 148
18.5. cut, copy and paste a line .......................................................................... 148
18.6. cut, copy and paste lines ............................................................................ 149
18.7. start and end of line ................................................................................... 149
18.8. join two lines ............................................................................................. 149
18.9. words .......................................................................................................... 150
18.10. save and exit vi ........................................................................................ 150
18.11. searching .................................................................................................. 151
18.12. replace ...................................................................................................... 151
18.13. read files and input .................................................................................. 151
18.14. text buffers ............................................................................................... 152
18.15. multiple files ............................................................................................ 152
18.16. abbreviations ............................................................................................ 152
23.1. Debian User Environment .......................................................................... 206
23.2. Red Hat User Environment ........................................................................ 206
25.1. Unix special files ....................................................................................... 216
25.2. standard Unix file permissions .................................................................. 217
25.3. Unix file permissions position ................................................................... 217
25.4. Octal permissions ....................................................................................... 220
iv
Part I. introduction to Linux
Chapter 1. Linux history
Table of Contents
1.1. Linux history .................................................................................................... 3
This chapter briefly tells the history of Unix and where Linux fits in.
If you are eager to start working with Linux without this blah, blah, blah over history,
distributions, and licensing then jump straight to Part II - Chapter 6. Working with
Directories page 26.
2
Linux history
In the Eighties many companies started developing their own Unix: IBM created
AIX, Sun SunOS (later Solaris), HP HP-UX and about a dozen other companies did
the same. The result was a mess of Unix dialects and a dozen different ways to do the
same thing. And here is the first real root of Linux, when Richard Stallman aimed
to end this era of Unix separation and everybody re-inventing the wheel by starting
the GNU project (GNU is Not Unix). His goal was to make an operating system that
was freely available to everyone, and where everyone could work together (like in the
Seventies). Many of the command line tools that you use today on Linux or Solaris
are GNU tools.
The Nineties started with Linus Torvalds, a Swedish speaking Finnish student,
buying a 386 computer and writing a brand new POSIX compliant kernel. He put
the source code online, thinking it would never support anything but 386 hardware.
Many people embraced the combination of this kernel with the GNU tools, and the
rest, as they say, is history.
Today more than 90 percent of supercomputers (including the complete top 10), more
than half of all smartphones, many millions of desktop computers, around 70 percent
of all web servers, a large chunk of tablet computers, and several appliances (dvd-
players, washing machines, dsl modems, routers, ...) run Linux. It is by far the most
commonly used operating system in the world.
Linux kernel version 3.2 was released in January 2012. Its source code grew by almost
two hundred thousand lines (compared to version 3.1) thanks to contributions of over
4000 developers paid by about 200 commercial companies including Red Hat, Intel,
Broadcom, Texas Instruments, IBM, Novell, Qualcomm, Samsung, Nokia, Oracle,
Google and even Microsoft.
http://en.wikipedia.org/wiki/Dennis_Ritchie
http://en.wikipedia.org/wiki/Richard_Stallman
http://en.wikipedia.org/wiki/Linus_Torvalds
http://kernel.org
http://lwn.net/Articles/472852/
http://www.linuxfoundation.org/
http://en.wikipedia.org/wiki/Linux
http://www.levenez.com/unix/ (a huge Unix history poster)
3
Chapter 2. distributions
Table of Contents
2.1. Red Hat ............................................................................................................ 5
2.2. Ubuntu .............................................................................................................. 5
2.3. Debian .............................................................................................................. 5
2.4. Other ................................................................................................................ 5
2.5. Which to choose ? ........................................................................................... 5
4
distributions
2.2. Ubuntu
Canonical started sending out free compact discs with Ubuntu Linux in 2004 and
quickly became popular for home users (many switching from Microsoft Windows).
Canonical wants Ubuntu to be an easy to use graphical Linux desktop without need
to ever see a command line. Of course they also want to make a profit by selling
support for Ubuntu.
2.3. Debian
There is no company behind Debian. Instead there are thousands of well organised
developers that elect a Debian Project Leader every two years. Debian is seen as one
of the most stable Linux distributions. It is also the basis of every release of Ubuntu.
Debian comes in three versions: stable, testing and unstable. Every Debian release is
named after a character in the movie Toy Story.
2.4. Other
Distributions like CentOS, Oracle Enterprise Linux and Scientific Linux are based
on Red Hat Enterprise Linux and share many of the same principles, directories and
system administration techniques. Linux Mint, Edubuntu and many other *buntu
named distributions are based on Ubuntu and thus share a lot with Debian. There are
hundreds of other Linux distributions.
5
Chapter 3. licensing
Table of Contents
3.1. about software licenses .................................................................................... 7
3.2. public domain software and freeware .............................................................. 7
3.3. Free Software or Open Source Software ......................................................... 8
3.4. GNU General Public License .......................................................................... 8
3.5. using GPLv3 software ..................................................................................... 8
3.6. BSD license ..................................................................................................... 9
3.7. other licenses ................................................................................................... 9
3.8. combination of software licenses ..................................................................... 9
This chapter briefly explains the different licenses used for distributing operating
systems software.
Many thanks go to Ywein Van den Brande for writing most of this chapter.
Ywein is an attorney at law, co-author of The International FOSS Law Book and
author of Praktijkboek Informaticarecht (in Dutch).
http://ifosslawbook.org
http://www.crealaw.eu
6
licensing
Legal theory states that the author of FOSS, contrary to the author of public domain
software, has in no way whatsoever given up his rights on his work. FOSS supports on
the rights of the author (the copyright) to impose FOSS license conditions. The FOSS
license conditions need to be respected by the user in the same way as proprietary
license conditions. Always check your license carefully before you use third party
software.
Examples of proprietary software are AIX from IBM, HP-UX from HP and Oracle
Database 11g. You are not authorised to install or use this software without paying a
licensing fee. You are not authorised to distribute copies and you are not authorised
to modify the closed source code.
Public domain software is considered as software to which the author has given up all
rights and on which nobody is able to enforce any rights. This software can be used,
reproduced or executed freely, without permission or the payment of a fee. Public
domain software can in certain cases even be presented by third parties as own work,
and by modifying the original work, third parties can take certain versions of the
public domain software out of the public domain again.
Freeware is not public domain software or FOSS. It is proprietary software that you
can use without paying a license cost. However, the often strict license terms need
to be respected.
Examples of freeware are Adobe Reader, Skype and Command and Conquer:
Tiberian Sun (this game was sold as proprietary in 1999 and is since 2011 available
as freeware).
7
licensing
Recently, the term free and open source software or FOSS has arisen as a neutral
alternative. A lesser-used variant is free/libre/open source software (FLOSS), which
uses libre to clarify the meaning of free as in freedom rather than as in at no charge.
The above definition is based on the Debian Free Software Guidelines available
here:
http://www.debian.org/social_contract#guidelines
8
licensing
In case you use the software internally (including over a network), you may modify
the software without being obliged to distribute your modification. You may hire
third parties to work on the software exclusively for you and under your direction and
control. But if you modify the software and use it otherwise than merely internally,
this will be considered as distribution. You must distribute your modifications under
GPLv3 (the copyleft principle). Several more obligations apply if you distribute
GPLv3 software. Check the GPLv3 license carefully.
You create output with GPLv3 software: The GPLv3 does not automatically apply
to the output.
This is a permissive free software license. The license places minimal restrictions on
how the software can be redistributed. This is in contrast to copyleft licenses such as
the GPLv. 3 discussed above, which have a copyleft mechanism.
This difference is of less importance when you merely use the software, but kicks in
when you start redistributing verbatim copies of the software or your own modified
versions.
9
Chapter 4. getting Linux at home
Table of Contents
4.1. download a Linux CD image ......................................................................... 11
4.2. download Virtualbox ..................................................................................... 11
4.3. create a virtual machine ................................................................................. 12
4.4. attach the CD image ...................................................................................... 17
4.5. install Linux ................................................................................................... 20
This book assumes you have access to a working Linux computer. Most companies
have one or more Linux servers, if you have already logged on to it, then you 're all
set (skip this chapter and go to the next).
If you do not have access to a Linux computer at the moment, and if you are unable
or unsure about installing Linux on your computer, then this chapter proposes a third
option: installing Linux in a virtual machine.
This chapter gives easy steps and screenshots to get a working Ubuntu server in a
Virtualbox virtual machine. The steps are very similar to installing Fedora or CentOS
or even Debian, and if you like you can also use VMWare instead of Virtualbox.
10
getting Linux at home
11
getting Linux at home
Click New to create a new virtual machine. We will walk together through the wizard.
The screenshots below are taken on Mac OSX; they will be slightly different if you
are running Microsoft Windows.
12
getting Linux at home
Give the virtual machine some memory (512MB if you have 2GB or more, otherwise
select 256MB).
13
getting Linux at home
14
getting Linux at home
15
getting Linux at home
16
getting Linux at home
Do not worry if your screen looks different, just find the button named storage.
17
getting Linux at home
Remember the .ISO file you downloaded? Connect this .ISO file to this virtual
machine by clicking on the CD icon next to Empty.
Now click on the other CD icon and attach your ISO file to this virtual CD drive.
18
getting Linux at home
Verify that your download is accepted. If Virtualbox complains at this point, then
you probably did not finish the download of the CD (try downloading it again).
It could be useful to set the network adapter to bridge instead of NAT. Bridged usually
will connect your virtual computer to the Internet.
19
getting Linux at home
20
Part II. first steps on
the command line
Chapter 5. man pages
Table of Contents
5.1. man $command .............................................................................................. 23
5.2. man $configfile .............................................................................................. 23
5.3. man $daemon ................................................................................................. 23
5.4. man -k (apropos) ............................................................................................ 23
5.5. whatis ............................................................................................................. 23
5.6. whereis ........................................................................................................... 24
5.7. man sections ................................................................................................... 24
5.8. man $section $file .......................................................................................... 24
5.9. man man ........................................................................................................ 24
5.10. mandb ........................................................................................................... 25
This chapter will explain the use of man pages (also called manual pages) on your
Unix or Linux computer.
You will learn the man command together with related commands like whereis,
whatis and mandb.
Most Unix files and commands have pretty good man pages to explain their use. Man
pages also come in handy when you are using multiple flavours of Unix or several
Linux distributions since options and parameters sometimes vary.
22
man pages
5.5. whatis
To see just the description of a manual page, use whatis followed by a string.
23
man pages
5.6. whereis
The location of a manpage can be revealed with whereis.
24
man pages
5.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.
25
Chapter 6. working with directories
Table of Contents
6.1. pwd ................................................................................................................. 27
6.2. cd .................................................................................................................... 27
6.3. absolute and relative paths ............................................................................. 28
6.4. path completion .............................................................................................. 29
6.5. ls ..................................................................................................................... 29
6.6. mkdir .............................................................................................................. 31
6.7. rmdir ............................................................................................................... 31
6.8. practice: working with directories ................................................................. 32
6.9. solution: working with directories ................................................................. 33
To explore the Linux file tree, you will need some basic tools.
This chapter is small overview of the most common commands to work with
directories : pwd, cd, ls, mkdir, rmdir. These commands are available on any Linux
(or Unix) system.
This chapter also discusses absolute and relative paths and path completion in the
bash shell.
26
working with directories
6.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
6.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
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
To stay in the current directory, type cd . ;-) We will see useful use of the . character
representing the current directory later.
27
working with directories
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
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$ pwd
/
paul@laika$ cd home
paul@laika$ pwd
/home
paul@laika$ cd /
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.
28
working with directories
You will need fewer key strokes when using the tab key, and you will be sure your
typed path is correct!
6.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:~$
ls -a
A frequently used option with ls is -a to show all files. Showing all files means
including the hidden files. When a file name 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.
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
29
working with directories
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
-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 -h -l
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
30
working with directories
6.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 / .
paul@laika:~$ mkdir MyDir
paul@laika:~$ cd MyDir
paul@laika:~/MyDir$ ls -al
total 8
drwxr-xr-x 2 paul paul 4096 2007-01-10 21:13 .
drwxr-xr-x 39 paul paul 4096 2007-01-10 21:13 ..
paul@laika:~/MyDir$ mkdir stuff
paul@laika:~/MyDir$ mkdir otherstuff
paul@laika:~/MyDir$ ls -l
total 8
drwxr-xr-x 2 paul paul 4096 2007-01-10 21:14 otherstuff
drwxr-xr-x 2 paul paul 4096 2007-01-10 21:14 stuff
paul@laika:~/MyDir$
mkdir -p
When given the option -p, then mkdir will create parent directories as needed.
paul@laika:~$ mkdir -p MyDir2/MySubdir2/ThreeDeep
paul@laika:~$ ls MyDir2
MySubdir2
paul@laika:~$ ls MyDir2/MySubdir2
ThreeDeep
paul@laika:~$ ls MyDir2/MySubdir2/ThreeDeep/
6.7. rmdir
When a directory is empty, you can use rmdir to remove the directory.
paul@laika:~/MyDir$ rmdir otherstuff
paul@laika:~/MyDir$ ls
stuff
paul@laika:~/MyDir$ cd ..
paul@laika:~$ rmdir MyDir
rmdir: MyDir/: Directory not empty
paul@laika:~$ rmdir MyDir/stuff
paul@laika:~$ rmdir MyDir
rmdir -p
And similar to the mkdir -p option, you can also use rmdir to recursively remove
directories.
paul@laika:~$ mkdir -p dir/subdir/subdir2
paul@laika:~$ rmdir -p dir/subdir/subdir2
paul@laika:~$
31
working with directories
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 these commands.
32
working with directories
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.
33
working with directories
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 these commands.
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$
34
Chapter 7. working with files
Table of Contents
7.1. all files are case sensitive .............................................................................. 36
7.2. everything is a file ......................................................................................... 36
7.3. file .................................................................................................................. 36
7.4. touch ............................................................................................................... 37
7.5. rm ................................................................................................................... 37
7.6. cp .................................................................................................................... 38
7.7. mv .................................................................................................................. 39
7.8. rename ............................................................................................................ 40
7.9. practice: working with files ........................................................................... 41
7.10. solution: working with files ......................................................................... 42
In this chapter we learn how to recognise, create, remove, copy and move files using
commands like file, touch, rm, cp, mv and rename.
35
working with files
This screenshot shows the difference between two files, one with upper case W, the
other with lower case 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!
7.3. 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.
paul@laika:~$ file pic33.png
pic33.png: PNG image data, 3840 x 1200, 8-bit/color RGBA, non-interlaced
paul@laika:~$ file /etc/passwd
/etc/passwd: ASCII text
paul@laika:~$ file HelloWorld.c
HelloWorld.c: ASCII C program text
The file command uses a magic file that contains patterns to recognise file types.
The magic file is located in /usr/share/file/magic. Type man 5 magic for more
information.
It is interesting to point out file -s for special files like those in /dev and /proc.
root@debian6~# file /dev/sda
/dev/sda: block special
root@debian6~# file -s /dev/sda
/dev/sda: x86 boot sector; partition 1: ID=0x83, active, starthead...
root@debian6~# file /proc/cpuinfo
/proc/cpuinfo: empty
root@debian6~# file -s /proc/cpuinfo
/proc/cpuinfo: ASCII C++ program text
36
working with files
7.4. touch
One easy way to create a file is with touch. (We will see many other ways for creating
files later in this book.)
paul@laika:~/test$ touch file1
paul@laika:~/test$ touch file2
paul@laika:~/test$ touch file555
paul@laika:~/test$ ls -l
total 0
-rw-r--r-- 1 paul paul 0 2007-01-10 21:40 file1
-rw-r--r-- 1 paul paul 0 2007-01-10 21:40 file2
-rw-r--r-- 1 paul paul 0 2007-01-10 21:40 file555
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.
paul@laika:~/test$ touch -t 200505050000 SinkoDeMayo
paul@laika:~/test$ touch -t 130207111630 BigBattle
paul@laika:~/test$ ls -l
total 0
-rw-r--r-- 1 paul paul 0 1302-07-11 16:30 BigBattle
-rw-r--r-- 1 paul paul 0 2005-05-05 00:00 SinkoDeMayo
7.5. 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 trash can 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.
paul@laika:~/Linux$ touch brel.txt
paul@laika:~/Linux$ rm -i brel.txt
rm: remove regular empty file `brel.txt'? y
paul@laika:~/Linux$
37
working with files
rm -rf
By default, rm -r 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.
You can literally erase your entire file system by accident.
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
7.6. 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.
paul@laika:~/test$ touch FileA
paul@laika:~/test$ ls
FileA
paul@laika:~/test$ cp FileA FileB
paul@laika:~/test$ ls
FileA FileB
paul@laika:~/test$ mkdir MyDir
paul@laika:~/test$ ls
FileA FileB MyDir
paul@laika:~/test$ cp FileA MyDir/
paul@laika:~/test$ ls MyDir/
FileA
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
38
working with files
cp -i
To prevent cp from overwriting existing files, use the -i (for interactive) option.
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
7.7. 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.
39
working with files
7.8. 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 file names ending in .txt. The second example
switches all occurrences of upper case ABC in lower case abc for all file names 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
paul@laika:~/test$ rename 's/txt/png/' *.txt
paul@laika:~/test$ ls
123.png ABC.png
paul@laika:~/test$ rename 's/ABC/abc/' *.png
paul@laika:~/test$ ls
123.png abc.png
paul@laika:~/test$
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]$
40
working with files
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!)
41
working with files
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 ?
42
working with files
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
43
Chapter 8. working with file contents
Table of Contents
8.1. head ................................................................................................................ 45
8.2. tail .................................................................................................................. 45
8.3. cat ................................................................................................................... 46
8.4. tac ................................................................................................................... 47
8.5. more and less ................................................................................................. 48
8.6. strings ............................................................................................................. 48
8.7. practice: file contents ..................................................................................... 49
8.8. solution: file contents ..................................................................................... 50
In this chapter we will look at the contents of text files with head, tail, cat, tac, more,
less and strings.
We will also get a glimpse of the possibilities of tools like cat on the command line.
44
working with file contents
8.1. head
You can use head to display the first ten lines of a file.
paul@laika:~$ head /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
paul@laika:~$
The head command can also display the first n lines of a file.
paul@laika:~$ head -4 /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
8.2. tail
Similar to head, the tail command will display the last ten lines of a file.
paul@laika:~$ tail /etc/services
vboxd 20012/udp
binkp 24554/tcp # binkp fidonet protocol
asp 27374/tcp # Address Search Protocol
asp 27374/udp
csync2 30865/tcp # cluster synchronization tool
dircproxy 57000/tcp # Detachable IRC Proxy
tfido 60177/tcp # fidonet EMSI over telnet
fido 60179/tcp # fidonet EMSI over TCP
# Local services
paul@laika:~$
You can give tail the number of lines you want to see.
$ tail -3 count.txt
six
seven
eight
The tail command has other useful options, some of which we will use during this
course.
45
working with file contents
8.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.
paul@laika:~$ cat /etc/resolv.conf
nameserver 194.7.1.4
paul@laika:~$
concatenate
cat is short for concatenate. One of the basic uses of cat is to concatenate files into
a bigger (or complete) file.
paul@laika:~$ echo one > part1
paul@laika:~$ echo two > part2
paul@laika:~$ echo three > part3
paul@laika:~$ cat part1 part2 part3
one
two
three
paul@laika:~$
create files
You can use cat to create flat text files. Type the cat > winter.txt 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.
paul@laika:~/test$ cat > winter.txt
It is very cold today!
paul@laika:~/test$ cat winter.txt
It is very cold today!
paul@laika:~/test$
The Ctrl d key combination will send an EOF (End of File) to the running process
ending the cat command.
46
working with file contents
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.
paul@laika:~/test$ cat winter.txt
It is very cold today!
paul@laika:~/test$ cat winter.txt > cold.txt
paul@laika:~/test$ cat cold.txt
It is very cold today!
paul@laika:~/test$
8.4. tac
Just one example will show you the purpose of tac (as the opposite of cat).
paul@laika:~/test$ cat count
one
two
three
four
paul@laika:~/test$ tac count
four
three
two
one
paul@laika:~/test$
47
working with file contents
8.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
__gmon_start__
_Jv_RegisterClasses
clock_gettime
libacl.so.1
...
48
working with file contents
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).
10. Open two terminal windows (or tabs) and make sure you are in the same directory
in both. Type echo this is the first line > tailing.txt in the first terminal, then issue
tail -f tailing.txt in the second terminal. Now go back to the first terminal and type
echo This is another line >> tailing.txt (note the double >>), verify that the tail -f
in the second terminal shows both lines. Stop the tail -f with Ctrl-C.
11. Use cat to create a file named tailing.txt that contains the contents of tailing.txt
followed by the contents of /etc/passwd.
12. Use cat to create a file named tailing.txt that contains the contents of tailing.txt
preceded by the contents of /etc/passwd.
49
working with file contents
3. Use cat to create a file named count.txt that looks like this:
cat > count.txt
One
Two
Three
Four
Five (followed by Ctrl-d)
6. Display catcnt.txt, but with all lines in reverse order (the last line first).
tac catcnt.txt
10. Open two terminal windows (or tabs) and make sure you are in the same directory
in both. Type echo this is the first line > tailing.txt in the first terminal, then issue
tail -f tailing.txt in the second terminal. Now go back to the first terminal and type
echo This is another line >> tailing.txt (note the double >>), verify that the tail -f
in the second terminal shows both lines. Stop the tail -f with Ctrl-C.
11. Use cat to create a file named tailing.txt that contains the contents of tailing.txt
followed by the contents of /etc/passwd.
cat /etc/passwd >> tailing.txt
12. Use cat to create a file named tailing.txt that contains the contents of tailing.txt
preceded by the contents of /etc/passwd.
mv tailing.txt tmp.txt ; cat /etc/passwd tmp.txt > tailing.txt
50
Chapter 9. the Linux file tree
Table of Contents
9.1. filesystem hierarchy standard ........................................................................ 52
9.2. man hier ......................................................................................................... 52
9.3. the root directory / ......................................................................................... 52
9.4. binary directories ........................................................................................... 53
9.5. configuration directories ................................................................................ 55
9.6. data directories ............................................................................................... 57
9.7. in memory directories .................................................................................... 59
9.8. /usr Unix System Resources .......................................................................... 64
9.9. /var variable data ............................................................................................ 66
9.10. practice: file system tree .............................................................................. 68
9.11. solution: file system tree .............................................................................. 70
This chapters takes a look at the most common directories in the Linux file tree. It
also shows that on Unix everything is a file.
51
the Linux file tree
[paul@RHELv4u3 ~]$ ls /
bin dev home media mnt proc sbin srv tftpboot usr
boot etc lib misc opt root selinux sys tmp var
52
the Linux file tree
/bin
The /bin directory contains binaries for use by all users. According to the FHS the /
bin directory should contain /bin/cat and /bin/date (among others).
In the screenshot below you see common Unix/Linux commands like cat, cp, cpio,
date, dd, echo, grep, and so on. Many of these will be covered in this book.
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
...
Some applications, often when installed directly from source will put themselves in
/opt. A samba server installation can use /opt/samba/bin to store its binaries.
/sbin
/sbin contains binaries to configure the operating system. Many of the system
binaries require root privilege to perform certain tasks.
53
the Linux file tree
/lib
Binaries found in /bin and /sbin often use shared libraries located in /lib. Below is
a screenshot of the partial contents of /lib.
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
Typically, the Linux kernel loads kernel modules from /lib/modules/$kernel-
version/. This directory is discussed in detail in the Linux kernel chapter.
The ELF (Executable and Linkable Format) is used in almost every Unix-like
operating system since System V.
/opt
The purpose of /opt is to store optional software. In many cases this is software from
outside the distribution repository. You may find an empty /opt directory on many
systems.
A large package can install all its files in /bin, /lib, /etc subdirectories within /opt/
$packagename/. If for example the package is called wp, then it installs in /opt/wp,
putting binaries in /opt/wp/bin and manpages in /opt/wp/man.
54
the Linux file tree
/boot
The /boot directory contains all files needed to boot the computer. These files don't
change very often. On Linux systems you typically find the /boot/grub directory
here. /boot/grub contains /boot/grub/grub.cfg (older systems may still have /boot/
grub/grub.conf) which defines the boot menu that is displayed before the kernel
starts.
/etc
All of the machine-specific configuration files should be located in /etc. Historically
/etc stood for etcetera, today people often use the Editable Text Configuration
backronym.
Many times the name of a configuration files is the same as the application, daemon,
or protocol with .conf added as the extension.
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/init.d/
A lot of Unix/Linux distributions have an /etc/init.d directory that contains scripts to
start and stop daemons. This directory could disappear as Linux migrates to systems
that replace the old init way of starting all daemons.
/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.
55
the Linux file tree
/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
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.
paul@RHELv4u4:~$ cat /etc/sysconfig/firstboot
RUN_FIRSTBOOT=NO
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/.
root@RHELv4u4:/etc/sysconfig# cat keyboard
KEYBOARDTYPE="pc"
KEYTABLE="us"
56
the Linux file tree
/home
Users can store personal or project data under /home. It is common (but not
mandatory by the fhs) practice to name the users home directory after the user name
in the format /home/$USERNAME. For example:
paul@ubu606:~$ ls /home
geert annik sandra 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 file name starts with a dot).
The hidden files of the Unix user profiles contain settings specific for that user.
paul@ubu606:~$ 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
/root
On many systems /root is the default location for personal data and profile of the
root user. If it does not exist by default, then some administrators create it.
/srv
You may use /srv for data that is served by your system. The FHS allows locating
cvs, rsync, ftp and www data in this location. The FHS also approves administrative
naming in /srv, like /srv/project55/ftp and /srv/sales/www.
On Sun Solaris (or Oracle Solaris) /export is used for this purpose.
/media
The /media directory serves as a mount point for removable media devices such as
CD-ROM's, digital cameras, and various usb-attached devices. Since /media is rather
new in the Unix world, you could very well encounter systems running without this
directory. Solaris 9 does not have it, Solaris 10 does. Most Linux distributions today
mount all removable media in /media.
paul@debian5:~$ ls /media/
cdrom cdrom0 usbdisk
57
the Linux file tree
/mnt
The /mnt directory should be empty and should only be used for temporary mount
points (according to the FHS).
Unix and Linux administrators used to create many directories here, like /mnt/
something/. You likely will encounter many systems with more than one directory
created and/or mounted inside /mnt to be used for various local and remote
filesystems.
/tmp
Applications and users should use /tmp to store temporary data when needed. Data
stored in /tmp may use either disk space or RAM. Both of which are managed by
the operating system. Never use /tmp to store data that is important or which you
wish to archive.
58
the Linux file tree
/dev
Device files in /dev appear to be ordinary files, but are not actually located on the hard
disk. The /dev directory is populated with files as the kernel is recognising hardware.
Common hardware such as hard disk devices are represented by device files in /dev.
Below a screenshot of SATA device files on a laptop and then IDE attached drives
on a desktop. (The detailed meaning of these devices will be discussed later.)
#
# SATA or SCSI or USB
#
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.
For example, /dev/tty1 represents a terminal or console attached to the system. (Don't
break your head on the exact terminology of 'terminal' or 'console', what we mean
here is a command line interface.) When typing commands in a terminal that is part
of a graphical interface like Gnome or KDE, then your terminal will be represented
as /dev/pts/1 (1 can be another number).
/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 ;-).
59
the Linux file 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
2 45 5380 6430 7189 acpi locks vmnet
20845 4542 5412 6450 7191 asound meminfo vmstat
221 46 5414 6551 7192 buddyinfo misc zoneinfo
2338 4704 5416 6568 7199 bus modules
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
60
the Linux file tree
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.
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.
61
the Linux file tree
/proc/interrupts
On the x86 architecture, /proc/interrupts displays the interrupts.
/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.
paul@laika:~$ ls -lh /proc/kcore
-r-------- 1 root root 2.0G 2007-01-30 08:57 /proc/kcore
paul@laika:~$
62
the Linux file tree
63
the Linux file tree
/usr/bin
The /usr/bin directory contains a lot of commands.
paul@deb508:~$ ls /usr/bin | wc -l
1395
/usr/include
The /usr/include directory contains general use include files for C.
paul@ubu1010:~$ ls /usr/include/
aalib.h expat_config.h math.h search.h
af_vfs.h expat_external.h mcheck.h semaphore.h
aio.h expat.h memory.h setjmp.h
AL fcntl.h menu.h sgtty.h
aliases.h features.h mntent.h shadow.h
...
/usr/lib
The /usr/lib directory contains libraries that are not directly executed by users or
scripts.
paul@deb508:~$ ls /usr/lib | head -7
4Suite
ao
apt
arj
aspell
avahi
bonobo
/usr/local
The /usr/local directory can be used by an administrator to install software locally.
paul@deb508:~$ ls /usr/local/
bin etc games include lib man sbin share src
paul@deb508:~$ du -sh /usr/local/
128K /usr/local/
64
the Linux file tree
/usr/share
The /usr/share directory contains architecture independent data. As you can see, this
is a fairly large directory.
paul@deb508:~$ ls /usr/share/ | wc -l
263
paul@deb508:~$ du -sh /usr/share/
1.3G /usr/share/
And it contains /usr/share/games for all static game data (so no high-scores or play
logs).
paul@ubu1010:~$ ls /usr/share/games/
openttd wesnoth
/usr/src
The /usr/src directory is the recommended location for kernel source files.
paul@deb508:~$ ls -l /usr/src/
total 12
drwxr-xr-x 4 root root 4096 2011-02-01 14:43 linux-headers-2.6.26-2-686
drwxr-xr-x 18 root root 4096 2011-02-01 14:43 linux-headers-2.6.26-2-common
drwxr-xr-x 3 root root 4096 2009-10-28 16:01 linux-kbuild-2.6.26
65
the Linux file tree
/var/log
The /var/log directory serves as a central point to contain all log files.
[paul@RHEL4b ~]$ ls /var/log
acpid cron.2 maillog.2 quagga secure.4
amanda cron.3 maillog.3 radius spooler
anaconda.log cron.4 maillog.4 rpmpkgs spooler.1
anaconda.syslog cups mailman rpmpkgs.1 spooler.2
anaconda.xlog dmesg messages rpmpkgs.2 spooler.3
audit exim messages.1 rpmpkgs.3 spooler.4
boot.log gdm messages.2 rpmpkgs.4 squid
boot.log.1 httpd messages.3 sa uucp
boot.log.2 iiim messages.4 samba vbox
boot.log.3 iptraf mysqld.log scrollkeeper.log vmware-tools-guestd
boot.log.4 lastlog news secure wtmp
canna mail pgsql secure.1 wtmp.1
cron maillog ppp secure.2 Xorg.0.log
cron.1 maillog.1 prelink.log secure.3 Xorg.0.log.old
/var/log/messages
A typical first file to check when troubleshooting on Red Hat (and derivatives) is
the /var/log/messages file. By default this file will contain information on what just
happened to the system. The file is called /var/log/syslog on Debian and Ubuntu.
[root@RHEL4b ~]# tail /var/log/messages
Jul 30 05:13:56 anacron: anacron startup succeeded
Jul 30 05:13:56 atd: atd startup succeeded
Jul 30 05:13:57 messagebus: messagebus startup succeeded
Jul 30 05:13:57 cups-config-daemon: cups-config-daemon startup succeeded
Jul 30 05:13:58 haldaemon: haldaemon startup succeeded
Jul 30 05:14:00 fstab-sync[3560]: removed all generated mount points
Jul 30 05:14:01 fstab-sync[3628]: added mount point /media/cdrom for...
Jul 30 05:14:01 fstab-sync[3646]: added mount point /media/floppy for...
Jul 30 05:16:46 sshd(pam_unix)[3662]: session opened for user paul by...
Jul 30 06:06:37 su(pam_unix)[3904]: session opened for user root by paul
/var/cache
The /var/cache directory can contain cache data for several applications.
paul@ubu1010:~$ ls /var/cache/
apt dictionaries-common gdm man software-center
binfmts flashplugin-installer hald pm-utils
cups fontconfig jockey pppconfig
debconf fonts ldconfig samba
66
the Linux file tree
/var/spool
The /var/spool directory typically contains spool directories for mail and cron, but
also serves as a parent directory for other spool files (for example print spool files).
/var/lib
The /var/lib directory contains application state information.
Red Hat Enterprise Linux for example keeps files pertaining to rpm in /var/lib/rpm/.
/var/...
/var also contains Process ID files in /var/run (soon to be replaced with /run) and
temporary files that survive a reboot in /var/tmp and information about file locks in
/var/lock. There will be more examples of /var usage further in this book.
67
the Linux file 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 ?
68
the Linux file tree
14. Read the man page of random and explain the difference between /dev/random
and /dev/urandom.
69
the Linux file 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 ?
70
the Linux file 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
71
Part III. shell expansion
Chapter 10. commands and arguments
Table of Contents
10.1. echo .............................................................................................................. 74
10.2. arguments ..................................................................................................... 74
10.3. commands .................................................................................................... 76
10.4. aliases ........................................................................................................... 77
10.5. displaying shell expansion ........................................................................... 78
10.6. practice: commands and arguments ............................................................. 79
10.7. solution: commands and arguments ............................................................. 81
This chapter introduces you to shell expansion by taking a close look at commands
and arguments. Knowing shell expansion is important because many commands
on your Linux system are processed and most likely changed by the shell before they
are executed.
The command line interface or shell used on most Linux systems is called bash,
which stands for Bourne again shell. The bash shell incorporates features from sh
(the original Bourne shell), csh (the C shell), and ksh (the Korn shell).
73
commands and arguments
10.1. echo
This chapter frequently uses the echo command to demonstrate shell features. The
echo command is very simple: it echoes the input that it receives.
paul@laika:~$ echo Burtonville
Burtonville
paul@laika:~$ echo Smurfs are blue
Smurfs are blue
10.2. arguments
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, cutting it up in arguments. While scanning the
line, the shell may make many changes to the arguments you typed. This process
is called shell expansion. When the shell has finished scanning and modifying that
line, then it will be executed.
This explains why the following four different command lines are the same after shell
expansion.
[paul@RHELv4u3 ~]$ echo Hello World
Hello World
[paul@RHELv4u3 ~]$ echo Hello World
Hello World
[paul@RHELv4u3 ~]$ echo Hello World
Hello World
[paul@RHELv4u3 ~]$ echo Hello World
Hello World
The echo command will display each argument it receives from the shell. The echo
command will also add a new white space between the arguments it received.
single quotes
You can prevent the removal of white spaces by quoting the spaces. The contents of
the quoted string are considered as one argument. In the screenshot below the echo
receives only one argument.
[paul@RHEL4b ~]$ echo 'A line with single quotes'
A line with single quotes
[paul@RHEL4b ~]$
74
commands and arguments
double quotes
You can also prevent the removal of white spaces by double quoting the spaces.
Same as above, echo only receives one argument.
[paul@RHEL4b ~]$ echo "A line with double quotes"
A line with double quotes
[paul@RHEL4b ~]$
Later in this book, when discussing variables we will see important differences
between single and double quotes.
The echo command can generate more than white spaces, tabs and newlines. Look
in the man page for a list of options.
75
commands and arguments
10.3. commands
type
To find out whether a command given to the shell will be executed as an external
command or as a builtin command, use the type command.
paul@laika:~$ type cd
cd is a shell builtin
paul@laika:~$ type cat
cat is /bin/cat
As you can see, the cd command is builtin and the cat command is external.
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'
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 builtin, and ls, cp, rm, mv, mkdir, pwd, and which are external commands.
[root@RHEL4b ~]# which cp ls cd mkdir pwd
/bin/cp
/bin/ls
/usr/bin/which: no cd in (/usr/kerberos/sbin:/usr/kerberos/bin:...
/bin/mkdir
/bin/pwd
76
commands and arguments
10.4. aliases
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.
[paul@RHELv4u3 ~]$ cat count.txt
one
two
three
[paul@RHELv4u3 ~]$ alias dog=tac
[paul@RHELv4u3 ~]$ dog count.txt
three
two
one
abbreviate commands
An alias can also be useful to abbreviate an existing command.
paul@laika:~$ alias ll='ls -lh --color=auto'
paul@laika:~$ alias c='clear'
paul@laika:~$
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.
[paul@RHELv4u3 ~]$ rm -i winter.txt
rm: remove regular file `winter.txt'? no
[paul@RHELv4u3 ~]$ rm winter.txt
[paul@RHELv4u3 ~]$ ls winter.txt
ls: winter.txt: No such file or directory
[paul@RHELv4u3 ~]$ touch winter.txt
[paul@RHELv4u3 ~]$ alias rm='rm -i'
[paul@RHELv4u3 ~]$ rm winter.txt
rm: remove regular empty file `winter.txt'? no
[paul@RHELv4u3 ~]$
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'
77
commands and arguments
unalias
You can undo an alias with the unalias command.
[paul@RHEL4b ~]$ which rm
/bin/rm
[paul@RHEL4b ~]$ alias rm='rm -i'
[paul@RHEL4b ~]$ which rm
alias rm='rm -i'
/bin/rm
[paul@RHEL4b ~]$ unalias rm
[paul@RHEL4b ~]$ which rm
/bin/rm
[paul@RHEL4b ~]$
78
commands and arguments
4. 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.
5. 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
(optional)16. Complete the following command (do not use spaces) to display exactly
the following output:
4+4 =8
10+14 =24
79
commands and arguments
19. Use one echo command to display three words on three lines.
80
commands and arguments
answer: three
4. 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
5. Execute: alias rm='rm -i' . Test your alias with a test file. Does this work as
expected ?
touch testfile
81
commands and arguments
unalias city
12. What is the location of the cat and the passwd commands ?
which cat (probably /bin/cat)
/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.
16. Complete the following command (do not use spaces) to display exactly the
following output:
4+4 =8
10+14 =24
19. Use one echo command to display three words on three lines.
echo -e "one \ntwo \nthree"
82
Chapter 11. control operators
Table of Contents
11.1. ; semicolon ................................................................................................... 84
11.2. & ampersand ................................................................................................ 84
11.3. $? dollar question mark ............................................................................... 84
11.4. && double ampersand ................................................................................. 85
11.5. || double vertical bar .................................................................................... 85
11.6. combining && and || ................................................................................... 85
11.7. # pound sign ................................................................................................ 86
11.8. \ escaping special characters ........................................................................ 86
11.9. practice: control operators ........................................................................... 87
11.10. solution: control operators ......................................................................... 88
In this chapter we put more than one command on the command line using control
operators. We also briefly discuss related parameters ($?) and similar special
characters(&).
83
control operators
11.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.
[paul@RHELv4u3 ~]$ echo Hello
Hello
[paul@RHELv4u3 ~]$ echo World
World
[paul@RHELv4u3 ~]$ echo Hello ; echo World
Hello
World
[paul@RHELv4u3 ~]$
The technical explanation of what happens in this case is explained in the chapter
about processes.
84
control operators
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.
[paul@RHELv4u3 ~]$ cd gen && ls
file1 file3 File55 fileab FileAB fileabc
file2 File4 FileA Fileab fileab2
[paul@RHELv4u3 gen]$ cd gen && ls
-bash: cd: gen: No such file or directory
85
control operators
86
control operators
6. 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/ .
9. 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.
87
control operators
6. 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
9. 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
or
88
Chapter 12. variables
Table of Contents
12.1. about variables ............................................................................................. 90
12.2. quotes ........................................................................................................... 92
12.3. set ................................................................................................................. 92
12.4. unset ............................................................................................................. 92
12.5. env ................................................................................................................ 93
12.6. export ........................................................................................................... 93
12.7. delineate variables ........................................................................................ 94
12.8. unbound variables ........................................................................................ 94
12.9. shell options ................................................................................................. 95
12.10. shell embedding ......................................................................................... 96
12.11. practice: shell variables .............................................................................. 97
12.12. solution: shell variables ............................................................................. 98
We also take a brief look at child shells, embedded shells and shell options.
89
variables
$ dollar sign
Another important character interpreted by the shell is the dollar sign $. The shell
will look for an environment variable named like the string following the dollar
sign and replace it with the value of the variable (or with nothing if the variable does
not exist).
These are some examples using $HOSTNAME, $USER, $UID, $SHELL, and
$HOME.
[paul@RHELv4u3 ~]$ echo This is the $SHELL shell
This is the /bin/bash shell
[paul@RHELv4u3 ~]$ echo This is $SHELL on computer $HOSTNAME
This is /bin/bash on computer RHELv4u3.localdomain
[paul@RHELv4u3 ~]$ echo The userid of $USER is $UID
The userid of paul is 500
[paul@RHELv4u3 ~]$ echo My homedir is $HOME
My homedir is /home/paul
case sensitive
This example shows that shell variables are case sensitive!
[paul@RHELv4u3 ~]$ echo Hello $USER
Hello paul
[paul@RHELv4u3 ~]$ echo Hello $user
Hello
$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.
To avoid unrecoverable mistakes, you can set normal user prompts to green and the
root prompt to red. This picture shows (one way) to do this.
90
variables
$PATH
The $PATH variable is determines where the shell is looking for commands to
execute (unless the command is builtin or aliased). This variable contains a list of
directories, separated by colons.
[[paul@RHEL4b ~]$ echo $PATH
/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:
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 hack PC-DOS
computers). If you want the shell to look in the current directory, then add a . at the
end of your $PATH.
[paul@RHEL4b ~]$ PATH=$PATH:.
[paul@RHEL4b ~]$ echo $PATH
/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:.
[paul@RHEL4b ~]$
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 typically has /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 ~]#
creating variables
This example creates the variable $MyVar and sets its value. It then uses echo to
verify the value.
[paul@RHELv4u3 gen]$ MyVar=555
[paul@RHELv4u3 gen]$ echo $MyVar
555
[paul@RHELv4u3 gen]$
91
variables
12.2. quotes
Notice that double quotes still allow the parsing of variables, whereas single quotes
prevent this.
[paul@RHELv4u3 ~]$ MyVar=555
[paul@RHELv4u3 ~]$ echo $MyVar
555
[paul@RHELv4u3 ~]$ echo "$MyVar"
555
[paul@RHELv4u3 ~]$ echo '$MyVar'
$MyVar
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.
12.3. 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.
12.4. unset
Use the unset command to remove a variable from your shell environment.
[paul@RHEL4b ~]$ MyVar=8472
[paul@RHEL4b ~]$ echo $MyVar
8472
[paul@RHEL4b ~]$ unset MyVar
[paul@RHEL4b ~]$ echo $MyVar
[paul@RHEL4b ~]$
92
variables
12.5. env
The env command without options will display a list of exported variables. The
difference with set with options is that set lists all variables, including those not
exported to child shells.
But env can also be used to start a clean shell (a shell without any inherited
environment). The env -i command clears the environment for the subshell.
Notice in this screenshot that bash will set the $SHELL variable on startup.
[paul@RHEL4b ~]$ bash -c 'echo $SHELL $HOME $USER'
/bin/bash /home/paul paul
[paul@RHEL4b ~]$ env -i bash -c 'echo $SHELL $HOME $USER'
/bin/bash
[paul@RHEL4b ~]$
You can 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 (see the chapter on file globbing).
[paul@RHEL4b test]$ env LANG=C bash -c 'ls File[a-z]'
Filea Fileb
[paul@RHEL4b test]$ env LANG=en_US.UTF-8 bash -c 'ls File[a-z]'
Filea FileA Fileb FileB
[paul@RHEL4b test]$
12.6. export
You can export shell variables to other shells with the export command. This will
export the variable to child shells.
[paul@RHEL4b ~]$ var3=three
[paul@RHEL4b ~]$ var4=four
[paul@RHEL4b ~]$ export var4
[paul@RHEL4b ~]$ echo $var3 $var4
three four
[paul@RHEL4b ~]$ bash
[paul@RHEL4b ~]$ echo $var3 $var4
four
But it will not export to the parent shell (previous screenshot continued).
[paul@RHEL4b ~]$ export var5=five
[paul@RHEL4b ~]$ echo $var3 $var4 $var5
four five
[paul@RHEL4b ~]$ exit
exit
[paul@RHEL4b ~]$ echo $var3 $var4 $var5
three four
[paul@RHEL4b ~]$
93
variables
[paul@RHELv4u3 gen]$
There is, however, the nounset shell option 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.
94
variables
[paul@RHEL4b ~]$
To list all the set options for your shell, use echo $-. The noclobber (or -C) option
will be explained later in this book (in the I/O redirection chapter).
[paul@RHEL4b ~]$ echo $-
himBH
[paul@RHEL4b ~]$ set -C ; set -u
[paul@RHEL4b ~]$ echo $-
himuBCH
[paul@RHEL4b ~]$ set +C ; set +u
[paul@RHEL4b ~]$ echo $-
himBH
[paul@RHEL4b ~]$
When typing set without options, you get a list of all variables without function when
the shell is on posix mode. You can set bash in posix mode typing set -o posix.
95
variables
[paul@RHELv4u3 gen]$
You can embed a shell in an embedded shell, this is called nested embedding of
shells.
backticks
Single embedding can be useful to avoid changing your current directory. The
screenshot below uses backticks instead of dollar-bracket to embed.
[paul@RHELv4u3 ~]$ echo `cd /etc; ls -d * | grep pass`
passwd passwd- passwd.OLD
[paul@RHELv4u3 ~]$
You can only use the $() notation to nest embedded shells, backticks cannot do this.
96
variables
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.
15. Create the variable embvar in an embedded shell and echo it. Does the variable
exist in your current shell now ?
(optional)17. Given the following screenshot, add exactly four characters to that
command line so that the total output is FirstMiddleLast.
[paul@RHEL4b ~]$ echo First; echo Middle; echo Last
18. Display a long listing (ls -l) of the passwd command using the which command
inside back ticks.
97
variables
set|more on Ubuntu/Debian
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.
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
solution by Yves from Dexia : echo $varx'le'$vary're'
solution by Erwin from Telenet : echo "$varx"le"$vary"re
11. Activate nounset in your shell. Test that it shows an error message when using
non-existing variables.
98
variables
set -u
OR
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 \W$ '
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.
15. 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).
(optional)17. Given the following screenshot, add exactly four characters to that
command line so that the total output is FirstMiddleLast.
[paul@RHEL4b ~]$ echo First; echo Middle; echo Last
18. Display a long listing (ls -l) of the passwd command using the which command
inside back ticks.
ls -l `which passwd`
99
Chapter 13. shell history
Table of Contents
13.1. repeating the last command ....................................................................... 101
13.2. repeating other commands ......................................................................... 101
13.3. history ......................................................................................................... 101
13.4. !n ................................................................................................................. 101
13.5. Ctrl-r ........................................................................................................... 102
13.6. $HISTSIZE ................................................................................................ 102
13.7. $HISTFILE ................................................................................................ 102
13.8. $HISTFILESIZE ........................................................................................ 102
13.9. (optional)regular expressions ..................................................................... 103
13.10. (optional)repeating commands in ksh ...................................................... 103
13.11. practice: shell history ............................................................................... 104
13.12. solution: shell history ............................................................................... 105
The shell makes it easy for us to repeat commands, this chapter explains how.
100
shell history
13.3. history
To see older commands, use history to display the shell command history (or use
history n to see the last n commands).
paul@debian5:~/test$ history 10
38 mkdir test
39 cd test
40 touch file1
41 echo hello > file2
42 echo It is very cold today > winter.txt
43 ls
44 ls -l
45 cp winter.txt summer.txt
46 ls -l
47 history 10
13.4. !n
When typing ! followed by the number preceding the command you want repeated,
then the shell will echo the command and execute it.
paul@debian5:~/test$ !43
ls
file1 file2 summer.txt winter.txt
101
shell history
13.5. Ctrl-r
Another option is to use ctrl-r to search in the history. In the screenshot below i only
typed ctrl-r followed by four characters apti and it finds the last command containing
these four consecutive characters.
paul@debian5:~$
(reverse-i-search)`apti': sudo aptitude install screen
13.6. $HISTSIZE
The $HISTSIZE variable determines the number of commands that will be
remembered in your current environment. Most distributions default this variable to
500 or 1000.
paul@debian5:~$ echo $HISTSIZE
500
13.7. $HISTFILE
The $HISTFILE variable points to the file that contains your history. The bash shell
defaults this value to ~/.bash_history.
paul@debian5:~$ echo $HISTFILE
/home/paul/.bash_history
A session history is saved to this file when you exit the session!
Closing a gnome-terminal with the mouse, or typing reboot as root will NOT save
your terminal's history.
13.8. $HISTFILESIZE
The number of commands kept in your history file can be set using $HISTFILESIZE.
paul@debian5:~$ echo $HISTFILESIZE
15000
102
shell history
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
$
103
shell history
2. Repeat the previous command using only two characters (there are two solutions!)
4. Issue the long echo from question 1 again, using the line numbers you received
from the command in question 3.
5. How many commands can be kept in memory for your current shell session ?
7. How many commands can be written to the history file when exiting your current
shell session ?
8. Make sure your current bash shell remembers the next 5000 commands you type.
9. 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 ?
104
shell history
2. Repeat the previous command using only two characters (there are two solutions!)
!!
OR
!e
4. Issue the long echo from question 1 again, using the line numbers you received
from the command in question 3.
paul@ubu1010:~$ !56
echo The answer to the meaning of life, the universe and everything is 42
The answer to the meaning of life, the universe and everything is 42
5. How many commands can be kept in memory for your current shell session ?
echo $HISTSIZE
7. How many commands can be written to the history file when exiting your current
shell session ?
echo $HISTFILESIZE
8. Make sure your current bash shell remembers the next 5000 commands you type.
HISTSIZE=5000
9. 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
105
Chapter 14. file globbing
Table of Contents
14.1. * asterisk .................................................................................................... 107
14.2. ? question mark .......................................................................................... 107
14.3. [] square brackets ....................................................................................... 107
14.4. a-z and 0-9 ranges ..................................................................................... 108
14.5. $LANG and square brackets ...................................................................... 108
14.6. preventing file globbing ............................................................................. 109
14.7. practice: shell globbing .............................................................................. 110
14.8. solution: shell globbing .............................................................................. 111
The shell is also responsible for file globbing (or dynamic filename generation). This
chapter will explain file globbing.
106
file globbing
14.1. * asterisk
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]$
107
file globbing
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]$
108
file globbing
109
file globbing
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. 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 ?
110
file globbing
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
touch file33 fileAB filea fileA fileAAA
touch "file("
touch "file 2"
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]
13. List all files that do not start with the letter F.
ls [!F]*
111
file globbing
16. 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 *
112
Part IV. pipes and commands
Chapter 15. redirection and pipes
Table of Contents
15.1. stdin, stdout, and stderr .............................................................................. 115
15.2. output redirection ....................................................................................... 115
15.3. error redirection ......................................................................................... 117
15.4. input redirection ......................................................................................... 118
15.5. confusing redirection .................................................................................. 119
15.6. quick file clear ........................................................................................... 119
15.7. swapping stdout and stderr ........................................................................ 119
15.8. pipes ........................................................................................................... 120
15.9. practice: redirection and pipes ................................................................... 121
15.10. solution: redirection and pipes ................................................................. 122
One of the powers of the Unix command line is the use of redirection and pipes.
This chapter first explains redirection of input, output and error streams. It then
introduces pipes that consist of several commands.
114
redirection and pipes
The keyboard often serves as stdin, stdout and stderr both go to the display. The
shell allows you to redirect these streams.
> stdout
stdout can be redirected with a greater than sign. While scanning the line, the shell
will see the > sign and will clear the file.
[paul@RHELv4u3 ~]$ echo It is cold today!
It is cold today!
[paul@RHELv4u3 ~]$ echo It is cold today! > winter.txt
[paul@RHELv4u3 ~]$ cat winter.txt
It is cold today!
[paul@RHELv4u3 ~]$
Note that the > notation is in fact the abbreviation of 1> (stdout being referred to
as stream 1.
noclobber
Erasing a file while using > can be prevented by setting the noclobber option.
[paul@RHELv4u3 ~]$ cat winter.txt
It is cold today!
[paul@RHELv4u3 ~]$ set -o noclobber
[paul@RHELv4u3 ~]$ echo It is cold today! > winter.txt
-bash: winter.txt: cannot overwrite existing file
[paul@RHELv4u3 ~]$ set +o noclobber
[paul@RHELv4u3 ~]$
115
redirection and pipes
overruling noclobber
The noclobber can be overruled with >|.
>> append
Use >> to append output to a file.
116
redirection and pipes
2> stderr
Redirecting stderr is done with 2>. This can be very useful to prevent error messages
from cluttering your screen. The screenshot below shows redirection of stdout to a
file, and stderr to /dev/null. Writing 1> is the same as >.
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
ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard error made a copy
of the standard output before the standard output was redirected to dirlist.
117
redirection and pipes
< stdin
Redirecting stdin is done with < (short for 0<).
118
redirection and pipes
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 $error.
$command 3>&1 1>&2 2>&3 | grep -v $error 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 $error
119
redirection and pipes
15.8. pipes
One of the most powerful advantages of Linux is the use of 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.
| vertical bar
Consider the following example.
paul@debian5:~/test$ ls /etc > etcfiles.txt
paul@debian5:~/test$ tail -4 etcfiles.txt
X11
xdg
xml
xpdf
paul@debian5:~/test$
multiple pipes
One command line can use multiple pipes. All commands in the pipe can run at the
same time.
paul@deb503:~/test$ ls /etc | tail -4 | tac
xpdf
xml
xdg
X11
120
redirection and pipes
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.
121
redirection and pipes
4. When listing all shell options, which character represents the noclobber option ?
echo $- (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:~$
122
Chapter 16. filters
Table of Contents
16.1. cat ............................................................................................................... 124
16.2. tee ............................................................................................................... 124
16.3. grep ............................................................................................................. 124
16.4. cut ............................................................................................................... 126
16.5. tr ................................................................................................................. 126
16.6. wc ............................................................................................................... 127
16.7. sort .............................................................................................................. 128
16.8. uniq ............................................................................................................. 129
16.9. comm .......................................................................................................... 129
16.10. od .............................................................................................................. 130
16.11. sed ............................................................................................................ 131
16.12. pipe examples ........................................................................................... 132
16.13. practice: filters ......................................................................................... 133
16.14. solution: filters ......................................................................................... 134
Commands that are created to be used with a pipe are often called filters. These
filters are very small programs that do one specific thing very efficiently. They can
be used as building blocks.
This chapter will introduce you to the most common filters. The combination of
simple commands and filters in a long pipe allows you to design elegant solutions.
123
filters
16.1. cat
When between two pipes, the cat command does nothing (except putting stdin on
stdout.
[paul@RHEL4b pipes]$ tac count.txt | cat | cat | cat | cat | cat
five
four
three
two
one
[paul@RHEL4b pipes]$
16.2. 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]$
16.3. 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
One of the most useful options of grep is grep -i which filters in a case insensitive
way.
124
filters
Another very useful option is grep -v which outputs lines not matching the string.
[paul@RHEL4b pipes]$ grep -v Fra tennis.txt
Kim Clijsters, BEL
Justine Henin, Bel
Serena Williams, usa
Venus Williams, USA
[paul@RHEL4b pipes]$
And of course, both options can be combined to filter all lines not containing a case
insensitive string.
[paul@RHEL4b pipes]$ grep -vi usa tennis.txt
Amelie Mauresmo, Fra
Kim Clijsters, BEL
Justine Henin, Bel
[paul@RHEL4b pipes]$
With grep -A1 one line after the result is also displayed.
paul@debian5:~/pipes$ grep -A1 Henin tennis.txt
Justine Henin, Bel
Serena Williams, usa
With grep -B1 one line before the result is also displayed.
paul@debian5:~/pipes$ grep -B1 Henin tennis.txt
Kim Clijsters, BEL
Justine Henin, Bel
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).
paul@debian5:~/pipes$ grep -C1 Henin tennis.txt
Kim Clijsters, BEL
Justine Henin, Bel
Serena Williams, usa
125
filters
16.4. 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.
[paul@RHEL4b pipes]$ cut -d" " -f1 tennis.txt
Amelie
Kim
Justine
Serena
Venus
[paul@RHEL4b pipes]$
This example uses cut to display the second to the seventh character of /etc/passwd.
[paul@RHEL4b pipes]$ cut -c2-7 /etc/passwd | tail -4
igo:x:
faff:x
arry:x
ermion
[paul@RHEL4b pipes]$
16.5. tr
You can translate characters with tr. The screenshot shows the translation of all
occurrences of e to E.
[paul@RHEL4b pipes]$ cat tennis.txt | tr 'e' 'E'
AmEliE MaurEsmo, Fra
Kim ClijstErs, BEL
JustinE HEnin, BEl
SErEna Williams, usa
VEnus Williams, USA
126
filters
two
three
four
five
[paul@RHEL4b pipes]$ cat count.txt | tr '\n' ' '
one two three four five [paul@RHEL4b pipes]$
The tr -s filter can also be used to squeeze multiple occurrences of a character to one.
[paul@RHEL4b pipes]$ cat spaces.txt
one two three
four five six
[paul@RHEL4b pipes]$ cat spaces.txt | tr -s ' '
one two three
four five six
[paul@RHEL4b pipes]$
16.6. wc
Counting words, lines and characters is easy with wc.
[paul@RHEL4b pipes]$ wc tennis.txt
5 15 100 tennis.txt
[paul@RHEL4b pipes]$ wc -l tennis.txt
5 tennis.txt
[paul@RHEL4b pipes]$ wc -w tennis.txt
15 tennis.txt
[paul@RHEL4b pipes]$ wc -c tennis.txt
100 tennis.txt
[paul@RHEL4b pipes]$
127
filters
16.7. sort
The sort filter will default to an alphabetical sort.
paul@debian5:~/pipes$ cat music.txt
Queen
Brel
Led Zeppelin
Abba
paul@debian5:~/pipes$ sort music.txt
Abba
Brel
Led Zeppelin
Queen
But the sort filter has many options to tweak its usage. This example shows sorting
different columns (column 1 or column 2).
[paul@RHEL4b pipes]$ sort -k1 country.txt
Belgium, Brussels, 10
France, Paris, 60
Germany, Berlin, 100
Iran, Teheran, 70
Italy, Rome, 50
[paul@RHEL4b pipes]$ sort -k2 country.txt
Germany, Berlin, 100
Belgium, Brussels, 10
France, Paris, 60
Italy, Rome, 50
Iran, Teheran, 70
The screenshot below shows the difference between an alphabetical sort and a
numerical sort (both on the third column).
[paul@RHEL4b pipes]$ sort -k3 country.txt
Belgium, Brussels, 10
Germany, Berlin, 100
Italy, Rome, 50
France, Paris, 60
Iran, Teheran, 70
[paul@RHEL4b pipes]$ sort -n -k3 country.txt
Belgium, Brussels, 10
Italy, Rome, 50
France, Paris, 60
Iran, Teheran, 70
Germany, Berlin, 100
128
filters
16.8. uniq
With uniq you can remove duplicates from a sorted list.
paul@debian5:~/pipes$ cat music.txt
Queen
Brel
Queen
Abba
paul@debian5:~/pipes$ sort music.txt
Abba
Brel
Queen
Queen
paul@debian5:~/pipes$ sort music.txt |uniq
Abba
Brel
Queen
16.9. 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.
paul@debian5:~/pipes$ cat > list1.txt
Abba
Bowie
Cure
Queen
Sweet
paul@debian5:~/pipes$ cat > list2.txt
Abba
Cure
Queen
Turner
paul@debian5:~/pipes$ comm list1.txt list2.txt
Abba
Bowie
Cure
Queen
Sweet
Turner
129
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.
16.10. 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
paul@laika:~/test$ od -b text.txt
0000000 141 142 143 144 145 146 147 012 061 062 063 064 065 066 067 012
0000020
paul@laika:~/test$ od -c text.txt
0000000 a b c d e f g \n 1 2 3 4 5 6 7 \n
0000020
130
filters
16.11. 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).
131
filters
who | wc
How many users are logged on to this system ?
[paul@RHEL4b pipes]$ who
root tty1 Jul 25 10:50
paul pts/0 Jul 25 09:29 (laika)
Harry pts/1 Jul 25 12:26 (barry)
paul pts/2 Jul 25 12:26 (pasha)
[paul@RHEL4b pipes]$ who | wc -l
4
Display a sorted list of logged on users, but every user only once .
[paul@RHEL4b pipes]$ who | cut -d' ' -f1 | sort | uniq
Harry
paul
root
grep | cut
Display a list of all bash user accounts on this computer. Users accounts are
explained in detail later.
paul@debian5:~$ grep bash /etc/passwd
root:x:0:0:root:/root:/bin/bash
paul:x:1000:1000:paul,,,:/home/paul:/bin/bash
serena:x:1001:1001::/home/serena:/bin/bash
paul@debian5:~$ grep bash /etc/passwd | cut -d: -f1
root
paul
serena
132
filters
3. Make a list of all filenames 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 text file, 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/ .)
133
filters
3. Make a list of all filenames 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 text file, 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/ .)
134
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.
135
Chapter 17. basic Unix tools
Table of Contents
17.1. find ............................................................................................................. 137
17.2. locate .......................................................................................................... 138
17.3. date ............................................................................................................. 138
17.4. cal ............................................................................................................... 139
17.5. sleep ........................................................................................................... 139
17.6. time ............................................................................................................. 139
17.7. gzip - gunzip .............................................................................................. 140
17.8. zcat - zmore ............................................................................................... 140
17.9. bzip2 - bunzip2 .......................................................................................... 141
17.10. bzcat - bzmore ......................................................................................... 141
17.11. practice: basic Unix tools ........................................................................ 142
17.12. solution: basic Unix tools ........................................................................ 143
This chapter introduces commands to find or locate files and to compress files,
together with other common tools that were not discussed before. While the tools
discussed here are technically not considered filters, they can be used in pipes.
136
basic Unix tools
17.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 -name "*.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 -name "*.odf" -ok rm {} \;
137
basic Unix tools
17.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.
[paul@RHEL4b ~]$ locate Samba
warning: locate: could not open database: /var/lib/slocate/slocate.db:...
warning: You need to run the 'updatedb' command (as root) to create th...
Please have a look at /etc/updatedb.conf to enable the daily cron job.
[paul@RHEL4b ~]$ updatedb
fatal error: updatedb: You are not authorized to create a default sloc...
[paul@RHEL4b ~]$ su -
Password:
[root@RHEL4b ~]# updatedb
[root@RHEL4b ~]#
Most Linux distributions will schedule the updatedb to run once every day.
17.3. date
The date command can display the date, time, time zone and more.
paul@rhel55 ~$ date
Sat Apr 17 12:44:30 CEST 2010
A date string can be customised 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
138
basic Unix tools
17.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
25 26 27 28 29 30
17.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 ~$
17.6. time
The time command can display how long it takes to execute a command. The date
command takes only a little time.
paul@rhel55 ~$ time date
Sat Apr 17 13:08:27 CEST 2010
real 0m0.014s
user 0m0.008s
sys 0m0.006s
The sleep 5 command takes five real seconds to execute, but consumes little cpu
time.
paul@rhel55 ~$ time sleep 5
real 0m5.018s
user 0m0.005s
sys 0m0.011s
139
basic Unix tools
This bzip2 command compresses a file and uses a lot of cpu time.
paul@rhel55 ~$ time bzip2 text.txt
real 0m2.368s
user 0m0.847s
sys 0m0.539s
140
basic Unix tools
141
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 ?
9. Issue the date command. Now display the date in YYYY/MM/DD format.
10. Issue the cal command. Display a calendar of 1582 and 1752. Notice anything
special ?
142
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/
143
basic Unix tools
The first might fail when there are too many files to fit on one command line.
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
9. Issue the date command. Now display the date in YYYY/MM/DD format.
date +%Y/%m/%d
10. Issue the cal command. Display a calendar of 1582 and 1752. Notice anything
special ?
cal 1582
144
Part V. vi
Chapter 18. Introduction to vi
Table of Contents
18.1. command mode and insert mode ............................................................... 147
18.2. start typing (a A i I o O) ........................................................................... 147
18.3. replace and delete a character (r x X) ........................................................ 148
18.4. undo and repeat (u .) .................................................................................. 148
18.5. cut, copy and paste a line (dd yy p P) ....................................................... 148
18.6. cut, copy and paste lines (3dd 2yy) ........................................................... 149
18.7. start and end of a line (0 or ^ and $) ......................................................... 149
18.8. join two lines (J) and more ........................................................................ 149
18.9. words (w b) ................................................................................................ 150
18.10. save (or not) and exit (:w :q :q! ) ............................................................. 150
18.11. Searching (/ ?) .......................................................................................... 151
18.12. replace all ( :1,$ s/foo/bar/g ) ................................................................... 151
18.13. reading files (:r :r !cmd) ........................................................................... 151
18.14. text buffers ............................................................................................... 152
18.15. multiple files ............................................................................................ 152
18.16. abbreviations ............................................................................................ 152
18.17. key mappings ........................................................................................... 153
18.18. setting options .......................................................................................... 153
18.19. practice: vi(m) .......................................................................................... 154
18.20. solution: vi(m) .......................................................................................... 155
The vi editor is installed on almost every Unix. Linux will very often install vim (vi
improved) which is similar. Every system administrator should know vi(m), because
it is an easy tool to solve problems.
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).
146
Introduction to vi
147
Introduction to vi
148
Introduction to vi
149
Introduction to vi
18.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).
150
Introduction to vi
18.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.
command action
/string forward search for string
?string backward search for string
n go to next occurrence of search string
/^string forward search string at beginning of line
/string$ forward search string at end of line
/br[aeio]l search for bral brel bril and brol
/\<he\> search for the word he (and not for here or the)
command action
:4,8 s/foo/bar/g replace foo with bar on lines 4 to 8
:1,$ s/foo/bar/g replace foo with bar on all lines
command action
:r fname (read) file fname and paste contents
:r !cmd execute cmd and paste its output
151
Introduction to vi
18.16. abbreviations
With :ab you can put abbreviations in vi. Use :una to undo the abbreviation.
152
Introduction to vi
This example shows how to set the F6 function key to toggle between set number
and set nonumber. The <bar> separates the two commands, set number! toggles
the state and set number? reports the current state.
:map <F6> :set number!<bar>set number?<CR>
You can set these options (and much more) in ~/.vimrc for vim or in ~/.exrc for
standard vi.
153
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 ?
154
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.
155
Part VI. scripting
Chapter 19. scripting introduction
Table of Contents
19.1. prerequisites ............................................................................................... 158
19.2. hello world ................................................................................................. 158
19.3. she-bang ..................................................................................................... 158
19.4. comment ..................................................................................................... 159
19.5. variables ..................................................................................................... 159
19.6. sourcing a script ......................................................................................... 159
19.7. troubleshooting a script .............................................................................. 160
19.8. prevent setuid root spoofing ...................................................................... 160
19.9. practice: introduction to scripting .............................................................. 161
19.10. solution: introduction to scripting ............................................................ 162
Shells like bash and Korn have support for programming constructs that can be saved
as scripts. These scripts in turn then become more shell commands. Many Linux
commands are scripts. User profile scripts are run when a user logs on and init
scripts are run when a daemon is stopped or started.
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.
The goal of this chapter is to give you enough information to be able to read and
understand scripts. Not to become a writer of complex scripts.
157
scripting introduction
19.1. prerequisites
You should have read and understood part III shell expansion and part IV pipes
and commands before starting this chapter.
After creating this simple script in vi or with echo, 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.
[paul@RHEL4a ~]$ echo echo Hello World > hello_world
[paul@RHEL4a ~]$ chmod +x hello_world
[paul@RHEL4a ~]$ ./hello_world
Hello World
[paul@RHEL4a ~]$
19.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 (sometimes called sha-bang), where the she-
bang is the first two characters of the script.
#!/bin/bash
echo Hello World
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 she-bang 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`
This script will run in a Korn shell (unless /bin/ksh is a hard 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`
158
scripting introduction
19.4. comment
Let's expand our example a little further by adding comment lines.
#!/bin/bash
#
# Hello World Script
#
echo Hello World
19.5. variables
Here is a simple example of a variable inside a script.
#!/bin/bash
#
# simple variable in script
#
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 ~]$ echo $var1
[paul@RHEL4a ~]$
159
scripting introduction
Expanding this to bash -x allows you to see the commands that the shell is executing
(after shell expansion).
paul@debian6~/test$ bash -x runme
+ var4=42
+ echo 42
42
paul@debian6~/test$ cat runme
# the runme script
var4=42
echo $var4
paul@debian6~/test$
Notice the absence of the commented (#) line, and the replacement of the variable
before execution of echo.
Any arguments after the -- are treated as filenames and arguments. An argument of
- is equivalent to --.
160
scripting introduction
4. Create a script that defines two variables, and outputs their value.
5. The previous script does not influence your current shell (the variables do not exist
outside of the script). Now run the script so that it influences your current shell.
7. Comment your scripts so that you know what they are doing.
161
scripting introduction
Note that while first.bash will technically work as a Korn shell script, the name ending
in .bash is confusing.
4. Create a script that defines two variables, and outputs their value.
$ cat second.bash
#!/bin/bash
var33=300
var42=400
5. The previous script does not influence your current shell (the variables do not exist
outside of the script). Now run the script so that it influences your current shell.
source second.bash
7. Comment your scripts so that you know what they are doing.
$ cat second.bash
#!/bin/bash
# script to test variables and sourcing
162
Chapter 20. scripting loops
Table of Contents
20.1. test [ ] ......................................................................................................... 164
20.2. if then else ................................................................................................. 165
20.3. if then elif .................................................................................................. 165
20.4. for loop ....................................................................................................... 165
20.5. while loop .................................................................................................. 166
20.6. until loop .................................................................................................... 166
20.7. practice: scripting tests and loops .............................................................. 167
20.8. solution: scripting tests and loops .............................................................. 168
163
scripting loops
20.1. test [ ]
The test command can test whether something is true or false. Let's start by testing
whether 10 is greater than 55.
[paul@RHEL4b ~]$ test 10 -gt 55 ; echo $?
1
[paul@RHEL4b ~]$
The test command returns 1 if the test fails. And as you see in the next screenshot,
test returns 0 when a test succeeds.
[paul@RHEL4b ~]$ test 56 -gt 55 ; echo $?
0
[paul@RHEL4b ~]$
If you prefer true and false, then write the test like this.
[paul@RHEL4b ~]$ test 56 -gt 55 && echo true || echo false
true
[paul@RHEL4b ~]$ test 6 -gt 55 && echo true || echo false
false
The test command can also be written as square brackets, the screenshot below is
identical to the one above.
[paul@RHEL4b ~]$ [ 56 -gt 55 ] && echo true || echo false
true
[paul@RHEL4b ~]$ [ 6 -gt 55 ] && echo true || echo false
false
Below are some example tests. Take a look at man test to see more options for tests.
[ -d foo ] Does the directory foo exist ?
[ -e bar ] Does the file bar exist ?
[ '/etc' = $PWD ] Is the string /etc equal to the variable $PWD ?
[ $1 != 'secret' ] Is the first parameter different from secret ?
[ 55 -lt $bar ] Is 55 less than the value of $bar ?
[ $foo -ge 1000 ] Is the value of $foo greater or equal to 1000 ?
[ "abc" < $bar ] Does abc sort before the value of $bar ?
[ -f foo ] Is foo a regular file ?
[ -r bar ] Is bar a readable file ?
[ foo -nt bar ] Is file foo newer than file bar ?
[ -o nounset ] Is the shell option nounset set ?
164
scripting loops
if [ -f isit.txt ]
then echo isit.txt exists!
else echo isit.txt not found!
fi
165
scripting loops
The same example as above can be written without the embedded shell using the bash
{from..to} shorthand.
#!/bin/bash
for counter in {1..20}
do
echo counting from 1 to 20, now at $counter
sleep 1
done
This for loop uses file globbing (from the shell expansion). Putting the instruction
on the command line has identical functionality.
kahlan@solexp11$ ls
count.ksh go.ksh
kahlan@solexp11$ for file in *.ksh ; do cp $file $file.backup ; done
kahlan@solexp11$ ls
count.ksh count.ksh.backup go.ksh go.ksh.backup
Endless loops can be made with while true or while : , where the colon is the
equivalent of no operation in the Korn and bash shells.
#!/bin/ksh
# endless loop
while :
do
echo hello
sleep 1
done
166
scripting loops
5. Write a script that counts the number of files ending in .txt in the current directory.
6. Wrap an if statement around the script so it is also correct when there are zero files
ending in .txt.
167
scripting loops
for i in 3 4 5 6 7
do
echo Counting from 3 to 7, now at $i
done
i=3
while [ $i -le 7 ]
do
echo Counting from 3 to 7, now at $i
let i=i+1
done
i=8
until [ $i -lt 4 ]
do
echo Counting down from 8 to 4, now at $i
let i=i-1
done
5. Write a script that counts the number of files ending in .txt in the current directory.
#!/bin/bash
let i=0
for file in *.txt
do
let i++
done
echo "There are $i files ending in .txt"
6. Wrap an if statement around the script so it is also correct when there are zero files
ending in .txt.
#!/bin/bash
168
scripting loops
169
Chapter 21. scripting parameters
Table of Contents
21.1. script parameters ........................................................................................ 171
21.2. shift through parameters ............................................................................ 172
21.3. runtime input .............................................................................................. 172
21.4. sourcing a config file ................................................................................. 173
21.5. get script options with getopts ................................................................... 174
21.6. get shell options with shopt ....................................................................... 175
21.7. practice: parameters and options ................................................................ 176
21.8. solution: parameters and options ............................................................... 177
170
scripting parameters
#!/bin/bash
echo The first argument is $1
echo The second argument is $2
echo The third argument is $3
Once more the same script, but with only two parameters.
Here is another example, where we use $0. The $0 parameter contains the name of
the script.
171
scripting parameters
if [ "$#" == "0" ]
then
echo You have to give at least one parameter.
exit 1
fi
while (( $# ))
do
echo You gave me $1
shift
done
#!/bin/bash
echo -n Enter a number:
read number
172
scripting parameters
. ./myApp.conf
The running application can use the values inside the sourced configuration file.
173
scripting parameters
This is sample output from the script above. First we use correct options, then we
enter twice an invalid option.
kahlan@solexp11$ ./options.ksh
kahlan@solexp11$ ./options.ksh -af
received -a
received -f
kahlan@solexp11$ ./options.ksh -zfg
received -z
received -f
invalid option -g
kahlan@solexp11$ ./options.ksh -a -b -z
received -a
invalid option -b
received -z
174
scripting parameters
You can also check for options that need an argument, as this example shows.
kahlan@solexp11$ cat argoptions.ksh
#!/bin/ksh
175
scripting parameters
2. Write a script that receives two parameters (two filenames) and outputs whether
those files exist.
3. 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.
4. 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.
176
scripting parameters
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 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.
4. 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.
177
Chapter 22. more scripting
Table of Contents
22.1. eval ............................................................................................................. 179
22.2. (( )) ............................................................................................................. 179
22.3. let ................................................................................................................ 180
22.4. case ............................................................................................................. 181
22.5. shell functions ............................................................................................ 182
22.6. practice : more scripting ............................................................................ 183
22.7. solution : more scripting ............................................................................ 184
178
more scripting
22.1. eval
eval reads arguments as input to the shell (the resulting commands are executed).
This allows using the value of a variable as a variable.
paul@deb503:~/test42$ answer=42
paul@deb503:~/test42$ word=answer
paul@deb503:~/test42$ eval x=\$$word ; echo $x
42
Sometimes the eval is needed to have correct parsing of arguments. Consider this
example where the date command receives one parameter 1 week ago.
When we set this command in a variable, then executing that variable fails unless
we use eval.
22.2. (( ))
The (( )) allows for evaluation of numerical expressions.
paul@deb503:~/test42$ (( 42 > 33 )) && echo true || echo false
true
paul@deb503:~/test42$ (( 42 > 1201 )) && echo true || echo false
false
paul@deb503:~/test42$ var42=42
paul@deb503:~/test42$ (( 42 == var42 )) && echo true || echo false
true
paul@deb503:~/test42$ (( 42 == $var42 )) && echo true || echo false
true
paul@deb503:~/test42$ var42=33
paul@deb503:~/test42$ (( 42 == var42 )) && echo true || echo false
false
179
more scripting
22.3. 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.
180
more scripting
22.4. case
You can sometimes simplify nested if statements with a case construct.
181
more scripting
function greetings {
echo Hello World!
echo and hello to $USER to!
}
function plus {
let result="$1 + $2"
echo $1 + $2 = $result
}
plus 3 10
plus 20 13
plus 20 22
182
more scripting
Sum: 5 + 2 = 7
Product: 5 x 2 = 10
2. Improve the previous script to test that the numbers are between 1 and 100, exit
with an error if necessary.
3. Improve the previous script to congratulate the user if the sum equals the product.
4. Write 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.
5. 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.
183
more scripting
Sum: 5 + 2 = 7
Product: 5 x 2 = 10
#!/bin/bash
let sum="$n1+$n2"
let pro="$n1*$n2"
2. Improve the previous script to test that the numbers are between 1 and 100, exit
with an error if necessary.
echo -n "Enter a number between 1 and 100 : "
read n1
3. Improve the previous script to congratulate the user if the sum equals the product.
if [ $sum -eq $pro ]
then echo Congratulations $sum == $pro
fi
4. Write 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
#
184
more scripting
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
5. 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.
185
Part VII. local user management
Chapter 23. users
Table of Contents
23.1. identify yourself ......................................................................................... 188
23.2. users ........................................................................................................... 189
23.3. passwords ................................................................................................... 191
23.4. home directories ......................................................................................... 196
23.5. user shell .................................................................................................... 197
23.6. switch users with su ................................................................................... 198
23.7. run a program as another user ................................................................... 199
23.8. practice: users ............................................................................................ 201
23.9. solution: users ............................................................................................ 202
23.10. shell environment ..................................................................................... 204
187
users
whoami
The whoami command tells you your username.
[root@RHEL5 ~]# whoami
root
[root@RHEL5 ~]# su - paul
[paul@RHEL5 ~]$ whoami
paul
who
The who command will give you information about who is logged on the system.
[paul@RHEL5 ~]$ who
root tty1 2008-06-24 13:24
sandra pts/0 2008-06-24 14:05 (192.168.1.34)
paul pts/1 2008-06-24 16:23 (192.168.1.37)
who am i
With who am i the who command will display only the line pointing to your current
session.
[paul@RHEL5 ~]$ who am i
paul pts/1 2008-06-24 16:23 (192.168.1.34)
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
paul pts/2 192.168.1.34 05:13 25.00s 0.07s 0.04s top
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)
188
users
23.2. users
user management
User management on any Unix can be done in three complimentary ways. You can
use the graphical tools provided by your distribution. These tools have a look and
feel that depends on the distribution. If you are a novice Linux user on your home
system, then use the graphical tool that is provided by your distribution. This will
make sure that you do not run into problems.
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 across 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!
/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.
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).
189
users
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.
/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.
userdel
You can delete the user yanina with userdel. The -r option of userdel will also remove
the home directory.
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.
190
users
23.3. passwords
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.
/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.
191
users
password encryption
192
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!
193
users
password defaults
/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).
chage
The chage command can be used to set an expiration date for a user account (-E),
set a minimum (-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.
disabling a password
Passwords in /etc/shadow cannot begin with an exclamation mark. When the second
field in /etc/passwd starts with an exclamation mark, then the password can not be
used.
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.
194
users
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!
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!
195
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).
/etc/skel/
When using useradd 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.
196
users
login shell
The /etc/passwd file specifies the login shell for the user. In the screenshot below
you can see that user annelies will log in with the /bin/bash shell, and user laura with
the /bin/ksh shell.
You can use the usermod command to change the shell for a user.
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.
197
users
su to another user
The su command allows a user to run a shell as another user.
[paul@RHEL4b ~]$ su harry
Password:
[harry@RHEL4b paul]$
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]#
su as root
Unless 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]$
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 ~]$
su -
When no username is provided to su or su -, the command will assume root is the
target.
[harry@RHEL4b ~]$ su -
Password:
[root@RHEL4b ~]#
198
users
about sudo
The sudo program allows a user to start a program with the credentials of another
user. Before this works, the system administrator has to set up the /etc/sudoers file.
This can be useful to delegate administrative tasks to another user (without giving
the root password).
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.
setuid on sudo
The sudo binary has the setuid bit set, so any user can run it with the effective userid
of root.
visudo
Check the man page of visudo before playing with the /etc/sudoers file.
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.
199
users
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:~#
200
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.
201
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). Disabling with passwd will erase
the password from /etc/shadow.
202
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 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
On Debian/Ubuntu: cat /etc/shells
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
203
users
/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.
~/.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
~/.bash_login
When .bash_profile does not exist, then bash will check for ~/.bash_login and
execute it.
204
users
~/.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.
~/.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
205
users
~/.bash_logout
When exiting bash, it can execute ~/.bash_logout. Debian and Red Hat both use this
opportunity to clear the screen.
if [ "$SHLVL" = 1 ]; then
[ -x /usr/bin/clear_console ] && /usr/bin/clear_console -q
fi
/usr/bin/clear
Debian overview
Below is a table overview of when Debian is running any of these bash startup scripts.
RHEL5 overview
Below is a table overview of when Red Hat Enterprise Linux 5 is running any of
these bash startup scripts.
206
Chapter 24. groups
Table of Contents
24.1. about groups ............................................................................................... 208
24.2. groupadd ..................................................................................................... 208
24.3. /etc/group .................................................................................................... 208
24.4. usermod ...................................................................................................... 209
24.5. groupmod ................................................................................................... 209
24.6. groupdel ...................................................................................................... 209
24.7. groups ......................................................................................................... 209
24.8. gpasswd ...................................................................................................... 210
24.9. vigr ............................................................................................................. 210
24.10. practice: groups ........................................................................................ 211
24.11. solution: groups ........................................................................................ 212
207
groups
24.2. groupadd
Groups can be created with the groupadd command. The example below shows the
creation of five (empty) groups.
24.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.
208
groups
24.4. usermod
Group membership can be modified with the useradd or usermod command.
root@laika:~# usermod -a -G tennis inge
root@laika:~# usermod -a -G tennis katrien
root@laika:~# usermod -a -G salsa katrien
root@laika:~# usermod -a -G snooker sandra
root@laika:~# usermod -a -G formula1 annelies
root@laika:~# tail -5 /etc/group
tennis:x:1006:inge,katrien
football:x:1007:
snooker:x:1008:sandra
formula1:x:1009:annelies
salsa:x:1010:katrien
root@laika:~#
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.
24.5. groupmod
You can change the group name with the groupmod command.
root@laika:~# groupmod -n darts snooker
root@laika:~# tail -5 /etc/group
tennis:x:1006:inge,katrien
football:x:1007:
formula1:x:1009:annelies
salsa:x:1010:katrien
darts:x:1008:sandra
24.6. groupdel
You can permanently remove a group with the groupdel command.
root@laika:~# groupdel tennis
root@laika:~#
24.7. groups
A user can type the groups command to see a list of groups where the user belongs to.
[harry@RHEL4b ~]$ groups
harry sports
[harry@RHEL4b ~]$
209
groups
24.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
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.
24.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.
210
groups
6. Make someone responsible for managing group membership of foot and sports.
Test that it works.
211
groups
6. Make someone responsible for managing group membership of foot and sports.
Test that it works.
gpasswd -A (to make manager)
212
Part VIII. file security
Chapter 25. standard file permissions
Table of Contents
25.1. file ownership ............................................................................................ 215
25.2. list of special files ...................................................................................... 216
25.3. permissions ................................................................................................. 217
25.4. practice: standard file permissions ............................................................. 222
25.5. solution: standard file permissions ............................................................. 223
214
standard file permissions
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.
chgrp
You can change the group owner of a file using the chgrp command.
root@laika:/home/paul# touch FileForPaul
root@laika:/home/paul# ls -l FileForPaul
-rw-r--r-- 1 root root 0 2008-08-06 14:11 FileForPaul
root@laika:/home/paul# chgrp paul FileForPaul
root@laika:/home/paul# ls -l FileForPaul
-rw-r--r-- 1 root paul 0 2008-08-06 14:11 FileForPaul
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.
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
215
standard file permissions
Below a screenshot of a character device (the console) and a block device (the hard
disk).
And here you can see a directory, a regular file and a symbolic link.
216
standard file permissions
25.3. permissions
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.
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.
217
standard file permissions
permission examples
Some example combinations on files and directories are seen in this screenshot. The
name of the file explains the permissions.
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 summarise, 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.
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
218
standard file permissions
219
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.
220
standard file permissions
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.
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.
mkdir -m
When creating directories with mkdir you can use the -m option to set the mode.
This screenshot explains.
paul@debian5~$ mkdir -m 700 MyDir
paul@debian5~$ mkdir -m 777 Public
paul@debian5~$ ls -dl MyDir/ Public/
drwx------ 2 paul paul 4096 2011-10-16 19:16 MyDir/
drwxrwxrwx 2 paul paul 4096 2011-10-16 19:16 Public/
221
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.
222
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
223
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
224
Chapter 26. advanced file permissions
Table of Contents
26.1. sticky bit on directory ................................................................................ 226
26.2. setgid bit on directory ................................................................................ 226
26.3. setgid and setuid on regular files ............................................................... 227
26.4. practice: sticky, setuid and setgid bits ....................................................... 228
26.5. solution: sticky, setuid and setgid bits ....................................................... 229
225
advanced file permissions
The sticky bit can also be set with octal permissions, it is binary 1 in the first of four
triplets.
root@RHELv4u4:~# chmod 1775 /project55/
root@RHELv4u4:~# ls -ld /project55
drwxrwxr-t 2 root root 4096 Feb 7 17:38 /project55
root@RHELv4u4:~#
You will typically find the sticky bit on the /tmp directory.
root@barry:~# ls -ld /tmp
drwxrwxrwt 6 root root 4096 2009-06-04 19:02 /tmp
You can use the find command to find all setgid directories.
paul@laika:~$ find / -type d -perm -2000 2> /dev/null
/var/log/mysql
/var/log/news
/var/local
...
226
advanced file permissions
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.
227
advanced 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.
228
advanced 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
229
advanced file permissions
root@laika:~/attr# lsattr
----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#
230
Chapter 27. access control lists
Table of Contents
27.1. acl in /etc/fstab ........................................................................................... 232
27.2. getfacl ......................................................................................................... 232
27.3. setfacl ......................................................................................................... 232
27.4. remove an acl entry ................................................................................... 233
27.5. remove the complete acl ............................................................................ 233
27.6. the acl mask ............................................................................................... 233
27.7. eiciel ........................................................................................................... 234
Standard Unix permissions might not be enough for some organisations. This chapter
introduces access control lists or acl's to further protect files and directories.
231
access control lists
27.2. getfacl
Reading acls can be done with /usr/bin/getfacl. This screenshot shows how to read
the acl of file33 with getfacl.
paul@laika:~/test$ getfacl file33
# file: file33
# owner: paul
# group: paul
user::rw-
group::r--
mask::rwx
other::r--
27.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.
Then we add the group tennis with octal permission 6 to the acl of the same file.
paul@laika:~/test$ setfacl -m g:tennis:6 file33
232
access control lists
Note that omitting the u or g when defining the acl for an account will default it to
a user account.
233
access control lists
27.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.
234
Chapter 28. file links
Table of Contents
28.1. inodes ......................................................................................................... 236
28.2. about directories ......................................................................................... 237
28.3. hard links ................................................................................................... 238
28.4. symbolic links ............................................................................................ 239
28.5. removing links ........................................................................................... 239
28.6. practice : links ............................................................................................ 240
28.7. solution : links ............................................................................................ 241
An average computer using Linux has a file system with many hard links and
symbolic links.
To understand links in a file system, you first have to understand what an inode is.
235
file links
28.1. inodes
inode contents
An inode is a data structure that contains metadata about a file. When the file system
stores a new file on the hard disk, it stores not only the contents (data) of the file, but
also extra properties like the name of the file, the creation date, its permissions, the
owner of the file, and more. All this information (except the name of the file and the
contents of the file) is stored in the inode of the file.
The ls -l command will display some of the inode contents, as seen in this screenshot.
root@rhel53 ~# ls -ld /home/project42/
drwxr-xr-x 4 root pro42 4.0K Mar 27 14:29 /home/project42/
inode table
The inode table contains all of the inodes and is created when you create the file
system (with mkfs). You can use the df -i command to see how many inodes are
used and free on mounted file systems.
root@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.
inode number
Each inode has a unique number (the inode number). You can see the inode numbers
with the ls -li command.
236
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.
a directory is a table
A directory is a special kind of file that contains a table which maps filenames
to inodes. Listing our current directory with ls -ali will display the contents of the
directory file.
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$
. 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.
237
file links
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.
238
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).
239
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.
240
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
241
Part IX. Appendices
Appendix A. certifications
A.1. 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.
243
certifications
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
towards database application developers, and the CMDBA towards database
administrators. Both tracks require two exams each. The MySQL cluster DBA
certification requires CMDBA certification and passing the CMCDBA exam.
Novell CLP/CLE
To become a Novell Certified Linux Professional, you have to take a live practicum.
This is a VNC session to a set of real SLES servers. You have to perform several
tasks and are free to choose your method (commandline or YaST or ...). No multiple
choice involved.
Sun Solaris
Sun uses the classical formula of multiple choice exams for certification. Passing
two exams for an operating system gets you the Solaris Certified Administrator for
Solaris X title.
Other certifications
There are many other lesser known certifications like EC council's Certified Ethical
Hacker, CompTIA's Linux+, and Sair's Linux GNU.
244
Appendix B. 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.
245
keyboard settings
246
Appendix C. hardware
C.1. buses
about buses
Hardware components communicate with the Central Processing Unit or cpu over
a bus. The most common buses today are usb, pci, agp, pci-express and pcmcia aka
pc-card. These are all Plag and Play buses.
Older x86 computers often had isa buses, which can be configured using jumpers
or dip switches.
/proc/bus
To list the buses recognised 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 ?
/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:~#
/var/lib/usbutils/usb.ids
The /var/lib/usbutils/usb.ids file contains a gzipped list of all known usb devices.
247
hardware
/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....
...
C.2. interrupts
about interrupts
An interrupt request or IRQ is a request from a device to the CPU. A device raises
an interrupt when it requires the attention of the CPU (could be because the device
has data ready to be read by the CPU).
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.
/proc/interrupts
You can see a listing of interrupts on your system in /proc/interrupts.
248
hardware
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
dmesg
You can also use dmesg to find irq's allocated at boot time.
paul@laika:~$ dmesg | grep "irq 1[45]"
[ 28.930069] ata3: PATA max UDMA/133 cmd 0x1f0 ctl 0x3f6 bmdma 0x2090 irq 14
[ 28.930071] ata4: PATA max UDMA/133 cmd 0x170 ctl 0x376 bmdma 0x2098 irq 15
C.3. io ports
about io ports
Communication in the other direction, from CPU to device, happens through IO
ports. The CPU writes data or control codes to the IO port of the device. But this is
not only a one way communication, the CPU can also use a device's IO port to read
status information about the device. Unlike interrupts, ports cannot be shared!
/proc/ioports
You can see a listing of your system's IO ports via /proc/ioports.
249
hardware
C.4. dma
about dma
A device that needs a lot of data, interrupts and ports can pose a heavy load on the
cpu. With dma or Direct Memory Access a device can gain (temporary) access to
a specific range of the ram memory.
/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.
250
/etc/sysconfig/harddisks, 56
Index /etc/sysconfig/hwconf, 56
/etc/sysconfig/keyboard, 56
Symbols /etc/X11/xorg.conf, 55
; (shell), 84 /export, 57
!! (shell), 101 /home, 57
! (bash history), 101 /lib, 54
! (file globbing), 108 /lib/kbd/keymaps/, 56
? (file globbing), 107 /lib/modules, 54
/, 28, 52 /lib32, 54
/bin, 53, 76 /lib64, 54
/bin/bash, 73, 204 /media, 57
/bin/cat, 53 /opt, 54
/bin/csh, 73 /proc, 36, 60
/bin/date, 53 /proc/bus, 247
/bin/ksh, 73, 204 /proc/bus/pci, 248
/bin/rm, 77 /proc/bus/usb/devices, 247
/bin/sh, 73 /proc/cpuinfo, 61
/boot, 55 /proc/dma, 250
/boot/grub, 55 /proc/interrupts, 62, 248
/boot/grub/grub.cfg, 55 /proc/ioports, 249
/boot/grub/grub.conf, 55 /proc/kcore, 62
/dev, 36, 59 /proc/sys, 61
/dev/null, 59, 117 /root, 57
/dev/pts/1, 59 /run, 67
/dev/random, 70 /sbin, 53, 76
/dev/tty1, 59 /srv, 57
/dev/urandom, 69, 71 /sys, 63
/dev/zero, 70 /tmp, 58, 226
/etc, 55 /usr, 64
/etc/bashrc, 205 /usr/bin, 64
/etc/default/useradd, 190 /usr/bin/getfacl, 232
/etc/fstab, 232 /usr/bin/passwd, 227
/etc/group, 208, 215 /usr/bin/setfacl, 232
/etc/gshadow, 210 /usr/include, 64
/etc/hosts, 71 /usr/lib, 64
/etc/init.d/, 55 /usr/local, 64
/etc/inputrc, 204 /usr/share, 65
/etc/login.defs, 194 /usr/share/games, 65
/etc/passwd, 132, 189, 195, 195, 197, 215 /usr/share/man, 65
/etc/profile, 204 /usr/src, 65
/etc/resolv.conf, 71 /var, 66
/etc/shadow, 191, 193, 227 /var/cache, 66
/etc/shells, 158, 197 /var/lib, 67
/etc/skel, 56, 196 /var/lib/rpm, 67
/etc/sudoers, 199, 199 /var/lib/usbutils/usb.ids, 247
/etc/sysconfig, 56 /var/lock, 67
/etc/sysconfig/firstboot, 56 /var/log, 66
251
Index
252
Index
comm(1), 129 F
command line scan, 74 Fedora, 5
command mode(vi), 147 FHS, 52
copyleft, 8 file(1), 36, 54
copyright, 7, 7 file globbing, 106
cp(1), 38, 38 file ownership, 215
cpu, 247 Filesystem Hierarchy Standard, 52
crypt, 192 filters, 123
csh, 158 find(1), 137, 226, 227, 238
Ctrl d, 46 FireWire, 63
ctrl-r, 102 for (bash), 165
current directory, 27 FOSS, 7
cut, 132 four freedoms, 8
cut(1), 126 Free Software, 7
free software, 8
D freeware, 7
daemon, 23 function (shell), 182
date, 138
Debian, 5 G
Dennis Ritchie, 3 gcc(1), 193
devfs, 63 getfacl, 232
df -i, 236 getopts, 174
directory, 237 GID, 208
distribution, 4 glob(7), 107
distributions, 52 GNU, 3
dma, 250 gpasswd, 210
dmesg(1), 249, 250 GPL, 8
dumpkeys(1), 56 GPLv3, 8
grep(1), 124
E grep -i, 124
echo, 74 grep -v, 125
echo(1), 74, 75 groupadd(1), 208
echo $-, 95 groupdel(1), 209
echo *, 109 groupmod(1), 209
Edubuntu, 5 groups, 208
eiciel, 234 groups(1), 209
ELF, 54 gunzip(1), 140
elif, 165 gzip, 140
embedding(shell), 96 gzip(1), 140
env(1), 93, 93
environment variable, 90 H
EOF, 118 hard link, 238
escaping (shell), 109 head(1), 45
eval, 179 here directive, 47
executables, 53 here document, 118
exit (bash), 102 here string, 118
export, 93 hidden files, 29
HP, 3
253
Index
254
Index
255
Index
W
w(1), 188
wc(1), 127
whatis(1), 23
whereis(1), 24
which(1), 76
while (bash), 166
white space(shell), 74
who, 132
who(1), 188
who am i, 188
whoami(1), 188
wild cards, 108
X
X, 55
X Window System, 55
Z
zcat, 140
zmore, 140
256
UNIT-II
DBMS
Lab Exercise-1
Table :Employee
Table : Department
d_no d.name
001 CSE
002 EEE
003 ECE
004 AI
005 MEE
1. Create the above tables
2. Insert the records as shown
3. Show the structure of the table
4. Retrieve the details of all employees
5. Retrieve the names of the employees
6. Retrieve the name and salary of all employees
7. List details of all employees of age above 30
8. List the names of employee from banglore who are of age 25
9. List the name and age of female employee who draw salary
between 20000 and 50000
10. List the employees not from banglore
11. List the name of male employees who are above 40 and female
below 35
12. List the age of employees who belong to the city
banglore and draws salary not more than 20000
13. Update the emp_no 105 to 106
14. Delete the details of record whose emp_no is 101
15. Display the details of employee table whose designation is not
programmer
16. Write a SQL statement to display all customers, who are either
belongs to the city banglore or of gender male
17. Change all cities “Chennai” to “Mumbai”
18. Rename the table employee to emp.
19. List the d_no of department ECE
20. Add a new column phone number to the employee table
21. Assign phone numbers to existing employees.
22. Display the unique designations for the employees.
Shell programs
1. hello world program
#!/bin/sh
# comment lines start with the # character
echo "Hello world"
2. #!/bin/sh
#this program is meant for printing welcome statemnet
echo "Hello world"
3. Introducing variables
#!/bin/sh
number=25
name="Bill Gates"
echo "the number is: $number and the name is : $name"
4. Introducing variables
echo "Enter name: "
read name
echo "How many friends do you have? "
read number
echo "$name has $number friends"
5. echo "Enter name: "
read name
echo "How many friends do you have? "
read number
echo "$name has $number friends"
6. #!/bin/sh
echo "enter your height"
read height
echo "My height is $height"
7. #!/bin/sh
echo "enter your first name and last name"
read firstname lastname
echo "May name and my address : $firstname $lastname $doornumber $street $district $state"
8. #!/bin/sh
echo "Enter amount of book : "
read cost
echo "The total cost in dollar is: \$$cost"
9. #!/bin/sh
i=5
#expr $i + 1
i= `expr $i + 1`
echo "the value of i is: $i"
10. addition
#!/bin/sh
echo "enter first number"
read number1
echo "enter second number"
read number2
#expr $number1 + $number2
#back quotes used ofr assigning expresseion result to another varikable
sum=`expr $number1 + $number2`
echo "the sum is: $sum"
11. multiplication
i=2
i=`expr $i \* 3`
echo $i
12. multiplication
#!/bin/sh
echo "enter first number"
read number1
echo "enter second number"
read number2
#expr $number1 + $number2
#back quotes used ofr assigning expresseion result to another varikable
res=`expr $number1 \* $number2`
echo "the result is: $res"
13. expression
num=2
echo $y
user=`whoami`
echo "user name is" $user
numusers=`who | wc -l`
echo "Hi $user! There are $numusers users logged on."
14. if else
#!/bin/sh
user=`whoami`
if [ $user = "am" ]
then
echo "my user naem is amma!"
else
echo "My user name is not AMMA!"
fi
15. if else if
#!/bin/sh
users=`who | wc -l`
if [ $users -ge 4 ]
then
echo "Heavy load"
elif [ $users -gt 1 ]
then
echo "Medium load"
else
echo "less load "
fi
fi
fi
loops
19.
#!/bin/sh
resp="no"
while [ $resp != "yes" ]
do
echo "Wakeup [yes/no]?"
read resp
done
read n
i=1
while [ $i -le $n ]
do
echo "hi"
i=`expr $i + 1`
#read resp
done
#!/bin/sh
echo "enter n:"
read n
echo " nvalue is" $n
i=1
while [ $i -le $n ]
do
echo "hello"
i=`expr $i + 1`
done
#!/bin/sh
if [ -f displayhello.sh ]
then
echo "We have found the file!"
cat displayhello.sh
else
echo "Keep looking!"
fi
s1="amrita"
s2="amrita"
if [ $s1 = $s2 ]
then
echo "strings are equal"
else
echo " not equal"
fi
#!/bin/sh
if [ `who | grep amma | wc -l` -ge 1 -a `whoami` != "amma" ]
then
echo "Bill is loading down the machine!"
else
echo "All is well!"
fi
25. logical opeartor usage
#!/bin/sh
read a
read b
read c
if [ $a -gt $b -a $a -gt $c ]
then
echo "a is greater!"
else
echo "not greater!"
fi
#!/bin/bash
for i in 7 9 2 3 4 5
do
echo $i
done
28. break
#!/bin/bash
#breaking a loop
num=1
while [ $num -lt 10 ]
do
echo "$num"
if [ $num -eq 2 ]
then
break
fi
num=`expr $num + 1`
done
echo "Loop is complete"
29. continue
for i in 1 2 3 4 5 6 7 8 9
do
if [ $i -eq 5 ]
then
continue
fi
echo "I is equal to: $i"
done
#!/bin/bash
for table in {2..20..2}
do
echo "table for 2: $table"
done
execute with : $chmod +x filename.sh
./filename.sh
33. #!/bin/bash
for (( i=1; i<=10; i++ ))
do
echo "$i"
done
33. The grep filter searches a file for a particular pattern of characters, and displays all
lines that contain that pattern. The pattern that is searched in the file is referred to as
the regular expression (grep stands for globally search for regular expression and
print out).
Syntax:
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.
example:
$cat > geekfile.txt
Output:
unix is great os. unix is opensource. unix is free os.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .u
Displaying the count of number of matches : We can find the number of lines that
matches the given string/pattern
2
3. Display the file names that matches the pattern : We can just display the files that
contains the given string/pattern.
$grep -l "unix" *
or
geekfile.txt
4. Checking for the whole words in a file : By default, grep matches the given
string/pattern even if it found as a substring in a file. The -w option to grep makes it
match only the whole words.
$ grep -w "unix" geekfile.txt
Output:
unix
unix
unix
unix
unix
unix
6. Show line number while displaying the output using grep -n : To show the line
number of file with the line matched.
Shell Programming
2
SHELLS
A
shell can be used in one of two
ways:
A command interpreter, used
interactively
A programming language, to write shell
scripts (your own custom commands)
3g
r
a
m
m
i
n
g
4g
r
a
m
m
i
n
g
5g
r
a
m
m
i
n SHELL SCRIPTS
g
SHELL VARIABLES
i
n
g
SHELL VARIABLES
i
n
g
To use a variable,
precede the name
with a “$”:
$ cat test1
#!/bin/sh
number=25
name="Bill Gates"
echo "$number $name"
$ test1
25 Bill Gates
$
9g
r
a
m
m
USER INPUT
i
n
g
Use the read command to get and store input from the
user.
$ cat test2
#!/bin/sh
echo "Enter name: "
read name
echo "How many girlfriends do you have? "
read number
echo "$name has $number girlfriends!"
$ test2
Enter name:
Bill Gates
How many girlfriends do you have?
too many
Bill Gates has too many girlfriends!
0g
r
a
m
USER INPUT
m
i
n
g read reads one line of input from the keyboard and
assigns it to one or more user-supplied variables.
$ cat test3
#!/bin/sh
echo "Enter name and how many girlfriends:"
read name number
echo "$name has $number girlfriends!"
$ test3
Enter name and how many girlfriends:
Bill Gates 63
Bill has Gates 63 girlfriends!
$ test3
Enter name and how many girlfriends:
BillG 63
BillG has 63 girlfriends!
$ test3
Enter name and how many girlfriends:
Bill
Bill has girlfriends!
Leftover input words are all assigned to the last variable.
1g
r
a
m
m
$
i
n
g
$
i
n
g
BACKQUOTES:
r
a
m
COMMAND SUBSTITUTION
m
i
n
g
CONTROL FLOW
i
n
g
Relational operators:
-eq, -ne, -gt, -ge, -lt, -le
File operators:
-f file True if file exists and is not a directory
-d file True if file exists and is a directory
-s file True if file exists and has a size > 0
String operators:
-z string True if the length of string is zero
-n string True if the length of string is nonzero
s1 = s2 True if s1 and s2 are the same
s1 != s2 True if s1 and s2 are different
s1 True if s1 is not the null string
3g
r
a
m
m
i
n FILE OPERATOR EXAMPLE
g
$ cat test9
#!/bin/sh
if [ -f letter1 ]
then
echo "We have found the evidence!"
cat letter1
else
echo "Keep looking!"
fi
$ test9
We have found the evidence!
How much would it cost to buy Apple Computer?
Best,
Bill
4g
r
a
m
m
$ cat test10
#!/bin/sh
if [ `who | grep gates | wc -l` -ge 1 -a `whoami` != “gates" ]
then
echo "Bill is loading down the machine!"
else
echo "All is well!"
fi
$ test10
Bill is loading down the machine!
5g
r
a
m
m
i
n
g
WHILE
The while statement loops indefinitely, while the
condition is true, such as a user-controlled condition:
$ cat test11
#!/bin/sh
resp="no"
while [ $resp != "yes" ]
do
echo "Wakeup [yes/no]?"
read resp
done
$ test11
Wakeup [yes/no]?
no
Wakeup [yes/no]?
y
Wakeup [yes/no]?
yes
$
6g
r
a
m
WHILE
m
i
n
while can also do normal incrementing loops:
g $ cat fac
#!/bin/sh
echo "Enter number: "
read n
fac=1
i=1
while [ $i -le $n ]
do
fac=`expr $fac \* $i`
i=`expr $i + 1`
done
echo "The factorial of $n is $fac"
$ fac
Enter number:
5
The factorial of 5 is 120
7g
r
a
m
m
i
n
g
BREAK
The break command works like in C++, breaking out
of the innermost loop :
$ cat test12
#!/bin/sh
while [ 1 ]
do
echo "Wakeup [yes/no]?"
read resp
if [ $resp = "yes" ]
then
break
fi
done
$ test12
Wakeup [yes/no]?
no
Wakeup [yes/no]?
y
Wakeup [yes/no]?
yes
g
r
a
m
m
28
g
r
a
m
m
Input
prompting user
command line arguments
Decision:
if-then-else
case
Repetition
do-while, repeat-until
for
select
Functions
Traps 29
g
r
a
m
m
USER INPUT
i
n
g
or
#! /bin/sh
read -p "enter your name: " first last
31
g
r
a
m
m
Parameter Meaning
$0 Name of the current shell script
$1-$9 Positional parameters 1 through 9
$# The number of positional parameters
$* All positional parameters, “$*” is one string
$@ All positional parameters, “$@” is a set of strings
$? Return status of most recently executed command
$$ Process id of current process
32
g
r
a
m
m EXAMPLES: COMMAND LINE
ARGUMENTS
i
n
g
if-then-else
case
loops
for
while
until
34
g
r
a
m
m
IF STATEMENT
i
n
g
if command
then
statements
fi
35
g
r
a
m
m
TEST COMMAND
i
n
g
Syntax:
test expression
[ expression ]
evaluates ‘expression’ and returns true or false
Example:
if test –w "$1"
then
echo "file $1 is write-able"
fi
36
g
r
a
m
m
if [ condition ]; then
statements
fi
37
g
r
a
m
m
if [ condition ]; then
statements-1
else
statements-2
fi
38
g
r
a
m
m
THE IF…STATEMENT
i
n
g
if [ condition ]; then
statements
elif [ condition ]; then
statement
else
statements
fi
! not
and, or
&& and must be enclosed within
|| or
[[ ]]
41
g
r
a
m
m
Purpose:
To execute commands in “command-list” as long
as “expression” evaluates to false
Syntax:
until [ expression ]
do
command-list
done
42
g
r
a
m
m
#!/bin/bash
COUNTER=20
until [ $COUNTER -lt 10 ]
do
echo $COUNTER
let COUNTER-=1
done
43
g
r
a
m
m
Purpose:
To execute commands as many times as the
number of words in the “argument-list”
Syntax:
for variable in argument-list
do
commands
done
44
g
r
a
m
m
#!/bin/bash
for i in 7 9 2 3 4 5
do
echo $i
done
45
g
r
a
m
m
46
g
r
a
m
m
while [ condition ]
do
cmd-1
break This iteration is over
cmd-n and there are no more
iterations
done
echo "done"
47
g
r
a
m
m
while [ condition ]
do
cmd-1 This iteration is
continue over; do the next
cmd-n iteration
done
echo "done"
48
g
r
a
m
m
EXAMPLE:
i
n
g
for index in 1 2 3 4 5 6 7 8 9 10
do
if [ $index –le 3 ]; then
echo "continue"
continue
fi
echo $index
if [ $index –ge 8 ]; then
echo "break"
break
fi
done 49
0g
r
a
m
m
i
n
g
1g
r
a
m
m
i
n
g
2g
r
a
m
m
i
n
g
g
r
a
m
m
SHELL PROGRAMMING
i
n
g
Sequence
Decision:
if-then-else
case
Repetition DONE !
do-while, repeat-until
for
53
15 simple TOP command examples on Linux to
monitor processes
One of the most basic command to monitor processes on Linux is the top
command. As the name suggests, it shows the top processes based on certain
criterias like cpu usage or memory usage.
The processes are listed out in a list with multiple columns for details like
process name, pid, user, cpu usage, memory usage.
Apart from the list of processes, the top command also shows brief stats
about average system load, cpu usage and ram usage on the top.
This post shows you some very simple examples of how to use the top
command to monitor processes on your linux machine or server.
To check your top command version and variant use the -v option
$ top -v
This post focuses on the top command coming from the procps-ng project.
This is the version available on most modern distros like Ubunut, Fedora,
CentOS etc.
1. Display processes
To get a glimpse of the running processes, just run the top command as is
without any options like this.
$ top
And immediately the output would be something like this -
%Cpu(s): 2.3 us, 0.5 sy, 0.0 ni, 97.1 id, 0.2 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem: 8165300 total, 6567896 used, 1597404 free, 219232 buffers
KiB Swap: 1998844 total, 0 used, 1998844 free. 2445372 cached Mem
The screen contains a lot of information about the system. The header areas
include uptime, load average, cpu usage, memory usage data.
The process list shows all the processes with various process specific details
in separate columns. Some of the column names are pretty self explanatory.
PID - Process ID
USER - The system user account running the process.
%CPU - CPU usage by the process.
%MEM - Memory usage by the process
COMMAND - The command (executable file) of the process
To find the process consuming the most cpu or memory, simply sort the list.
Press M key ( yes, in capital, not small ) to sort the process list by memory
usage. Processes using the most memory are shown first and rest in order.
Here are other options to sort by CPU usage, Process ID and Running Time -
%Cpu(s): 5.2 us, 1.7 sy, 0.0 ni, 93.2 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem: 8165300 total, 6089388 used, 2075912 free, 199060 buffers
KiB Swap: 1998844 total, 0 used, 1998844 free. 1952412 cached Mem
Press the 'd' key, and top will ask you to enter the time interval between each
refresh. You can enter numbers smaller than 1 second as well, like 0.5. Enter
the desired interval and hit Enter.
%Cpu(s): 1.3 us, 0.4 sy, 0.0 ni, 98.1 id, 0.2 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem: 8165300 total, 7899784 used, 265516 free, 238068 buffers
KiB Swap: 1998844 total, 5432 used, 1993412 free. 3931316 cached Mem
Press the 'o' or 'O' to activate filter prompt. It will show a line indicating the
filter format like this -
COMMAND=apache
Now top will show only those processes whose COMMAND field contains the
value apache.
Here is another filter example that shows processes consuming CPU actively
-
%CPU>0.0
See active filters - Press Ctrl+o to see currently active filters
Clear filter - Press '=' key to clear any active filters
%Cpu(s): 11.8 us, 3.3 sy, 0.6 ni, 84.2 id, 0.0 wa, 0.0 hi, 0.1 si, 0.0 st
KiB Mem: 8165300 total, 6108824 used, 2056476 free, 198680 buffers
KiB Swap: 1998844 total, 0 used, 1998844 free. 1963436 cached Mem
Hiding the header information area, makes more processes visible in the list.
12. Forest mode - 'V'
Pressing 'V' will display the processes in a parent child hierarchy. It looks
something like this -
%Cpu(s): 6.1 us, 2.1 sy, 0.0 ni, 91.8 id, 0.1 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem: 8165300 total, 3968224 used, 4197076 free, 82868 buffers
KiB Swap: 1998844 total, 0 used, 1998844 free. 1008416 cached Mem
%Cpu0 : 3.6 us, 3.6 sy, 0.0 ni, 92.9 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu1 : 3.1 us, 3.6 sy, 0.0 ni, 93.3 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu2 : 7.6 us, 1.8 sy, 0.0 ni, 90.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu3 : 9.6 us, 2.6 sy, 0.0 ni, 87.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem: 8165300 total, 7118864 used, 1046436 free, 204224 buffers
KiB Swap: 1998844 total, 0 used, 1998844 free. 3410364 cached Mem
Fields Management for window 1:Def, whose current sort field is %CPU
Navigate with Up/Dn, Right selects for move then <Enter> or Left commits,
'd' or <Space> toggles display, 's' sets sort. Use 'q' or <Esc> to end!
* %CPU = CPU Usage CODE = Code Size (Ki nsUTS = UTS namespace
The fields marked * or bold are the fields that are displayed, in the order in
which they appear in this list.
Navigate the list using up/down arrow keys and press 'd' to toggle the
display of that field. Once done, press q to go back to the process list
The following output displays only PID, USER, CPU, MEMORY and
COMMAND columns.
%Cpu(s): 6.3 us, 2.0 sy, 0.2 ni, 91.5 id, 0.1 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem: 8165300 total, 6089244 used, 2076056 free, 189272 buffers
KiB Swap: 1998844 total, 0 used, 1998844 free. 1902836 cached Mem
Here is a simple example that shows the Cpu usage at intervals of 1 second.
Each panel can be sorted on a different column. Press 'a' to move through the
panels. Each panel can have a different set of fields displayed and different
sort columns.
top command multiple panels
Solution: file contents
1. Display the first 12 lines of /etc/services.
head -12 /etc/services
2. Display the last line of /etc/passwd.
tail -1 /etc/passwd
3. Use cat to create a file named count.txt that looks like this:
cat > count.txt One Two Three Four Five (followed by Ctrl-d)
4. Use cp to make a backup of this file to cnt.txt.
cp count.txt cnt.txt
5. Use cat to make a backup of this file to catcnt.txt.
cat count.txt > catcnt.txt
6. Display catcnt.txt, but with all lines in reverse order (the last line first).
tac catcnt.txt
7. Use more to display /var/log/messages.
more /var/log/messages
8. Display the readable character strings from the /usr/bin/passwd command.
strings /usr/bin/passwd
9. Use ls to find the biggest file in /etc.
ls -lrS /etc
10. Open two terminal windows (or tabs) and make sure you are in the same directory in both.
Type echo this is the first line > tailing.txt in the first terminal, then issue tail -f tailing.txt in the
second terminal. Now go back to the first terminal and type echo This is another line >> tailing.txt
(note the double >>), verify that the tail -f in the second terminal shows both lines. Stop the tail -f
with Ctrl-C.
11. Use cat to create a file named tailing.txt that contains the contents of tailing.txt followed by
the contents of /etc/passwd.
cat /etc/passwd >> tailing.txt
12. Use cat to create a file named tailing.txt that contains the contents of tailing.txt preceded by
the contents of /etc/passwd.
mv tailing.txt tmp.txt ; cat /etc/passwd tmp.txt > tailing.txt
Chapter – 15
15.1. stdin, stdout, and stderr
The shell (and almost every other Linux command) takes input from stdin (stream 0) and sends
output to stdout (stream 1) and error messages to stderr (stream 2) .
The keyboard often serves as stdin, stdout and stderr both go to the display. The shell allows you
to redirect these streams.
15.2. output redirection
> stdout
stdout can be redirected with a greater than sign. While scanning the line, the shell will see the >
sign and will clear the file.
[paul@RHELv4u3 ~]$ echo It is cold today! It is cold today!
[paul@RHELv4u3 ~]$ echo It is cold today! > winter.txt
[paul@RHELv4u3 ~]$ cat winter.txt It is cold today!
[paul@RHELv4u3 ~]$
Note that the > notation is in fact the abbreviation of 1> (stdout being referred to as stream 1.
output file is erased
To repeat: 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!
[paul@RHELv4u3 ~]$ cat winter.txt It is cold today!
[paul@RHELv4u3 ~]$ zcho It is cold today! > winter.txt
-bash: zcho: command not found
[paul@RHELv4u3 ~]$ cat winter.txt
[paul@RHELv4u3 ~]$
noclobber
Erasing a file while using > can be prevented by setting the noclobber option.
[paul@RHELv4u3 ~]$ cat winter.txt It is cold today!
[paul@RHELv4u3 ~]$ set -o noclobber
[paul@RHELv4u3 ~]$ echo It is cold today! > winter.txt
-bash: winter.txt: cannot overwrite existing file
[paul@RHELv4u3 ~]$ set +o noclobber
[paul@RHELv4u3 ~]$
>> append
Use >> to append output to a file.
[paul@RHELv4u3 ~]$ echo It is cold today! > winter.txt
[paul@RHELv4u3 ~]$ cat winter.txt It is cold today!
[paul@RHELv4u3 ~]$ echo Where is the summer ? >> winter.txt
[paul@RHELv4u3 ~]$ cat winter.txt It is cold today! Where is the summer ?
[paul@RHELv4u3 ~]$
The touch command is the easiest way to create new, empty files. It is also used to change
the timestamps (i.e., dates and times of the most recent access and modification) on existing files
and directories. touch's syntax is
When used without any options, touch creates new files for any file names that are provided
as arguments (i.e., input data) if files with such names do not already exist. Touch can create any
number of files simultaneously.
Thus, for example, the following command would create three new, empty files
named file1, file2 and file3:
All Linux systems have a directory structure that starts at the root directory. The root directory is
represented by a forward slash, like this: /. Everything that exists on your Linux system can be
found below this root directory. Let's take a brief look at the contents of the root directory.
[paul@RHELv4u3 ~]$ ls / bin dev home media mnt proc sbin srv tftpboot usr boot etc
lib misc opt root selinux sys tmp var
2. binary directories
Binaries are files that contain compiled source code (or machine code). Binaries can be
executed on the computer. Sometimes binaries are called executables.
/bin
The /bin directory contains binaries for use by all users. According to the FHS the / bin
directory should contain /bin/cat and /bin/date (among others).
3. /lib
Binaries found in /bin and /sbin often use shared libraries located in /lib. Below is a screenshot
of the partial contents of /lib.
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
4. /lib/modules
Typically, the Linux kernel loads kernel modules from /lib/modules/$kernelversion/. This
directory is discussed in detail in the Linux kernel chapter.
/lib32 and /lib64
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. A 64-bit computer may have some 32-bit binaries and
libraries for compatibility with legacy applications. This screenshot uses the file utility to
demonstrate the difference.
configuration directories
1. /boot
The /boot directory contains all files needed to boot the computer. These files don't change
very often. On Linux systems you typically find the /boot/grub directory here. /boot/grub
contains /boot/grub/grub.cfg (older systems may still have /boot/ grub/grub.conf) which
defines the boot menu that is displayed before the kernel starts.
2. /etc
All of the machine-specific configuration files should be located in /etc. Historically /etc stood
for etcetera, today people often use the Editable Text Configuration backronym.
Many times the name of a configuration files is the same as the application, daemon, or
protocol with .conf added as the extension.
Data directories
1. /home
Users can store personal or project data under /home. It is common (but not mandatory by the
fhs) practice to name the users home directory after the user name in the format
/home/$USERNAME. For example:
paul@ubu606:~$ ls /home geert annik sandra paul tom
2. /mnt
The /mnt directory should be empty and should only be used for temporary mount points
(according to the FHS).
Unix and Linux administrators used to create many directories here, like /mnt/ something/.
You likely will encounter many systems with more than one directory created and/or mounted
inside /mnt to be used for various local and remote filesystems.
3. /tmp
Applications and users should use /tmp to store temporary data when needed. Data stored in
/tmp may use either disk space or RAM. Both of which are managed by the operating system.
Never use /tmp to store data that is important or which you wish to archive.
Memory directories
1. /dev
Device files in /dev appear to be ordinary files, but are not actually located on the hard disk.
The /dev directory is populated with files as the kernel is recognising hardware.
common physical devices
Common hardware such as hard disk devices are represented by device files in /dev. Below a
screenshot of SATA device files on a laptop and then IDE attached drives on a desktop.