Unix Toc+Ch1
Unix Toc+Ch1
1 Getting started
Introducing Unix
7
8
Discovering the shell 10
Understanding commands 12
Navigating directories 14
Dealing wildcards 16
Recognizing metacharacters 18
Quoting phrases 20
Getting help 22
Summary 24
2 Managing files
Creating folders
25
26
Arranging files 28
Adding links 30
Examining properties 32
Comparing files 34
Finding files 36
Compressing files 38
Making backups 40
Summary 42
3 Handling text
Reading and writing
43
44
Redirecting output 46
Seeking strings 48
Sorting order 50
Arranging columns 52
Matching expressions 54
Editing text 56
Inserting text 58
Summary 60
4 Editing commands
Amending characters
61
62
Changing lines 64
Completing commands 66
Adjusting characters 68
Inserting text 70
Repeating history 72
Fixing commands 74
Expanding history 76
Summary 78
5 Customizing environment
Switching users
79
80
Setting permissions 82
Adding colors 84
Creating aliases 86
Setting options 88
Modifying variables 90
Changing prompts 92
Adjusting paths 94
Summary 96
6 Controlling behavior
Disabling defaults
97
98
Formatting output 100
Reading input 102
Substituting commands 104
Managing jobs 106
Killing processes 108
Communicating routines 110
Relating shells 112
Summary 114
7 Performing operations
Storing values
115
116
Filling arrays 118
Handling strings 120
Doing arithmetic 122
Assigning values 124
Comparing values 126
Assessing logic 128
Matching patterns 130
Summary 132
8 Directing flow
Examining conditions
133
134
Providing alternatives 136
Testing cases 138
Iterating for 140
Selecting options 142
Looping while 144
Looping until 146
Breaking out 148
Summary 150
10 Handy reference
Special characters
169
170
Commands A-D 172
Commands D-F 174
Commands G-L 176
Commands L-S 178
Commands S-U 180
Commands U-Z 182
Date formats 184
Shell variables 186
Index 187
Preface
The creation of this book has been for me, Mike McGrath, an exciting opportunity to
demonstrate the powerful command-line shell functionality available in almost any modern
Unix-family operating system. I sincerely hope you enjoy discovering the exciting possibilities
of the command-line and have as much fun with it as I did in writing this book.
In order to clarify script code listed in the steps given I have adopted certain colorization
conventions. Interpreter directives and comments are colored green, shell components are blue,
literal string and numeric values are black, user-specified variable and function names are red.
Additionally a colored icon and a file name appears in the margin alongside the script code to
readily identify each particular script:
#!/bin/bash
The screenshots that accompany each example illustrate the actual output produced by precisely
executing the commands listed in the easy steps:
For convenience I have placed source code files from the examples featured in this book into a
single ZIP archive. You can obtain the complete archive by following these three easy steps:
l 1 Open a web browser and navigate to www.ineasysteps.com then select the menu
entitled “Free Resources” and choose the “Downloads” item
l 2 Next find “Unix in easy steps” in the list then click on the hyperlink entitled
“All Code Examples” to download the archive
l 3 Now extract the contents to any convenient location, such as your home directory
1 Getting started
8 Introducing Unix
Welcome to the exciting
10 Discovering the shell
world of Unix. This chapter
12 Understanding commands
introduces the Bash
14 Navigating directories
command interpreter shell
16 Dealing wildcards
and demonstrates essential
18 Recognizing metacharacters
basic commands.
20 Quoting phrases
22 Getting help
24 Summary
Getting started
Introducing Unix
Unix is a multi-user, multi-tasking computer operating system
developed at AT&T’s Bell Labs. Way back in the mid 1960s Bell
Labs, the Massachusetts Institute of Technology and General
Electric co-developed a mainframe multi-tasking operating system
named “Multics”. The Multics operating system became large
and complex so Bell Labs withdrew from the project. A group
from Bell Labs, notably Brian Kernighan and Dennis Ritchie,
wanted to create something with many of the same multi-tasking
capabilities but simpler to use. They named it “Unix” as a joke,
saying “whatever Multics is many of, Unix is just one of ”.
“Multics” (MULTiplexed
Information and In 1973 Kernighan and Ritchie created the “C” high-level
Computing Service) programming language and rewrote Unix in their new language.
was the forerunner This was a huge leap from the assembly code used in all other
to “Unics” (UNiplexed operating system development at that time. The migration from
Information and
assembly code to the C language produced much more portable
Computing Service) –
a.k.a. “Unix”. software that was easily ported to other computing platforms.
AT&T made the Unix source code available to universities,
which created a great amount of academic interest, particularly
at the University of California, Berkeley. Their Computer Science
8
sudo who
9
find cd
cp mv
rm man
du
cat
exit clear
ls
Bash is part of the Once you have confirmed that Bash is the current shell you can
“GNU” Unix-like see its version information by issuing a bash --version command:
l
operating system – find
details and download 1 Launch a Terminal window then at the prompt exactly
instructions online at type ps $$ and hit Return to discover the current shell
gnu.org/software/bash.
10
l 4 Once you have confirmed you are indeed using the Bash
shell, at the prompt exactly type bash --version then hit
Return to discover the current Bash version
l
on the system.
5 Now, issue a clear command (or press Ctrl + L keys) to
clear the terminal screen back to a command prompt
11
Notice that the default Bash command prompt comprises several
pieces of information including the user’s name (shown here
as user) and the host system name (shown here as host). These
details can also be displayed using the whoami and hostname
commands:
l 6 Type whoami then hit Return to see your user name, then
type hostname and hit Return to see your computer name
l
hide the user name and
7 Finally issue an exit command (or press Ctrl + D keys) to host name.
end the session and thereby close the Terminal window
Getting started
Understanding commands
When the user hits the Return key after typing a command at
a shell prompt it adds a final invisible newline character. This
denotes the end of the command and indicates to the shell that
it should then attempt to interpret that command. The Bash
interpreter first reads the command line as “standard input” (stdin)
and splits it into separate words broken by spaces or tabs. Each of
these words is known as a “token”. The interpreter next examines
the first token to see if it is one of the shell’s “built-in” commands
or an executable program located on the file system.
Each Unix program When the first token is recognized as a built-in shell command,
can accept standard the interpreter executes that command otherwise it searches
input and can produce through the directories on a specified path to find a program of
standard output that name. The interpreter will then execute a recognized built-in
and standard error command or recognized program and display any result in the
messages. Terminal as “standard output” (stdout). Where neither is found,
the interpreter will display an error message in the Terminal as
“standard error” (stderr).
The Bash type command can be used to determine whether a
12
l 2 Next, type type exit then hit Return to discover that exit
is in fact a built-in shell command
13
In addition to the built-in shell commands the Bash shell also
contains a number of built-in shell variables. These are named
“containers” that each store a piece of information and their names
use all uppercase characters. To access the information stored
within a variable its name must be prefixed with a $ dollar sign:
Navigating directories
The Unix filesystem is arranged as a tree-like hierarchical structure
of directories and files with the “root” directory at its base. The
root directory is addressed simply as a forward-slash character /.
Sub-directories within the root directory are addressed by
appending their directory name to the forward-slash. For example,
/dev the “home” directory has the address /home. Directories within
/bin /lib
those sub-directories are addressed by appending another forward-
/sbin slash and their directory name. For example, a “user” directory
/boot /proc
within the “home” directory has the address /home/user.
/initrd /etc
Similarly, files in directories are addressed by appending another
forward-slash and the filename, such as /home/user/filename.
/var
/mnt
/usr /opt /tmp This hierarchical address system can therefore easily describe
the “absolute path” of any directory or file from the root base.
/home /root Additionally, contents of the current directory and its sub-
directories can be addressed by name using their “relative path”.
For example, a sub-directory named “user” within /home can be
addressed from /home simply as user, and a file within that sub-
directory can be addressed as user/filename.
/ When the user launches a Terminal window it conveniently
14
As Unix is case-sensitive
the names of directories
l 2 Next, type ls then hit Return to see the contents of the
current directory
l
and files in addresses
must be correctly 3 Now, specify the relative address of an immediate child
capitalized. sub-directory to the ls command to see nested directories
– for example, type ls Documents then hit Return
15
l 5 Type cd Documents/Pictures then hit Return to see the
prompt change to display the nested sub-directory location
Dealing wildcards
The ls command, introduced on the previous page, will list all
files and folders in the current or specified directory, except
special hidden files whose names begin with a . period character.
Typically, these are system files such as a .bashrc hidden file
in the user’s home directory containing the shell configuration
details. Hidden files can be included in the list displayed by the ls
command by adding a -a option, so the command becomes ls -a.
Optionally, a filename pattern can be supplied to the ls command
so it will list only filenames matching the specified pattern.
If you wish to delete a Special “wildcard” characters, described in the table below, can be
directory remember that used to specify the filename pattern to be matched:
it may contain hidden
files – use the ls -a
command to check. Wildcard: Matches:
l 2 Next, type ls doc.? then hit Return to see all files named
“doc” that have a single-letter file extension
matching with wildcards
demonstrated here is
commonly known as
l
“globbing” – a reference
3 Now, type ls *.c then hit Return to see all files of any to global wildcard
name that have a “.c” file extension expansion.
l 4 Type ls *.[a-c] then hit Return to see all files of any name
that have a “.a”, “.b” or “.c” file extension
17
l 5 Now, type ls *.[!a-c] then hit Return to see all files of any
name that do not have a “.a”, “.b” or “.c” file extension
Recognizing metacharacters
Just as the special wildcard characters ? * [ ] can be used to
perform pathname expansion, plain strings can be expanded using
{ } brace characters. These may contain a comma-separated list of
substrings that can be appended to a specified prefix, or prepended
to a specified suffix, or both, to generate a list of expanded strings.
The brace expansions can also be nested for complex expansion.
Additionally, brace expansion can produce a sequence of letters or
numbers by specifying a range separated by .. between the braces:
There must be no
spaces within the braces
or between the braces
l 1 At a prompt, type echo b{ad,oy} then hit Return to see
two expanded strings – appended to the specified prefix
l
and each specified prefix
and suffix. 2 Next, type echo {ge,fi}t then hit Return to see two
expanded strings – prepended to the specified suffix
Bash version 4
introduced zero-padded
brace expansion so that
echo {001..3} produces
001 002 003.
...cont’d
Metacharacter: Meaning:
19
\ Escape next character
| Pipe
[ Start of wildcard set
] End of wildcard set
{ Start of command block
} End of command block
; Pipeline command separator
‘ Quote mark (strong)
“ Quote mark (weak)
Notice that the semi-
< Redirect input
colon ; character allows
> Redirect output two commands to be
/ Pathname address separator issued on the same line.
For example, type
? Single-character wildcard echo {a..z} ; echo {1..9}
! Pipeline logical NOT then hit Return.
Getting started
Quoting phrases
The metacharacters that have special meaning to the Bash shell
can be used literally, without applying their special meaning, by
enclosing them within a pair of ‘ ‘ single quote characters to form
a quoted phrase. For example, to include the name of a shell
variable in a phrase without interpreting its value:
21
Double quote marks “ “ are regarded as weak by the Bash shell
as they do allow the interpretation of shell variables they enclose.
They can, however, be useful to print out a quoted string if the
entire string (and its double quotes) are enclosed in single quotes:
Getting help
Bash includes an online help system for its built-in commands.
Information on all its built-in commands can be displayed using
the help command and help | more can be used to display just
one screen at a time. A command name can be specified to
discover information about that particular command:
The | character is a
“pipe” that allows
output to be redirected
– here output is sent
to the more command.
Pipelines are described
in detail on page 46.
22
Bash version 4
l3 Now, type help echo and hit Return to display
information about the Bash shell built-in echo command
23
l 5 Hit Return to scroll down the screen one line at a time or
type q and hit Return to return to a prompt
Summary
• Bash is a command interpreter shell that enables the user to
interact with the kernel of any Unix-based operating system
• and
The command displays the current process information
ps $$
can be used to confirm Bash as the current shell
• allows
Enclosing with single quotes or prefixing with a backslash
‘‘
metacharacters to be displayed literally
\
• Onlinecommands
info
help can be found for any command using the
and for built-ins using the command
help
or man