Navigating Linux
Navigating Linux
Sayan Ghosh
IIT Madras
BS Data Science and Applications
Disclaimer
This document is a companion activity book for the System Commands
(BSSE2001) course taught by Prof. Gandham Phanikumar at IIT Madras
BS Program. This book contains resources, references, questions and
solutions to some common questions on Linux commands, shell scripting,
grep, sed, awk, and other system commands.
This was prepared with the help and guidance of the course instructors:
Copyright
© This book is released under the public domain, meaning it is freely available
for use and distribution without restriction. However, while the content itself
is not subject to copyright, it is requested that proper attribution be given if
any part of this book is quoted or referenced. This ensures recognition of the
original authorship and helps maintain transparency in the dissemination of
information.
Colophon
This document was typeset with the help of KOMA-Script and LATEX using
the kaobook class.
The source code of this book is available at:
https://github.com/sayan01/se2001-book
(You are welcome to contribute!)
Edition
Compiled on August 10, 2024
UNIX is basically a simple operating system, but you
have to be a genius to understand the simplicity.
– Dennis Ritchie
Preface
Through this work I have tried to make learning and understanding the
basics of Linux fun and easy. I have tried to make the book as practical
as possible, with many examples and exercises. The structure of the book
follows the structure of the course BSSE2001 - System Commands, taught by
Prof. Gandham Phanikumar at IIT Madras BS Program. .
The book takes inspiration from the previous works done for the course,
The book covers basic commands, their motivation, use cases, and examples.
The book also covers some advanced topics like shell scripting, regular
expressions, and text processing using sed and awk.
This is not a substitute for the course, but a companion to it. The book is a
work in progress and any contribution is welcome at https://github.com/
sayan01/se2001-book
Sayan Ghosh
Contents
Preface v
Contents vii
1 Essentials of Linux 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1.1 What is Linux? . . . . . . . . . . . . . . . . . . . . . . 1
1.1.2 Desktop Environments . . . . . . . . . . . . . . . . . 4
1.1.3 Window Managers . . . . . . . . . . . . . . . . . . . 5
1.1.4 Why Linux? . . . . . . . . . . . . . . . . . . . . . . . 6
1.1.5 What is Shell? . . . . . . . . . . . . . . . . . . . . . . 7
1.1.6 Shell vs Terminal . . . . . . . . . . . . . . . . . . . . 8
1.1.7 Why the Command Line? . . . . . . . . . . . . . . . 10
1.1.8 Command Prompt . . . . . . . . . . . . . . . . . . . 11
1.2 Simple Commands in GNU Core Utils . . . . . . . . . . . . 12
1.2.1 File System Navigation . . . . . . . . . . . . . . . . . 12
1.2.2 Manuals . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.2.3 System Information . . . . . . . . . . . . . . . . . . . 20
1.2.4 File Management . . . . . . . . . . . . . . . . . . . . 24
1.2.5 Text Processing and Pagers . . . . . . . . . . . . . . . 29
1.2.6 Aliases and Types of Commands . . . . . . . . . . . 35
1.2.7 User Management . . . . . . . . . . . . . . . . . . . . 41
1.2.8 Date and Time . . . . . . . . . . . . . . . . . . . . . . 43
1.3 Navigating the File System . . . . . . . . . . . . . . . . . . . 47
1.3.1 What is a File System? . . . . . . . . . . . . . . . . . 47
1.3.2 In Memory File System . . . . . . . . . . . . . . . . . 51
1.3.3 Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
1.3.4 Basic Commands for Navigation . . . . . . . . . . . . 57
1.4 File Permissions . . . . . . . . . . . . . . . . . . . . . . . . . 60
1.4.1 Read . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.4.2 Write . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.4.3 Execute . . . . . . . . . . . . . . . . . . . . . . . . . . 62
1.4.4 Interesting Caveats . . . . . . . . . . . . . . . . . . . 63
1.4.5 Changing Permissions . . . . . . . . . . . . . . . . . 65
1.4.6 Special Permissions . . . . . . . . . . . . . . . . . . . 66
1.4.7 Octal Representation of Permissions . . . . . . . . . 70
1.5 Types of Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
1.5.1 Regular Files . . . . . . . . . . . . . . . . . . . . . . . 73
1.5.2 Directories . . . . . . . . . . . . . . . . . . . . . . . . 73
1.5.3 Symbolic Links . . . . . . . . . . . . . . . . . . . . . 73
1.5.4 Character Devices . . . . . . . . . . . . . . . . . . . . 74
1.5.5 Block Devices . . . . . . . . . . . . . . . . . . . . . . 75
1.5.6 Named Pipes . . . . . . . . . . . . . . . . . . . . . . . 76
1.5.7 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . 77
1.5.8 Types of Regular Files . . . . . . . . . . . . . . . . . . 78
1.6 Inodes and Links . . . . . . . . . . . . . . . . . . . . . . . . . 80
1.6.1 Inodes . . . . . . . . . . . . . . . . . . . . . . . . . . 80
1.6.2 Separation of Data, Metadata, and Filename . . . . . 82
1.6.3 Directory Entries . . . . . . . . . . . . . . . . . . . . 83
1.6.4 Hard Links . . . . . . . . . . . . . . . . . . . . . . . . 84
1.6.5 Symbolic Links . . . . . . . . . . . . . . . . . . . . . 86
1.6.6 Symlink vs Hard Links . . . . . . . . . . . . . . . . . 89
1.6.7 Identifying Links . . . . . . . . . . . . . . . . . . . . 89
1.6.8 What are . and ..? . . . . . . . . . . . . . . . . . . . . 90
7 Grep 309
7.1 Regex Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
7.2 PCRE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
7.3 Print Only Matching Part . . . . . . . . . . . . . . . . . . . . 312
7.4 Matching Multiple Patterns . . . . . . . . . . . . . . . . . . . 313
7.4.1 Disjunction . . . . . . . . . . . . . . . . . . . . . . . . 313
7.4.2 Conjunction . . . . . . . . . . . . . . . . . . . . . . . 314
7.5 Read Patterns from File . . . . . . . . . . . . . . . . . . . . . 315
7.6 Ignore Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
7.7 Invert Match . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
7.8 Anchoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
7.9 Counting Matches . . . . . . . . . . . . . . . . . . . . . . . . 318
7.10 Print Filename . . . . . . . . . . . . . . . . . . . . . . . . . . 320
7.11 Limiting Output . . . . . . . . . . . . . . . . . . . . . . . . . 321
7.12 Quiet Quitting . . . . . . . . . . . . . . . . . . . . . . . . . . 324
7.13 Numbering Lines . . . . . . . . . . . . . . . . . . . . . . . . 324
7.14 Recursive Search . . . . . . . . . . . . . . . . . . . . . . . . . 325
7.15 Context Line Control . . . . . . . . . . . . . . . . . . . . . . 326
7.16 Finding Lines Common in Two Files . . . . . . . . . . . . . . 327
popular DEs can be installed on all distributions. Figure 1.2: Desktop Environ-
Many distributions also come with multiple pre- ment Usage in 2022
bundled desktop environments due to user pref-
erences. Most server distributions and some en-
thusiast distributions come with no pre-bundled
desktop environment, and let the user determine
which one is required, or if one is required.
Shortcut Description
Ctrl + C Terminate the current process
Ctrl + D Exit the shell
Ctrl + L Clear the terminal screen
Ctrl + A Move the cursor to the beginning of the line
Ctrl + E Move the cursor to the end of the line
Ctrl + U Delete from the cursor to the beginning of the line
Ctrl + K Delete from the cursor to the end of the line
Ctrl + W Delete the word before the cursor
Ctrl + Y Paste the last deleted text
Ctrl + R Search the command history
Ctrl + Z Suspend the current process
Ctrl + \\ Terminate the current process
Ctrl + S Pause the terminal output
Ctrl + Q Resume the terminal output
10 1 Essentials of Linux
GUI:
CLI:
pwd:
ls:
1.2 Simple Commands in GNU Core Utils 13
We can also list hidden files 10 using the -a flag. 10: Hidden files are files
whose names start with a dot.
1 $ ls -a They are hidden by default
2 . .. .bashrc Desktop Documents in the ls command.
Downloads Music Pictures Videos
Command Description
ls List the contents of a directory
cd Change the current working directory
pwd Print the current working directory
mkdir Create a new directory
rmdir Remove a directory
touch Create a new file
rm Remove a file
cp Copy a file
mv Move a file
echo Print a message
cat Concatenate and display the contents of a file
less Display the contents of a file one page at a time
head Display the first few lines of a file
tail Display the last few lines of a file
find Find files and directories
locate Find files and directories
which Find the location of a command
uname Print system information
ps Display information about running processes
kill Terminate a process
chmod Change the permissions of a file
chown Change the owner of a file
chgrp Change the group of a file
date Print the current date and time
cal, ncal Print a calendar
df Display disk space usage
du Display disk usage
free Display memory usage
top Display system information
history Display the command history
sleep Pause the shell for a specified time
true Do nothing, successfully
false Do nothing, unsuccessfully
tee Read from stdin and write to stdout and files
whoami Print the current user
groups Print the groups the user belongs to
clear Clear the terminal screen
exit Exit the shell
1.2 Simple Commands in GNU Core Utils 15
If we want to go back to the previous directory, 13: This internally uses the
we can use the - symbol as an argument to the cd OLDPWD environment vari-
able to change the directory.
command. 13 More about variables will be
covered later in the course.
16 1 Essentials of Linux
1 $ cd Documents
2 $ pwd
3 /home/username/Documents
4 $ cd -
5 $ pwd
6 /home/username
1.2.2 Manuals
man:
How to remember so many flags and options for
each of the commands? The man command is used
to display the manual pages for a command.
1 $ man ls
User Commands
LS(1)
3
4 NAME
5 ls - list directory contents
6
7 SYNOPSIS
8 ls [OPTION]... [FILE]...
9
10 DESCRIPTION
11 List information about the FILEs (the
current directory by default). Sort
entries alphabetically if none of -
cftuvSUX nor --sort is specified.
12
13 Mandatory arguments to long options are
mandatory for short options too.
14
15 -a, --all
16 do not ignore entries starting
with .
17
18 -A, --almost-all
19 do not list implied . and ..
20 ...
info:
help:
uname:
ps:
17: The PID is the process
ID, the TTY is the terminal The ps command displays information about run-
the process is running from, ning processes. By default, it displays information
the TIME is the time the pro-
cess has been running, and
about the processes run by the current user that are
the CMD is the command running from a terminal. 17
that is running.
1.2 Simple Commands in GNU Core Utils 21
1 $ ps
2 PID TTY TIME CMD
3 12345 pts/0 00:00:00 bash
4 12346 pts/0 00:00:00 ps
kill:
df:
1 $ df -h
2 Filesystem Size Used Avail Use%
Mounted on
3 /dev/sda1 12G 1.2G 9.9G 11% /
4 /dev/sda2 12G 1.2G 9.9G 11% /home
du:
file:
1 $ file file1
2 file1: ASCII text
3 $ file /bin/bash
4 /bin/bash: ELF 64-bit LSB shared object, x86
-64, version 1 (SYSV), dynamically linked,
interpreter /lib64/ld-linux-x86-64.so.2,
for GNU/Linux 3.2.0, BuildID[sha1
]=1234567890abcdef, stripped
mkdir:
touch:
8 $ ls -l
9 -rw-r--r-- 1 username group 0 Mar 1 12:00
file1
10 -rw-r--r-- 1 username group 0 Mar 1 12:00
file2
11 -rw-r--r-- 1 username group 0 Mar 1 12:01
file3
rmdir:
rm:
4 $ rm file1 file2
5 $ ls -F
6 file3
cp:
1 $ touch file1
2 $ ls -F
3 file1
4 $ cp file1 file2
5 $ ls -F
6 file1 file2
mv:
echo:
cat:
less:
1.2 Simple Commands in GNU Core Utils 31
4 daemon:x:2:2::/:/usr/bin/nologin
5 mail:x:8:12::/var/spool/mail:/usr/bin/
nologin
6 ftp:x:14:11::/srv/ftp:/usr/bin/nologin
wc:
in filename.
wc -c filename will count the number of char-
acters in filename.
alias:
which:
whatis:
whereis:
locate:
type:
We can also use the -a flag to show all the ways the
command can be interpreted.
1 $ type -a pwd
2 pwd is a shell builtin
3 pwd is /sbin/pwd
4 pwd is /bin/pwd
5 pwd is /usr/bin/pwd
6 pwd is /usr/sbin/pwd
whoami:
42 1 Essentials of Linux
groups:
passwd
w:
date:
cal:
The cal command is used to print a calendar. By de-
fault, it prints the calendar of the current month.
1 $ cal
2 May 2024
3 Su Mo Tu We Th Fr Sa
4 1 2 3 4
5 5 6 7 8 9 10 11
6 12 13 14 15 16 17 18
7 19 20 21 22 23 24 25
8 26 27 28 29 30 31
=47,pgrp=1,timeout=60,minproto=5,maxproto
=5,direct,pipe_ino=2930)
22 tmpfs on /tmp type tmpfs (rw,noatime,inode64)
23 /dev/sda4 on /efi type vfat (rw,relatime,fmask
=0137,dmask=0027,codepage=437,iocharset=
ascii,shortname=mixed,utf8,errors=remount-
ro)
24 /dev/sda2 on /home type ext4 (rw,noatime)
25 binfmt_misc on /proc/sys/fs/binfmt_misc type
binfmt_misc (rw,nosuid,nodev,noexec,
relatime)
26 tmpfs on /run/user/1000 type tmpfs (rw,nosuid,
nodev,relatime,size=795052k,nr_inodes
=198763,mode=700,uid=1000,gid=1001,inode64
)
27 portal on /run/user/1000/doc type fuse.portal
(rw,nosuid,nodev,relatime,user_id=1000,
group_id=1001)
28 /dev/sdb3 on /data type ext4 (rw,noatime,x-
systemd.automount,x-systemd.idle-timeout=1
min)
proc:
Here you can see that the command line of the pro-
cess is stored in the cmdline file. Here the process
is of a command called entr.
/sys vs /proc:
34: Unix System V is one of
The /proc tree originated in System V Unix 34 ,
the first commercial versions
of the Unix operating system. where it only gave information about each running
It was originally developed process, using a /proc/\$PID/ format. Linux greatly
by AT&T and first released extended that, adding all sorts of information about
in 1983.
the running kernel’s status. In addition to these
read-only information files, Linux’s /proc also has
writable virtual files that can change the state of the
35: BSD, or Berkeley Soft-
running kernel. BSD 35 type OSes generally do not
ware Distribution, is a Unix-
like operating system that have /proc at all, so much of what you find under
was developed at the Univer- proc is non-portable.
sity of California, Berkeley.
It was first released in 1977 The intended solution for this mess in Linux’s /proc
and was based on the orig- is /sys. Ideally, all the non-process information that
inal Unix source code from
AT&T. BSD is not linux, it is a
got crammed into the /proc tree should have moved
totally different kernel, with to /sys by now, but historical inertia has kept a lot
similar core utils to GNU. of stuff in /proc. Often there are two ways to effect
a change in the running kernel: the old /proc way,
kept for backwards compatibility, and the new /sys
way that you’re supposed to be using now.
1.3.3 Paths
Absolute Path:
Relative Path:
Answer 1.3.1 ls
Answer 1.3.2 ls -a
Answer 1.3.3 ls -l
Answer 1.3.5 ls -1
This can also be done by passing the output of
ls to cat or storing the output of ls in a file and
then using cat to print it. We will see these in
later weeks.37 37: that is a one, not an L
60 1 Essentials of Linux
1.4.1 Read
1.4.2 Write
1.4.3 Execute
8 /home/sayan/test
Synopsis:
1 chmod [OPTION]... MODE[,MODE]... FILE...
2 chmod [OPTION]... OCTAL-MODE FILE...
SetUID:
1.4 File Permissions 67
1 $ ls -l /usr/bin/passwd
2 -rwsr-xr-x 1 root root 80912 Apr 1 15:49 /
usr/bin/passwd
SetGID:
Answer 1.4.1 ls -l
The permissions are the first 10 characters of
the output.
stat -c \%A filename will list only the permis-
72 1 Essentials of Linux
sions of a file.
There are other format specifiers of stat to show
different statistics which can be found in man
stat.
1.5.2 Directories
1 $ mkfifo pipe1
2 $ ls -l pipe1
3 prw-r--r-- -1 sayan sayan 0 May 22 18:22 pipe1
Terminal 1:
1 $ echo "hello" > pipe1
Terminal 2:
1 $ cat pipe1
1.5.7 Sockets
Terminal 1:
1 $ nc -lU socket.sock
Terminal 2:
1 $ echo "hello" | nc -U socket.sock
78 1 Essentials of Linux
1.6.1 Inodes
1 $ ls -i
2 1234567 file1
3 1234568 file2
4 1234569 file3
Hard links can be created for files only, and not di-
rectories. It can be created using the ln command.
1 $ ln file1 file2
Interesting Observation:
Soft Links:
Hard Links:
Keystroke execution
Emacs commands are key combinations for which
modifier keys are held down while other keys are
pressed; a command gets executed once completely
typed.
96 2 Command Line Editors
Keyboard
Vi does not use the Alt key and seldom uses the
Ctrl key. vi’s keyset is mainly restricted to the al-
phanumeric keys, and the escape key. This is an
enduring relic of its teletype heritage, but has the
effect of making most of vi’s functionality accessible
without frequent awkward finger reaches.
2.2 Vim
2.2.1 History
QED
VDU Terminals
EX
Vi Clones
Vim
2.2.2 Ed Commands
Description Commands
Show the Prompt P
Command Format [addr[,addr]]cmd[params]
Commands for location 1 . $ \% + - , ; /RE/
Commands for editing fpacdijsmu
Execute a shell command !command
edit a file e filename
read file contents into buffer r filename
read command output into buffer r !command
write buffer to filename w filename
quit q
Commands Description
a number like 2 refers to second line of file
. refers to current line
$ refers to last line
% refers to all the lines
+ line after the cursor (current line)
- line before the cursor (current line)
, refers to buffer holding the file or last line in buffer
; refers to current position to end of the file
/RE/ refers line matched by pattern specified by ’RE’
To print out all the lines of the file, we can use the ,
or \% with p command.
2.2 Vim 113
1 *,p
2 line-1 hello world
3 line-2 welcome to line editor
4 line-3 ed is perhaps the oldest editor out
there
5 line-4 end of file
1 *%p
2 line-1 hello world
3 line-2 welcome to line editor
4 line-3 ed is perhaps the oldest editor out
there
5 line-4 end of file
1 *p
2 line-1 hello world
3 *+
4 line-2 welcome to line editor
We can also print all the lines from the current line
to the end of the file using the ;p command.
1 *.
2 line-2 welcome to line editor
3 *;p
4 line-2 welcome to line editor
5 line-3 ed is perhaps the oldest editor out
there
6 line-4 end of file
5 *%p
6 line-1 hello universe
7 line-2 welcome to line editor
8 line-3 ed is perhaps the oldest editor out
there
9 perhaps not, since we know it was inspired
from QED
10 which was made multiple times by thompson and
ritchie
11 before ed was made.
12 line-4 end of file
13 *
15 *
17: The undo command in We can also undo the last change using the u com-
ed is not as powerful as the
undo command in vim. In
mand. 17
vim, we can undo multiple
1 *1
changes using the u com-
2 line-0 in the beginning, there was light
mand. In ed, we can only
undo the last change. If we 3 *s/light/darkness
run the u command multi- 4 line-0 in the beginning, there was darkness
ple times, it will undo the 5 *u
last change of undoing the 6 *.
last change, basically redo- 7 line-0 in the beginning, there was light
ing the last change.
8 *
Basic Navigation
Replacing Text
Key Description
:f show name of file
:p print current line
:a append at current line
:c change current line
:d delete current line
:i insert line at current position
:j join lines
:s search and replace regex pattern in current line
:m move current line to position
:u undo latest change
:w [filename] write buffer to filename
:q quit if no change
:wq write buffer to filename and quit
:x write buffer to filename and quit
:q! quit without saving
:r filename read file contents into buffer
:r !command read command output into buffer
:e filename edit a file
:sp [filename] split the screen and open another file
:vsp [filename] vertical split the screen and open another file
Toggling Case
Key Description
h move cursor left
j move cursor down
k move cursor up
l move cursor right
w move to the beginning of the next word
e move to the end of the current word
b move to the beginning of the previous word
\% move to the matching parenthesis, bracket, or brace
0 move to the beginning of the current line
$ move to the end of the current line
/ search forward for a pattern
? search backward for a pattern
n repeat the last search in the same direction
N repeat the last search in the opposite direction
gg move to the first line of the file
G move to the last line of the file
1G move to the first line of the file
1gg move to the first line of the file
:1 move to the first line of the file
{ move to the beginning of the current paragraph
} move to the end of the current paragraph
fg move cursor to next occurrence of ‘g’ in the line
Fg move cursor to previous occurrence of ‘g’ in the line
Key Description
r replace the character under the cursor
R replace the character from the cursor till escape is pressed
cw change the word under the cursor
c4w change the next 4 words
C delete from cursor till end of line and enter insert mode
cc delete entire line and enter insert mode
5cc delete next 5 lines and enter insert mode
S delete entire line and enter insert mode
s delete character under cursor and enter insert mode
Key Description
~ toggle the case of the character under the cursor
g~w toggle the case of the word under the cursor
g~0 toggle the case from cursor till beginning of line
g~$ toggle the case from cursor till end of line
g~{ toggle the case from cursor till previous empty line
g~{ toggle the case from cursor till next empty line
g~\% toggle the case from the bracket, brace, or parenthesis till its pair
This works not just with w but with any other motion
such as delete inside paragraph, which will delete
the entire paragraph under the cursor, resulting
in two empty lines being left behind, and delete
around paragraph, which will delete the entire
paragraph under the cursor, and only one empty
line being left behind.
and
1 0y$
Key Description
m,n from line m to line n
m line m
m,$ from line m to end of file
.,$ from current line to end of file
1,n from line 1 to line n
/regex/,n from line containing regex to line n
m,/regex/ from line m to line containing regex
.,/regex/ from current line to line containing regex
/regex/,. from line containing regex to current line
1,/regex/ from the first line to line containing regex
/regex/,$ from line containing regex to the last line
/regex1/;/regex2/ from line containing regex1 to line containing regex2
\% entire file
Insert Mode
2.2 Vim 131
Key Description
i enter insert mode before the cursor
a enter insert mode after the cursor
I enter insert mode at the beginning of the line
A enter insert mode at the end of the line
o add new line below the current line and enter insert mode
O add new line above the current line and enter insert mode
2.3 Emacs
2.3.1 History
TECO
TECO was developed at MIT in 1962. It was a text
editor used to correct the output of the PDP-1 com-
puter. It is short for Tape Editor and Corrector.
Unlike most modern text editors, TECO used sep-
arate modes in which the user would either add
text, edit existing text, or display the document One Figure 2.17: Richard Stall-
could not place characters directly into a document man - founder of GNU and
FSF projects
134 2 Command Line Editors
Gosling Emacs
GNU Emacs
Figure 2.19: James Gosling
- creator of Gosling Emacs In 1983, Stallman started the GNU project to create a
and later Java free software alternatives to proprietary softwares
and ultimately to create a free 25 operating sys-
25: Recall from the previ- tem.
ous chapter that free soft-
ware does not mean a soft- In 1984, Stallman started GNU Emacs, a free soft-
ware provided gratis, but ware alternative to Gosling Emacs. It was written
a software which respects
in C and used a true Lisp dialect, Emacs Lisp as
the user’s freedom to run,
copy, distribute, and modify the extension language. Emacs Lisp was also im-
the software. It is like free plemented in C. This is the version of Emacs that is
speech, not free beer. most popular today and available on most operating
systems repositories.
2.4 Nano
2.4.1 History
26: It is believed that
pine stands for Pine is Not
Pine 26 was a text-based email client developed at Elm, Elm being another text-
the University of Washington. It was created in 1989. based email client. However,
The email client also had a text editor built in called the author clarifies that it
was not named with that in
Pico.
mind. Although if a backro-
nym was to be made, he pref-
Although the license of Pine and Pico may seem ered ‘Pine is Nearly Elm’ or
open source, it was not. The license was restrictive ‘Pine is No-longer Elm’
and did not allow for modification or redistribution.
27
140 2 Command Line Editors
27: Up to version 3.91, the Due to this, many people created clones of Pico
Pine license was similar to with free software licenses. One of the most popular
BSD, and it stated that ‘Per-
mission to use, copy, mod-
clones was TIP (TIP isn’t Pico) which was created
ify, and distribute this soft- by Chris Allegretta in 1999. Later in 2000 the name
ware and its documenta- was changed to Nano. 28 In 2001, nano became part
tion for any purpose and of the GNU project.
without fee to the Univer-
sity of Washington is hereby GNU nano implements several features that Pico
granted ...’ The university
lacks, including syntax highlighting, line numbers,
registered a trademark for
the Pine name with respect regular expression search and replace, line-by-line
to ‘computer programs used scrolling, multiple buffers, indenting groups of
in communication and elec- lines, rebindable key support, and the undoing and
tronic mail applications’ in
March 1995. From version
redoing of edit changes.
3.92, the holder of the copy-
In most modern linux systems, the nano binary is
right, the University of Wash-
ington, changed the license present along with the pico binary, which is actually
so that even if the source a symbolic link to the nano binary.
code was still available, they
did not allow modifications You can explore this by finding the path of the
and changes to Pine to be executable using the which command and long-
distributed by anyone other
listing the executable.
than themselves. They also
claimed that even the old li- 1 $ which pico
cense never allowed distribu-
2 /usr/bin/pico
tion of modified versions.
3 $ ls -l /usr/bin/pico
28: Mathematically, nano is
10−9 or one billionth. and 4 lrwxrwxrwx 1 root root 22 Sep 6 2023 /usr/
pico is 10−12 or one trillionth. bin/pico -> /etc/alternatives/pico
or put relatively, nano is 1000 5 $ ls -l /etc/alternatives/pico
times bigger than pico, al- 6 lrwxrwxrwx 1 root root 9 Sep 6 2023 /etc/
though the size of nano bi- alternatives/pico -> /bin/nano
nary is smaller than pico.
File Handling
Editing
𝑛(𝑛 − 1) 𝑛 2 − 𝑛
=
2 2
Hub
Router
Level 3 Switch
3.1.4 IP Addresses
3: An octet is a group of
162.136.73.21 8 bits. Since an IP address
is 32 bits, it is represented
Here, each octet can take values from 0 to 255. 3 as 4 groups of 8 bits. 8 bits
can only represent numbers
Technically all such combinations are possible IP from 0 to 255. since 28 = 256.
addresses, resulting in 232 = 4 , 294 , 967 , 296 possi- Notice that there are some
ble IP addresses. That is a lot of IP addresses, but groups of zeros in the
not enough for the growing number of devices in address. These can be
compressed by writing
the world. only one zero in place of
multiple zeros in each group.
This is where IPv6 comes in. IPv6 is a 128-bit address Further, any leading zeros
represented as 8 groups of 4 hexadecimal digits can be omitted for each
separated by colons. For example, group. Making the above
address as 2001:db8:85
a3:0:0:8a2e:370:7334.
Further, if there are multiple
groups of zeros, they can
2001 : 0 𝑑𝑏 8 : 85 𝑎 3 : 0000 : 0000 : 8 𝑎 2 𝑒 : 0370 : 7334 be compressed to ::. This
can be used only once in
an address. Doing this,
This results in the above address can
be compressed further to
2128 = 340282366920938463463374607431768211456 2001:db8:85a3::8a2e
:370:7334.
150 3 Networking and SSH
3.1.5 Subnetting
Legacy Classes
10.125.42.62 → 00001010.01111101.00101010.00111110
Subnet Masks
3.1.7 CIDR
3.1.8 Ports
3.1.9 Protocols
3.1.10 Firewalls
3.1.11 SELinux
RBAC Items
3.1 Networking 159
Modes of SELinux
Tool Description
ip Show / manipulate routing, devices, policy routing and tunnels
ping To see if the remote machine is up
traceroute Diagnostics the hop timings to the remote machine
nslookup Ask for conversion of IP address to name
dig DNS lookup utility
netstat Print network connections
mxtoolbox Public accessibility of your server
whois Information about the domain
nmap Network port scanner
wireshark Network protocol analyzer and packet sniffer
ip
To find out the private IP address of the NICs of
your system, you can run the ip addr command.
10: ip a also works. 10
3.1 Networking 161
1 $ ip addr
2 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc
noqueue state UNKNOWN group default qlen
1000
3 link/loopback 00:00:00:00:00:00 brd
00:00:00:00:00:00
4 inet 127.0.0.1/8 scope host lo
5 valid_lft forever preferred_lft forever
6 inet6 ::1/128 scope host noprefixroute
7 valid_lft forever preferred_lft forever
8 2: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu
1500 qdisc fq_codel state UP group
default qlen 1000
9 link/ether 1c:1b:0d:e1:5d:61 brd ff:ff:ff:
ff:ff:ff
10 altname enp3s0
11 inet 192.168.0.109/24 brd 192.168.0.255
scope global dynamic eno1
12 valid_lft 7046sec preferred_lft 7046sec
13 inet6 fe80::68e2:97e0:38ec:4abc/64 scope
link noprefixroute
14 valid_lft forever preferred_lft forever
ping
=45.3 ms
6 64 bytes from maa05s06-in-f14.1e100.net
(172.217.163.206): icmp_seq=4 ttl=114 time
=45.8 ms
7
8 --- google.com ping statistics ---
9 4 packets transmitted, 4 received, 0% packet
loss, time 3004ms
10 rtt min/avg/max/mdev =
45.316/45.524/45.791/0.181 ms
dig
16 google.com. 50 IN A 172.217.163.206
17
18 ;; AUTHORITY SECTION:
19 google.com. 162911 IN NS ns1.google.com
.
20 google.com. 162911 IN NS ns3.google.com
.
21 google.com. 162911 IN NS ns4.google.com
.
22 google.com. 162911 IN NS ns2.google.com
.
23
24 ;; ADDITIONAL SECTION:
25 ns2.google.com. 163913 IN A
216.239.34.10
26 ns4.google.com. 163913 IN A
216.239.38.10
27 ns3.google.com. 337398 IN A
216.239.36.10
28 ns1.google.com. 340398 IN A
216.239.32.10
29 ns2.google.com. 163913 IN AAAA
2001:4860:4802:34::a
30 ns4.google.com. 163913 IN AAAA
2001:4860:4802:38::a
31 ns3.google.com. 2787 IN AAAA
2001:4860:4802:36::a
32 ns1.google.com. 158183 IN AAAA
2001:4860:4802:32::a
33
34 ;; Query time: 3 msec
35 ;; SERVER: 192.168.0.1#53(192.168.0.1) (UDP)
36 ;; WHEN: Thu Jun 13 18:18:52 IST 2024
37 ;; MSG SIZE rcvd: 331
netstat
168 3 Networking and SSH
3.2 SSH
3.2.2 History
OR
Figure 3.8: Symmetric En-
cryption
1 $ ssh username@domainname
ssh-copy-id
manual install
1 $ file ~/someoneskey.pub
2 ~/someoneskey.pub: OpenSSH ED25519 public key
3 $ cat ~/someoneskey.pub >> ~/.ssh/
authorized_keys
You can then login into the server using the ssh
command.
1 $ ssh [email protected]
3.2 SSH 175
1 $ ssh -i /path/to/private/key
[email protected]
sshd
3.2.9 SCP
4.1.1 Example
1 $ sleep 5
2 $ echo "Hello, World!"
3 Hello, World!
1 $ cat hello.sh
2 sleep 5
3 echo "Hello, World!"
4 $ bash hello.sh
5 Hello, World!
‗ NO-OP stands for No Operation. It is a command that does
nothing. More reading on NO-OP can be found here.
182 4 Process Management
1 sleep NUMBER[SUFFIX]...
You can also see that the TTY column is now set to
?, which means that the process is no longer tied to
the terminal.
4.2.5 Setsid
4.2.6 Nohup
4.2.7 coproc
Syntax
1 $ coproc [NAME] command [redirections]
4.3.1 Disown
4.3.2 Jobs
1 $ kill -l
2 1) SIGHUP 2) SIGINT 3) SIGQUIT
4) SIGILL 5) SIGTRAP
3 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1
4 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE
14) SIGALRM 15) SIGTERM
5 16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT
19) SIGSTOP 20) SIGTSTP
6 21) SIGTTIN 22) SIGTTOU 23) SIGURG
24) SIGXCPU 25) SIGXFSZ
7 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR
8 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1
36) SIGRTMIN+2 37) SIGRTMIN+3
9 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6
41) SIGRTMIN+7 42) SIGRTMIN+8
10 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN
+11 46) SIGRTMIN+12 47) SIGRTMIN+13
11 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX
-14 51) SIGRTMAX-13 52) SIGRTMAX-12
12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9
56) SIGRTMAX-8 57) SIGRTMAX-7
13 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4
61) SIGRTMAX-3 62) SIGRTMAX-2
longer available.
▶ SIGINT - Interrupt signal. This is sent to a
process when the user presses Ctrl+C. This
is used to tell the process to stop what it is
doing and exit.
▶ SIGKILL - Kill signal. This is used to kill a
process immediately. This signal cannot be
caught or ignored by the process.
▶ SIGTERM - Terminate signal. This is used to
tell the process to exit gracefully. The process
can catch this signal and do some cleanup
before exiting. This is the default signal sent
by the kill command.
▶ SIGSTP - Stop signal. This is used to pause
a process. This is sent when the user presses
Ctrl+Z. This signal can be caught or ignored
by the process.
▶ SIGSTOP - Stop signal. This is used to pause
a process. This signal cannot be caught or
ignored by the process.
▶ SIGCONT - Continue signal. This is used to
resume a process that has been paused using
the SIGSTOP signal. This is sent when the
user presses fg or bg.
▶ SIGUSR1 - User defined signal 1. This is a
signal that can be used by the user to send a
custom signal to the process.
▶ SIGUSR2 - User defined signal 2. This is a
signal that can be used by the user to send a
custom signal to the process.
▶ SIGCHLD - Child signal. This is sent to the
parent process when a child process exits.
This is used to tell the parent process that the
child process has exited.
▶ SIGSEGV - Segmentation fault signal. This
is sent to a process when it tries to access
memory that it is not allowed to access.
▶ SIGPIPE - Pipe signal. This is sent to a process
4.3 Process Management 201
4.4.1 pgrep
1 $ pgrep firefox
2 526272
4.4.2 pkill
1 $ pkill firefox
4.4.3 pidwait
4.5.1 ps
8: It exists in the Unix V7 ps is an ancient command 8 that is used to list the
manual, which was released
in 1979. It has BSD-like op-
processes running on the system.
tions, GNU-like options, and
There are a lot of options and flags that can be used
System V-like options.
with the ps command. The flags are of multiple
types, and some flags perform the same function
but are named differently. This is because the ps
command has been around for a long time, and
has been implemented in multiple ways in different
systems. There are also different formats in which
the output can be displayed.
4.5.2 pstree
4.5.3 top
4.5.4 htop
4.5.5 btop
4.5.6 glances
▶ 0 - Success
▶ 1 - General error
▶ 2 - Misuse of shell builtins
▶ 126 - Command invoked cannot execute
▶ 127 - Command not found
▶ 128 - Invalid argument to exit
▶ 128+n - Fatal error signal "n"
▶ 130 - Script terminated by Ctrl+C
▶ 137 - Process killed with SIGKILL
▶ 255 - Exit status out of range
1 $ echo $BASH_SUBSHELL
2 0
3 $ (echo $BASH_SUBSHELL)
4 1
5 $ (:;(echo $BASH_SUBSHELL ))
6 2
7 $ (:;(:;(echo $BASH_SUBSHELL )))
8 3
5.2 Streams
5.3 Redirection
5: We will cover pipes in the However, it can still be tricked by using a pipe. 5
next section.
1 $ echo hello > hello
2 $ cat hello | cat >> hello
3 $ cat hello
4 hello
5 hello
2 $ echo $myline
3 rex
11 this is space
12 this is tab
13 EOF
14 hello
15 this is space
16 this is tab
5.4 Pipes
1 $ date
2 Thu Jul 4 09:05:30 AM IST 2024
3 $ date | wc
4 1 7 32
tr ’A-Z’ ’a-z’
tr -cd ’a-z ’
tr ’ ’ ’\n’
grep .
4 in
5 wonderland
6 alices
7 adventures
8 in
9 wonderland
10 lewis
11 carroll
12 the
13 millennium
14 fulcrum
15 edition
16 chapter
17 i
18 down
19 the
20 rabbithole
21 alice
sort
10 a
11 a
12 a
13 a
14 a
15 a
16 a
17 a
18 a
19 a
20 a
21 a
uniq -c
14 1 abouttrying
15 2 above
16 1 abranch
17 1 absenceand
18 2 absurd
19 1 acceptance
20 2 accident
21 1 accidentally
sort -nr
14 313 was
15 241 that
16 237 as
17 202 her
18 190 at
19 169 on
20 161 all
21 158 with
/dev/null
/dev/zero
5.4 Pipes 243
Terminal 1:
1 $ cat /etc/profile > pipe1
Terminal 2:
1 $ wc pipe1
2 47 146 993 pipe1
Terminal 1:
1 $ grep linux pipe1
Terminal 2:
1 $ tree / > pipe1
1 $ myname="$(whoami)"
2 $ mypc="$(hostname)"
3 $ echo "Hello, $myname from $mypc"
4 Hello, sayan from rex
5.8 Summary
gr[ae]y
Ranges
2 a
3 a
4 a
5 a
6 b
7 $ echo "ranges are separated by hyphens like -
" | grep -o ’[-a-c]’
8 a
9 a
10 a
11 a
12 b
13 -
The caret symbol ^ is used to
negate the list of characters
if it is the first character in
the list, else it is matched lit-
erally. First case will match
any character except l, i, n,
e, and the second case will
match only the characters l,
Example for ^:
i, n, e and the caret symbol
^. 1 $ echo "this is a ^line^" | grep -o ’[^line]’
2 t
3 h
4 s
5
6 s
7
8 a
9
10 ^
11 ^
12 $ echo "this is a ^line^" | grep -o ’[line^]’
13 i
14 i
15 ^
16 l
17 i
18 n
19 e
20 ^
6.3 Regular Expressions 271
Collating Symbols
For example, the Welsh alphabet 4 has a number of 4: Read more about the
Welsh alphabet here.
digraphs that are treated as a single letter (marked
with a * below)
1 a b c ch d dd e f ff g ng h i j l ll m n o p
ph r rh s t th u w y
2 * * * *
* * *
5: a collating symbol will
Assuming the locale file defines it 5 , the collating
only work if it is defined in
symbol [[.ng.]] is treated like a single character. the current locale
Likewise, a single character expression like . or [^a]
will also match "ff" or "th." This also affects sorting,
so that [p-t] will include the digraphs "ph" and
"rh" in addition to the expected single letters.
Equivalence Classes
Escape Sequences
6.3.3 Anchors
6.3.4 Quantifiers
3 he
4 re
5 a
6 re
7
8 t
9 he
10 re
11
12 mai
13 n
14
15 qua
16 n
17 ti
18 fie
19 r
20 s
21 ,
22
23 w
24 hi
25 c
26 h
27 a
28 re
29 a
30 s
31 te
32 ri
33 s
34 k
35
36 (
37 *
38 )
39 ,
40
41 p
42 lu
43 s
278 6 Pattern Matching
44
45 (
46 +
47 )
48 ,
49 a
50 n
51 d
52 e
53 ro
54 te
55 me
56
57 (
58 ?
59 )
60 .
7 re
8 mai
9 qua
10 ti
11 fie
12 hi
13 a
14 re
15 a
16 te
17 ri
18 lu
19 a
20 e
21 ro
22 te
23 me
17 ti
18 fi
19 r
20 s
21 ,
22
23 w
24 hi
25 c
26 h
27 a
28 re
29 a
30 s
31 te
32 ri
33 s
34 k
35
36 (
37 *
38 )
39 ,
40
41 p
42 lu
43 s
44
45 (
46 +
47 )
48 ,
49 a
50 n
51 d
52 e
53 ro
54 te
55 me
56
57 (
6.3 Regular Expressions 281
58 ?
59 )
60 .
6.3.6 Grouping
6.3.7 Backreferences
37 ulu
38 umu
39 upu
40 uru
41 usu
42 utu
43 vav
44 viv
45 waw
46 wnw
47 wow
48 wsw
49 xix
50 xxx
51 zzz
6.5.5 Comments
▶ - Translate characters.
tr
▶ cut- Cut out fields (columns) from a line.
▶ grep - Search for patterns in a file.
▶ sed - Stream editor - search and replace, insert,
select, delete, translate.
▶ awk - A programming language for text pro-
cessing.
6.6.1 tr
Ciphers
1 , 2 , 3 , 4 , 5 , 6 , 7 , 2.
1 $ echo "abcdefghijklmnopqrstuvwxyz" | tr ’a-z’
’1-26’
2 12666666666666666666666666
3 $ tr ’a-z’ ’1-72’ <<< "
abcdefghijklmnopqrstuvwxyz"
4 12345672222222222222222222
Deletion
9 Bob,M
We had to use \K and
10 Carla,F we could not use a
11 $ cut -d, -f2-3 data.csv lookbehind assertion, as
12 age,gender lookbehind assertions are
13 18,F fixed length, and we do not
14 32,M know the length of the first
column. We could have used
15 23,F
a lookbehind assertion if we
16 $ cut -d, -f2- data.csv knew the length of the first
17 age,gender column.
18 18,F
19 32,M
20 23,F
The range is inclusive, that 1 $ cut -d: -f1,5-7 /etc/passwd | tail -n5
is, it includes the start and 2 dhcpcd:dhcpcd privilege separation:/:/usr/bin/
end columns. nologin
3 redis:Redis in-memory data structure store:/
If the start of the range is
absent, it is assumed to be var/lib/redis:/usr/bin/nologin
the first column. 4 saned:SANE daemon user:/:/usr/bin/nologin
5 tor::/var/lib/tor:/usr/bin/nologin
If the end of the range 6 test1::/home/test1:/usr/bin/bash
is absent, it is assumed to be
the last column.
Exercise 6.6.1 Now that you are familiar with
This lets us extract
columns even if we do
the /etc/passwd file, try to extract the usernames
not know the number of and the home directories of the users. The user-
columns in the file. names are the first field, and the home directo-
Here we are using the / ries are the sixth field. Use the cut command to
etc/passwd file as an ex-
extract the usernames and the home directories
ample. The /etc/passwd
file is a text file that con-
of the users.
tains information about the
users on the system. It con-
tains information like the
username, user ID, group Delimiter
ID, home directory, and shell.
The file is a colon-separated
file, where each line contains
The default delimiter for cut is the tab character.
information about a single However, we can specify the delimiter using the
user. The fields are separated -d flag. Although it is not required to quote the
by colons, and the fields are delimiter, certain characters might be apprehended
the username, password (it
is not stored, so it is always
by the shell and not passed as-is to the command,
x), user ID, group ID, user hence it is always best practice to quote the delimiter
information (this is usually using single-quotes. The delimiter has to be a single
used by modern distrbutions
character, and cannot be more than one character.
to store the user’s full name),
home directory, and shell.
The input delimiter can only be speficied if splitting
The file is readable by all
users, but only writable by the file by fields, that is, when we are using -f flag
the root user. The file is used with a field or range of fields.
by the system to authenticate
users and to store informa-
tion about the users on the
Output Delimiter
system.
Character Range
Complement
6.6.3 paste
6.6.4 fold
9 6
10 7
11 8
12 9
13 $ fold -w2 data.txt
14 12
15 34
16 56
17 78
18 9
6.6.5 grep
6.6.6 sed
6.6.7 awk
7.2 PCRE
7.4.1 Disjunction
7.4.2 Conjunction
2 appleberry
3 appleblossom
4 applecart
5 apple-cheeked
6 appled
7 appledrane
8 appledrone
9 apple-eating
10 apple-faced
11 apple-fallow
12 $ grep -i ’apple’ /usr/share/dict/words | head
13 Apple
14 appleberry
15 Appleby
16 appleblossom
17 applecart
18 apple-cheeked
19 appled
20 Appledorf
21 appledrane
22 appledrone
5 blackberry
6 raspberry
7 strawberry
8 $ grep -v ’berry’ data.txt
9 apple
10 banana
4 strapple
5 thorn-apple
6 thrapple
7 toffee-apple
8 undappled
9 ungrapple
10 ungrappled
11 ungrappler
12 $ grep -w ’apple’ /usr/share/dict/words | tail
13 may-apple
14 oak-apple
15 pine-apple
16 pond-apple
17 rose-apple
18 snap-apple
19 sorb-apple
20 star-apple
21 thorn-apple
22 toffee-apple
13 this is linux
13 systemd-journal-upload:x:979:979:systemd
Journal Upload:/:/usr/bin/nologin
14 systemd-resolve:x:978:978:systemd Resolver:/:/
usr/bin/nologin
15 systemd-timesync:x:977:977:systemd Time
Synchronization:/:/usr/bin/nologin
16 tss:x:976:976:tss user for tpm2:/:/usr/bin/
nologin
17 uuidd:x:68:68::/:/usr/bin/nologin
18 avahi:x:974:974:Avahi mDNS/DNS-SD daemon:/:/
usr/bin/nologin
19 named:x:40:40:BIND DNS Server:/:/usr/bin/
nologin
20 dnsmasq:x:973:973:dnsmasq daemon:/:/usr/bin/
nologin
21 geoclue:x:972:972:Geoinformation service:/var/
lib/geoclue:/usr/bin/nologin
22 _talkd:x:970:970:User for legacy talkd server
:/:/usr/bin/nologin
23 nbd:x:969:969:Network Block Device:/var/empty
:/usr/bin/nologin
24 nm-openconnect:x:968:968:NetworkManager
OpenConnect:/:/usr/bin/nologin
25 nm-openvpn:x:967:967:NetworkManager OpenVPN
:/:/usr/bin/nologin
26 nvidia-persistenced:x:143:143:NVIDIA
Persistence Daemon:/:/usr/bin/nologin
27 openvpn:x:965:965:OpenVPN:/:/usr/bin/nologin
28 partimag:x:110:110:Partimage user:/:/usr/bin/
nologin
29 polkitd:x:102:102:PolicyKit daemon:/:/usr/bin/
nologin
30 rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/
usr/bin/nologin
31 rpcuser:x:34:34:RPC Service User:/var/lib/nfs
:/usr/bin/nologin
32 rtkit:x:133:133:RealtimeKit:/proc:/usr/bin/
nologin
33 sddm:x:964:964:SDDM Greeter Account:/var/lib/
sddm:/usr/bin/nologin
7.11 Limiting Output 323
34 usbmux:x:140:140:usbmux user:/:/usr/bin/
nologin
35 qemu:x:962:962:QEMU user:/:/usr/bin/nologin
36 cups:x:209:209:cups helper user:/:/usr/bin/
nologin
37 dhcpcd:x:959:959:dhcpcd privilege separation
:/:/usr/bin/nologin
38 redis:x:958:958:Redis in-memory data structure
store:/var/lib/redis:/usr/bin/nologin
39 saned:x:957:957:SANE daemon user:/:/usr/bin/
nologin
40 tor:x:43:43::/var/lib/tor:/usr/bin/nologin
41 $ grep ’nologin’ /etc/passwd | head -n5
42 bin:x:1:1::/:/usr/bin/nologin
43 daemon:x:2:2::/:/usr/bin/nologin
44 mail:x:8:12::/var/spool/mail:/usr/bin/nologin
45 ftp:x:14:11::/srv/ftp:/usr/bin/nologin
46 http:x:33:33::/srv/http:/usr/bin/nologin
47 $ grep ’nologin’ /etc/passwd -m5
48 bin:x:1:1::/:/usr/bin/nologin
49 daemon:x:2:2::/:/usr/bin/nologin
50 mail:x:8:12::/var/spool/mail:/usr/bin/nologin
51 ftp:x:14:11::/srv/ftp:/usr/bin/nologin
52 http:x:33:33::/srv/http:/usr/bin/nologin
1 $ cat hello.txt
2 hello world
3 hello universe
4 $ cat linux.txt
5 this is linux
6 $ grep -l hello *txt
7 hello.txt
8 $ grep -l this *txt
9 linux.txt
10 $ grep -l i *txt
11 hello.txt
12 linux.txt
324 7 Grep
User Commands
ECHO(1)
3 NAME
4 echo - display a line of text
5 SYNOPSIS
6 echo [SHORT-OPTION]... [STRING]...
7 echo LONG-OPTION
8 DESCRIPTION
9 Echo the STRING(s) to standard output.
10 -n do not output the trailing
newline
8.2 Printing Variables to the Terminal 335
11 -e enable interpretation of
backslash escapes
12 -E disable interpretation of
backslash escapes (default)
13 --help display this help and exit
14 --version
15 output version information and
exit
16 If -e is in effect, the following
sequences are recognized:
1 $ echo --version
2 --version
1 $ /bin/echo --version
2 echo (GNU coreutils) 9.5
3 Copyright (C) 2024 Free Software Foundation,
Inc.
4 License GPLv3+: GNU GPL version 3 or later <
https://gnu.org/licenses/gpl.html>.
5 This is free software: you are free to change
and redistribute it.
6 There is NO WARRANTY, to the extent permitted
by law.
7
8 Written by Brian Fox and Chet Ramey.
Escape Characters
3 \b backspace
4 \c suppress further output
5 \e escape character
6 \E escape character
7 \f form feed
8 \n new line
9 \r carriage return
10 \t horizontal tab
11 \v vertical tab
12 \\ backslash
13 \0nnn the character whose ASCII code
is NNN (octal). NNN can be
14 0 to 3 octal digits
15 \xHH the eight-bit character whose
value is HH (hexadecimal). HH
16 can be one or two hex digits
17 \uHHHH the Unicode character whose
The backspace character \b
value is the hexadecimal value HHHH.
moves the cursor one charac-
18 HHHH can be one to four hex
ter to the left. This is useful to
digits. overwrite a previously typed
19 \UHHHHHHHH the Unicode character whose character.
value is the hexadecimal value The suppress further output
20 HHHHHHHH. HHHHHHHH can be one character \c suppresses the
to eight hex digits. output of any text present
after it.
1 $ echo -e "abc\bd" The escape character \e is
2 abd used to escape the escape
character after it, but contin-
1 $ echo -e "abc\cde" ues printing after that.
2 abc The form feed character \f
and vertical tab character
1 $ echo -e "abc\ede" \v moves the cursor to the
2 abce next line, but does not move
the cursor to the start of line,
1 $ echo -e "abc\fde" remaining where it was in
2 abc the previous line.
3 de The carriage return character
\r moves the cursor to the
1 $ echo -e "abc\vde" start of the line. This can be
2 abc used to overwrite some parts
3 de of the previously written line.
Characters not overwritten
1 $ echo -e "abc\rde" remain intact. Here the de
overwrite the ab but the c
remains intact.
338 8 Shell Variables
2 dec
The new line character \n
moves the cursor to the next 1 $ echo -e "abc\nde"
line and the cursor to the 2 abc
start of the line. This is same 3 de
as performing \f\r.
The horizontal tab character 1 $ echo -e "abc\tde"
\t moves the cursor to the 2 abc de
next tab stop.
The octal and hexadecimal 1 $ echo -e "\0132"
characters can be used to 2 Z
print the character with the 3 $ echo -e "\x41"
given ASCII code. Here, \ 4 A
x41 is the ASCII code for A
and \0132 is the ASCII code
for Z.
8.2.2 Accessing and Updating Numeric
Variables
9 25
10 $ echo $((var/5))
11 1
12 $ echo $((var%5))
13 0
14 $ echo $((var**2))
15 25
Bitwise Operations
1 $ var=5
2 $ ((var++))
3 $ echo $var
4 6
8.3 Removing Variables 343
2 $ echo $var
3 Hello World
4 $ var=""
5 $ echo $var
8.4.1 set
8.4.2 declare
8.4.3 env
3 WINDOWID=100663324
4 COLORTERM=truecolor
5 LANGUAGE=
6 LC_ADDRESS=en_US.UTF-8
7 JAVA_HOME=/usr/lib/jvm/default
8 LC_NAME=en_US.UTF-8
9 SSH_AUTH_SOCK=/run/user/1000/ssh-agent.socket
10 SHELL_SESSION_ID=91
c0e4dcd4b644e8bfa2a25613b60f60
11 XDG_CONFIG_HOME=/home/sayan/.config
8.4.4 printenv
7 USER=sayan
8 CLOUDSDK_PYTHON=/usr/bin/python
9 COLORFGBG=15;0
10 VISUAL=nvim
11 SSH_AUTH_SOCK=/run/user/1000/ssh-agent.socket
8.5.1 PWD
The PWD variable is updated
1 $ echo $PWD whenever the current work-
2 /home/sayan ing directory changes.
3 $ cd /tmp
4 $ echo $PWD
5 /tmp
8.5.2 RANDOM
The RANDOM variable stores
1 $ echo $RANDOM a random number between 0
2 11670 and 32767, and is constantly
changed.
3 $ echo $RANDOM
4 29897
8.5.3 PATH
8.5.4 PS1
3 default
4 $ echo $var
5 default
6 $ var=hello
7 $ echo ${var:=default}
8 hello
9 $ echo $var
10 hello
1 $ var="Hello World"
2 $ echo ${var:0:5}
3 Hello
4 $ echo ${var:6:5}
5 World
6 $ echo ${var:6:50}
7 World
8 $ echo ${var: -5:5}
9 World
10 $ echo ${var: -11:5}
11 Hello
This matches all the words after the first word, and
deletes them. Here the match is always greedy, and
will match the longest possible string.
▶ i: interactive shell
▶ m: monitor the jobs and report changes
▶ B: braceexpand - expand the expression in
braces
▶ H: histexpand - expand the history command
▶ s: Read commands from the standard input.
8.9 Signals
8.10 Brace Expansion 363
Syntax:
1 {start...end}
1 $ echo {1..5}
2 1 2 3 4 5
Syntax:
1 {string1,string2,string3}
16 | | |-- file4.txt
17 | | ‘-- file5.txt
18 | ‘-- 3
19 | |-- file1.txt
20 | |-- file2.txt
21 | |-- file3.txt
22 | |-- file4.txt
23 | ‘-- file5.txt
24 |-- b
25 | |-- 1
26 | | |-- file1.txt
27 | | |-- file2.txt
28 | | |-- file3.txt
29 | | |-- file4.txt
30 | | ‘-- file5.txt
31 | |-- 2
32 | | |-- file1.txt
33 | | |-- file2.txt
34 | | |-- file3.txt
35 | | |-- file4.txt
36 | | ‘-- file5.txt
37 | ‘-- 3
38 | |-- file1.txt
39 | |-- file2.txt
40 | |-- file3.txt
41 | |-- file4.txt
42 | ‘-- file5.txt
43 ‘-- c
44 |-- 1
45 | |-- file1.txt
46 | |-- file2.txt
47 | |-- file3.txt
48 | |-- file4.txt
49 | ‘-- file5.txt
50 |-- 2
51 | |-- file1.txt
52 | |-- file2.txt
53 | |-- file3.txt
54 | |-- file4.txt
55 | ‘-- file5.txt
56 ‘-- 3
8.11 History Expansion 367
57 |-- file1.txt
58 |-- file2.txt
59 |-- file3.txt
60 |-- file4.txt
61 ‘-- file5.txt
62
63 13 directories, 45 files
8.12 Arrays
1 $ arr=(1 2 3 4 5)
2 $ arr[10]=6
3 $ echo ${arr[@]}
4 1 2 3 4 5 6
5 $ echo ${!arr[@]}
6 0 1 2 3 4 10
7 $ unset arr[10]
8 $ echo ${arr[@]}
9 1 2 3 4 5
10 $ echo ${!arr[@]}
11 0 1 2 3 4
8.12 Arrays 371
1 $ declare -A arr
2 $ arr=(["name"]="Sayan" ["age"]=22)
3 $ echo ${arr[name]}
4 Sayan
5 $ arr["age"]=23
6 $ echo ${#arr[@]}
7 2
8 $ echo ${!arr[@]}
9 age name
10 $ echo ${arr[@]}
11 23 Sayan
12 $ unset arr[name]
9.2 Shebang
1 $ cat script.py
2 #!/usr/bin/python3
3 print("Hello, World!")
4 $ python3 script.py
5 Hello, World!
6 $ chmod u+x script.py
7 $ ./script.py
8 Hello, World!
9.3 Comments
9.4 Variables
1 $ cat variables.sh
2 name="alice"
3 dob=2001
4 $ source variables.sh
5 $ echo "Hello, ${name^}! You are $((2024 - dob
)) years old."
6 Hello, Alice! You are 23 years old.
9.5 Arguments
1 $ cat arguments.sh
2 echo $0
3 $ ./arguments.sh
4 ./arguments.sh
5 $ bash arguments.sh
6 arguments.sh
7 $ source arguments.sh
8 /bin/bash
9 $ echo $0
9.5 Arguments 381
10 /bin/bash
8 World
2 args=("$@")
3 echo $#
4 for ((i=0; i < $#; i++)); do
5 echo "${args[i]}"
6 done
7 $ bash args.sh hello how are you
8 4
9 hello
10 how
11 are
12 you
9.7 Conditionals
String condtions
Unary Operators
1 $ var=""
2 $ test -n "$var" ; echo $?
3 1
4 $ test -z "$var" ; echo $?
5 0
Binary Operators
The =, !=, <, and > flags of test check if two strings
are equal, not equal, less than, or greater than each
other.
1 $ var="apple"
2 $ test "$var" = "apple" ; echo $?
3 0
4 $ test "$var" != "apple" ; echo $?
5 1
1 $ var="apple"
2 $ test "$var" = "banana" ; echo $?
We are escaping the > and < 3 1
characters as they have spe-
4 $ test "$var" != "banana" ; echo $?
cial meaning in the shell. If
5 0
we do not escape them, the
shell will try to redirect the
1 $ var="apple"
input or output of the com-
mand to/from a file. We can 2 $ test "$var" \< "banana" ; echo $?
also quote the symbols in- 3 0
stead of escaping them.
9.7 Conditionals 389
Numeric conditions
File conditions
File Permissions
Binary Operators
Other conditions
▶ ! - Logical NOT
▶ -v - if the variable is set
▶ -o - if the shopt option is set (when used as
unary operator)
Logical Operators
1 $ var="apple"
2 $ [ "$var" = "apple" -a 1 -eq 1 ] ; echo $?
3 0
4 $ [ "$var" = "apple" ] && [ 1 -eq 1 ] ; echo $
?
5 0
Comparison Operators
Regular Expressions
Globbing
Double Equals
9.8 If-elif-else
9.8.1 If
9.8.2 Else
Figure 9.1: Flowchart of the To fix this, we can use the elif keyword, which is
if, elif, and else con- short for else if.
struct
9.9 Exit code inversion 397
9.8.3 Elif
9.12 Switch
1 $ cat select.sh
2 select choice in dog cat bird stop
3 do
4 case $choice in
5 dog) echo "A dog barks" ;;
6 cat) echo "A cat meows" ;;
7 bird) echo "A bird chirps" ;;
8 stop) break ;;
9 *) echo "Invalid choice" ;;
10 esac
11 done
12 $ bash select.sh
13 1) dog
14 2) cat
15 3) bird
16 4) stop
17 #? 1
18 A dog barks
19 #? 2
20 A cat meows
21 #? 3
22 A bird chirps
23 #? 4
a case statement.
9.14 Loops
1 $ cat foreach.sh
2 for item in mango banana strawberry; do
3 echo "$item shake"
4 done
5 $ bash foreach.sh
6 mango shake
7 banana shake
8 strawberry shake
Splitting by spaces:
1 $ cat forsplit.sh
2 name=("Sayan" "Alice" "John Doe")
3 for name in ${name[@]}; do
4 echo "Name: $name"
5 done
404 9 Shell Scripting
6 $ bash forsplit.sh
7 Name: Sayan
8 Name: Alice
9 Name: John
10 Name: Doe
1 $ cat range.sh
2 for i in $(seq 1 5); do
3 echo "Number: $i"
4 done
5 $ bash range.sh
6 1
7 2
8 3
9 4
9.14 Loops 405
10 5
Letters:
1 $ echo {a..e}
2 a b c d e
3 $ seq a e
4 seq: invalid floating point argument: ’a’
5 Try ’seq --help’ for more information.
4 2.0
5 $ echo {1..2..0.5}
6 {1..2..0.5}
6 Number: 0
7 Number: 1
8 Number: 2
9 Number: 3
10 Number: 4
9.14.3 IFS
5 unset IFS
6 var="a b c:d"
7 for i in $var; do
8 echo $i
9 done
10 $ bash unsetifs.sh
11 a
12 b
13 c:d
Break:
1 $ cat pat.sh
2 for i in {1..5}; do
3 for j in {1..5}; do
4 if [[ "$j" -eq 3 ]]; then
5 break;
6 fi
7 echo -n $j
8 done
9 echo
10 done
11 $ bash pat.sh
12 12
13 12
14 12
15 12
16 12
Continue:
1 $ cat pat.sh
2 for i in {1..5}; do
3 for j in {1..5}; do
4 if [[ "$j" -eq 3 ]]; then
5 continue;
9.14 Loops 415
6 fi
7 echo -n $j
8 done
9 echo
10 done
11 $ bash pat.sh
12 1245
13 1245
14 1245
15 1245
16 1245
9 echo
10 done
11 $ bash pat.sh
12 1212121212
9.15 Functions
Example:
1 $ cat functions.sh
2 sayhi(){
3 echo "Hello, $1"
4 }
5
6 sayhi "John"
7 $ bash functions.sh
8 Hello, John
9.15 Functions 417
Arguments in Functions
13 case "$operator" in
14 plus) answer=$(add $op1 $op2) ;;
15 multiply) answer=$(mul $op1 $op2) ;;
16 *) echo "Invalid option" ;;
17 esac
18 echo "Answer is $answer"
19 done
20 $ bash calc.sh
21 1) plus
22 2) multiply
23 #? 1
24 Operand 1: 5
25 Operand 2: 4
26 Answer is 9
27 #? 2
28 Operand 1: 6
29 Operand 2: 3
30 Answer is 18
31 #?
16 }
17
18 fun 5
19 echo return value: $?
20 fun 15
21 echo return value: $?
22 fun -5
23 echo return value: $?
24 $ bash return.sh
25 01234
26 return value: 0
27 0123456789
28 return value: 0
29 return value: 1
9.16 Debugging
1 $ cat debug.sh
2 fun(){
3 echo $(($1 + $2))
4 }
5
6 fun $(fun $(fun 1 2) 3) 4
7 $ bash debug.sh
8 10
9.17 Recursion
9 done
10 echo $a
11 }
12
13 time fibo 40
14 $ bash fibo.sh
15 102334155
16
17 real 0m0.001s
18 user 0m0.001s
19 sys 0m0.000s
9.18.1 bc
9.18.2 expr
5 $ expr 5 ’<’ 6
6 1
7 $ echo $?
8 0
9.19.1 exec
9.20 Getopts
9.22 Summary
Construct Description
if Execute a block of code based on a condition.
case Execute a block of code based on a pattern.
for Iterate over a list of elements.
while Execute a block of code as long as a condition is true.
until Execute a block of code as long as a condition is false.
break Exit the loop immediately.
continue Skip the rest of the code in the loop and go to the next iteration.
read Read input from the user.
unset Unset a variable.
local Declare a variable as local to a function.
return Return from a function.
source Run a script file in the current shell.
eval Run arbritary commands in the current shell.
exec Run arbritary commands in the current shell.
getopts Parse command line arguments.
Stream Editor 10
Stream Editor (sed) is a powerful text stream editor.
It is used to perform basic text transformations on an
input stream (a file or input from a pipeline). While Figure 10.1: Filtering
in some ways similar to an editor which permits Streams
scripted edits (such as ed), sed works by making
only one pass over the input(s), and is consequently
more efficient. But it is sed’s ability to filter text in
a pipeline which particularly distinguishes it from
other types of editors.
10.2 Addressing
2 10
3 11
4 12
5 19
6 20
10.2.1 Negation
10.3 Commands
10.3.4 Printing
10.3.5 Deleting
10.3.6 Substitution
5 one1
6 one2
Backreferences
wc emulation
2 1
3 hello
4 2
5 hello
6 3
7 hello
8 4
9 hello
10 5
11 hello
10.3.10 Transliteration
6 $ sed -i ’/^LAUNCH_ICBM/{s/FALSE/TRUE/;tx;s/
TRUE/FALSE/}; :x’ usa.conf
7 $ cat usa.conf
8 LAUNCH_ICBM=FALSE
10.6.2 Shebang
or
1 #!/usr/bin/sed -f
10.7.1 Labels
1 $ cat script.sed
2 :label1
3 5p
4 :label2
5 10p
6 $ seq 10 | sed -n -f script.sed
7 5
8 10
10.7.2 Branching
Unconditional Branching
5 :x
6 a Universe
7 $ sed -nf script.sed <<< "test"
8 Hello
9 Universe
5 $ cat data
6 this is a long line with lots of words, we
want to capitalize each first letter of a
word.
7 $ sed -f script.sed data
8 This Is A Long Line With Lots Of Words, We
Want To Capitalize Each First Letter Of A
Word.
Conditional Branching
10.7.5 If-Else
10.7.6 If-elif-else