System Commands (SC)
System Commands (SC)
Lecture 1.2
pwd — “print working directory”
when you run pwd it prints the full absolute path of the current working
directory
hunder@thunder-VMware-Virtual-Platform:~$ pwd
/home/thunder
ls — “list”
when you run ls it prints the files and directories present in the current
working directory
thunder@thunder-VMware-Virtual-Platform:~$ ls
Desktop Documents Downloads Music Pictures Public snap Template
s Videos
ps — “process status”
when you run ps it prints the a snapshot of the currently running processes
for the current user/session
thunder@thunder-VMware-Virtual-Platform:~$ ps
PID TTY TIME CMD
9302 pts/0 [Link] bash
9556 pts/0 [Link] ps
PID — Process ID
Week 1 1
⚠️ ps -e or ps -A — shows all processes on the system
thunder@thunder-VMware-Virtual-Platform:~$ ps -f
UID PID PPID C STIME TTY TIME CMD
thunder 9302 9294 0 11:23 pts/0 [Link] bash
thunder 10667 9302 0 12:03 pts/0 [Link] ps -f
thunder@thunder-VMware-Virtual-Platform:~$ uname
Linux
Week 1 2
⚠️ uname -a — all system information
thunder@thunder-VMware-Virtual-Platform:~$ uname -a
Linux thunder-VMware-Virtual-Platform 6.11.0-25-generic #25~2
4.04.1-Ubuntu SMP PREEMPT_DYNAMIC Tue Apr 15 [Link] UT
C 2 x86_64 x86_64 x86_64 GNU/Linux
⚠️ user@machine:~$ ls -a —
ls — Command
-a — option
user@machine:~$ man ls
man — command
ls — argument
ls -a —
Week 1 3
ls -acommand, which lists all files and directories, including hidden ones
(hidden ones are those that start with a dot . )
thunder@thunder-VMware-Virtual-Platform:~$ ls -a
. .bashrc Documents .local .profile .sudo_as_admin_successful
.. .cache Downloads Music Public Templates
.bash_history .config .gnupg Pictures snap Videos
.bash_logout Desktop .lesshst .pki .ssh
Name What It Is
. The current directory (your home directory)
ls -l —
It gives detailed information about each file and directory in the current
location
thunder@thunder-VMware-Virtual-Platform:~$ ls -l
total 36
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Desktop
drwxr-xr-x 2 thunder thunder 4096 May 16 13:25 Documents
drwxr-xr-x 2 thunder thunder 4096 May 18 12:31 Downloads
Week 1 4
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Music
drwxr-xr-x 2 thunder thunder 4096 May 16 13:28 Pictures
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Public
drwx------ 7 thunder thunder 4096 May 18 12:31 snap
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Templates
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Videos
Column Meaning
drwxr-xr-x Permissions and file type
2 Number of hard links
thunder Owner (username)
thunder Group (group name)
4096 Size in bytes
May 16 00:54 Last modified date & time
Desktop File or directory name
Week 1 5
File system: traversing the tree
. is current directory
.. is parent directory
Week 1 6
cd — “Change Directory”
It is used to move between folders (directories) in the terminal.
cd foldername
Week 1 7
⚠️ cd — Takes you to your home directory
Week 1 8
🧪
thunder@thunder-VMware-Virtual-Platform:~$ pwd
/home/thunder
thunder@thunder-VMware-Virtual-Platform:~$ ls
Desktop Documents Downloads Music Pictures Publ
ic snap Templates Videos
thunder@thunder-VMware-Virtual-Platform:~$ ls -a
. .bashrc Documents .local .profile .sudo_as
_admin_successful
.. .cache Downloads Music Public Templat
es
.bash_history .config .gnupg Pictures snap Vide
os
.bash_logout Desktop .lesshst .pki .ssh
Week 1 9
Listed all files, including hidden ones (those starting
with . )
thunder@thunder-VMware-Virtual-Platform:~$ cd ..
thunder@thunder-VMware-Virtual-Platform:/home$ pw
d
/home
thunder@thunder-VMware-Virtual-Platform:~$ cd ..
thunder@thunder-VMware-Virtual-Platform:/$ pwd
/
thunder@thunder-VMware-Virtual-Platform:~$ cd
thunder@thunder-VMware-Virtual-Platform:~$ pwd
/home/thunder
thunder@thunder-VMware-Virtual-Platform:~$ cd /
thunder@thunder-VMware-Virtual-Platform:~$ cd /
thunder@thunder-VMware-Virtual-Platform:/$ ls
Week 1 10
thunder@thunder-VMware-Virtual-Platform:~$ cd /
thunder@thunder-VMware-Virtual-Platform:/$ ls
thunder@thunder-VMware-Virtual-Platform:/$ ls -a
thunder@thunder-VMware-Virtual-Platform:~$ cd /
thunder@thunder-VMware-Virtual-Platform:/$ ls
thunder@thunder-VMware-Virtual-Platform:/$ ls -a
thunder@thunder-VMware-Virtual-Platform:/$ cd bin
thunder@thunder-VMware-Virtual-Platform:/bin$ ls -a
Week 1 11
/var — Variable data
thunder@thunder-VMware-Virtual-Platform:~$ cd /
thunder@thunder-VMware-Virtual-Platform:/$ ls
#here all the entries will show for the root directory
thunder@thunder-VMware-Virtual-Platform:/$ cd usr
thunder@thunder-VMware-Virtual-Platform:/usr$ ls
#here all the entries will show for usr directory
processes
/usr/lib — libraries
Shareable unsharable
/usr /etc
static
/opt /boot
Week 1 12
/var/run
variable /var/mail
/var/lock
Lecture 1.3
Week 1 13
🧪 date date and time thunder@thunder-VMware-
calendar of a Virtual-Platform:~$ date
cal
month Fri May 23 [Link] AM IST
memory 2025
free
statistics
thunder@thunder-VMware-Virtual-Platform:~$ groups
thunder adm cdrom sudo dip plugdev users lpadmin
Week 1 14
Year (e.g., 2025-05-23
+%Y
2025)
+%m Month (01–12) thunder@thunder-VMwar
e-Virtual-Platform:~$ date
Day of month
+%d -u
(01–31)
Fri May 23 [Link] AM U
+%H Hour (00–23)
TC 2025
+%M Minute (00–59)
memory stats
thunder@thunder-VMware-Virtual-Platform:~$ ls -l
total 36
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Desktop
drwxr-xr-x 2 thunder thunder 4096 May 16 13:25 Documents
drwxr-xr-x 2 thunder thunder 4096 May 18 12:31 Downloads
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Music
drwxr-xr-x 3 thunder thunder 4096 May 19 18:56 Pictures
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Public
drwx------ 7 thunder thunder 4096 May 18 12:31 snap
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Templates
drwxr-xr-x 2 thunder thunder 4096 May 16 00:54 Videos
Week 1 15
File Types
thunder@thunder-VMware-Virtual-Platform:~$ ls -i
3932236 Desktop 3932237 Downloads 3932242 Pictures
3932171 snap 3932243 Videos
3932240 Documents 3932241 Music 3932239 Public 3
932238 Templates
find -inum <number> — finds the file with the inode number <number>
Week 1 16
rwx — owner — read, write and execute
mkdir -p a/b/c — creates nested directories (a, a/b and a,b,c) in one go
Week 1 17
thunder@thunder-VMware-Virtual-Platform:~$ mkdir projects
thunder@thunder-VMware-Virtual-Platform:~$ cd projects
thunder@thunder-VMware-Virtual-Platform:~/projects$ mkdir c
ode notes data
thunder@thunder-VMware-Virtual-Platform:~/projects$ ls
code data notes
thunder@thunder-VMware-Virtual-Platform:~/projects/code
$ touch file
thunder@thunder-VMware-Virtual-Platform:~/projects/code
$ ls
file
thunder@thunder-VMware-Virtual-Platform:~/projects/code
$ touch [Link]
thunder@thunder-VMware-Virtual-Platform:~/projects/code
$ ls
[Link] file
Week 1 18
mkdir— creates directories and touch — creates empty files updates
timestamps
cp [Link] [Link]
cp [Link] /home/thunder/Documents/
mv [Link] /home/thunder/Documents/
mv [Link] [Link]
Week 1 19
[Link]
thunder@thunder-VMware-Virtual-Platform:~/billo$ mv bagg
[Link] ..
thunder@thunder-VMware-Virtual-Platform:~/billo$ ls
thunder@thunder-VMware-Virtual-Platform:~/billo$
thunder@thunder-VMware-Virtual-Platform:~$ ls
[Link] Desktop Downloads Music projects snap
Videos
billo Documents level1 Pictures Public Templates
thunder@thunder-VMware-Virtual-Platform:~$ rm [Link]
thunder@thunder-VMware-Virtual-Platform:~$ ls
billo Documents level1 Pictures Public Templates
Desktop Downloads Music projects snap Videos
thunder@thunder-VMware-Virtual-Platform:~$
rm -r foldername
then when you type shortname the shell runs the full command you
aliased
Week 1 20
alias ll='ls -l'
thunder@thunder-VMware-Virtual-Platform:~$ whoami
thunder
rm remove a file
Lecture 1.4
Week 1 21
🧪 Multiple uses of / is as good as one root folder / is its own parent
ls — list
recursive listing
thunder@thunder-VMware-Virtual-Platform:/etc$ ls -l profile
-rw-r--r-- 1 root root 582 Apr 22 2024 profile
its gives detailed information about the profile file located in the /etc
directory
scree at a time
less filename
#less /etc/profile
doesn’t load the entire file into memory - great for large files
Week 1 22
create new files
creates a new file and you can start typing content then press ctrl + D
head — is used to display the first few lines of a file (by default the
first 10 lines)
head filename
tail— is used to display the last part of a file typically the last 10
lines by default
tail filename
Week 1 23
this will show last 10 lines of the file
wc filename
this will display all lines, words, bytes, longest line length and also
the filename
thunder@thunder-VMware-Virtual-Platform:/etc$ wc profile
27 97 582 profile
command
which <command>
thunder@thunder-VMware-Virtual-Platform:~$ which ls
/usr/bin/ls
Week 1 24
verifying which version of a command you are using
more — to view the content of text files one screen at a time similar
to less but with more limited navigation.
more filename
man <command>
man ls
program -often more extensive than man pages. it opens GNU info
pages which are structured and include navigation features
ifo <command>
info ls
Week 1 25
whatis <command>
thunder@thunder-VMware-Virtual-Platform:~$ whatis ls
ls (1) - list directory contents
commands that are part of the shell itself (like cd , echo , etc.)
help [builtin_command]
help cd
type — is used to display information about how a given command name will
be interpreted by the shell- whether it’s a builtin, an alias, a function or an
external executable
type [command]
thunder@thunder-VMware-Virtual-Platform:~$ type ls
ls is aliased to `ls --color=auto'
use cases —
Week 1 26
find whether a command has been aliased
location of a command
Week 1 27
🧪 Multiple arguments —
Second argument
Week 1 28
cp -r folder1/ folder2/
mv folder1/ folder2/
So, recursion is assumed (or automatic) for mv , but for cp you must
specify it with -r .
so the line
Multiple arguments —
1. “Second argument”
2. “Interpretation of last argument”
3. “Recursion assumed for mv and not not cp ”
Week 1 29
💡 Hard links
A hard link is an additional name for an existing file. It points directly to
the inode (the actual data on disk), not just the file name. All hard links to
a file are equal — they are indistinguishable from the original file
🧠key concepts:
Every file in Linux is a pointer to an inode, which stores the file's
actual data.
A hard link creates another name (or label) pointing to the same
inode.
Deleting one hard link does not delete the data as long as at least
one hard link exists
ln [Link] [Link]
this creates a hard link called [Link] that points to the same inode as
[Link]
deleting [Link] does not delete the data since [Link] still exists
Week 1 31
💡 Symbolic Links:—
A symbolic link is a special type of file that points to another file or
directory by name, not by inode.
🧠 Key Concepts
A symbolic link just contains a path to another file.
It’s a separate file that points to the target by name, not inode.
ln -s [Link] [Link]
rm [Link]
cat [Link]
Works across
filesystems
✅ Yes ❌ No
Can link directories ✅ Yes ❌ No
Week 1 32
Breaks if target deleted ✅ Yes ❌ No
Can be chained
✅ Yes (can link to another ❌ No
link)
ln file1 file2
Week 1 33
💡 File Sizes
ls -s [options] [file...]
$ ls -s
4 Desktop 8 Downloads 4 [Link]
This means:
ls -sh
4.0K Desktop 8.0K Downloads 4.0K [Link]
$ stat [Link]
File: [Link]
Size: 1024 Blocks: 8 IO Block: 4096 regular file
Device: 802h/2050d Inode: 1835026 Links: 1
Access: 2025-05-24 [Link].000000000 +0000
Modify: 2025-05-23 [Link].000000000 +0000
Change: 2025-05-23 [Link].000000000 +0000
Birth: -
Week 1 34
du [options] [file or directory]
du mydir
This will show how much space mydir and its subdirectories are
using in kilobytes (by default).
du -h #human-redable sizes
du -s #show only the total for each argument
du -a #show sizes for all files too
du -c #displayy a grand total
Block Size:— The block size in Linux (and other Unix-like systems)
plays a crucial role in how disk space is allocated and reported by
tools like du , ls , and stat .
A block is the smallest unit of data the filesystem uses to store files.
Common block sizes are 512 bytes, 1KB, 4KB, etc.
Term Meaning
Week 1 35
💡 In memory file-system
Entry Description
Week 1 36
devices, drivers, and the kernel itself. It’s part of a system called
sysfs.
What Is /sys ?
Path Description
/sys/class/ Contains high-level classes like net , block , power
/sys/block/ Info about block devices like sda , nvme0n1
/sys/bus/ Bus systems like pci , usb , and their devices
/sys/devices/ Tree of all physical and virtual devices
/sys/firmware/ Firmware-related interfaces (e.g., ACPI)
/sys/module/ Info about loaded kernel modules
/sys/kernel/ Kernel settings and information
/sys/power/ Power management (e.g., suspend, hibernate)
Week 1 37
Feature /proc /sys
Week 1 38
WEEK 2
Lecture 2.1 (Command line editors — Part 1)
WEEK 2 1
🧪
Features —
WEEK 2 2
Key-maps, init scripts, macros (Customizes editor behavior,
automates tasks, and binds keys to commands or sequences)
ed (ed is one of the oldest line editors in Unix and Linux systems)
2 — refers to line 2
. — current line
$ — last line
WEEK 2 3
f — show or set the current file name
edit a file — e filename (closes the current buffer and loads filename into
the editor (unsaved changes are lost unless written))
quit — q (exits the editor. Use Q to force quit without warning about
unsaved changes)
Creating a file —
WEEK 2 4
thunder@thunder-VMware-Virtual-Platform:~$ echo "line-3 ed is pe
rhaps the oldest ediotr out there" >> [Link]
thunder@thunder-VMware-Virtual-Platform:~$ echo "line-4 end of fi
le" >> [Link]
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link]
line- 1 hello world
line-2 hello world
line-3 ed is perhaps the oldest ediotr out there
line-4 end of file
thunder@thunder-VMware-Virtual-Platform:~$ ed [Link]
107
q
this means 107 bytes were loaded into the buffer — that’s the total size
of [Link] , and we used q to quits the editor without making any
changes
for more information —
thunder@thunder-VMware-Virtual-Platform:~$ ls -l [Link]
-rw-rw-r-- 1 thunder thunder 107 Jun 15 17:06 [Link]
where
-rw-rw-r-- — permissions
107 — size
[Link] — filename
WEEK 2 5
thunder@thunder-VMware-Virtual-Platform:~$ ed [Link]
107
P
*1
line- 1 hello world
*$
line-4 end of file
*,p
line- 1 hello world
line-2 hello world
line-3 ed is perhaps the oldest ediotr out there
line-4 end of file
*2,3p
line-2 hello world
line-3 ed is perhaps the oldest ediotr out there
*/hello/
line- 1 hello world
*/oldest/
line-3 ed is perhaps the oldest ediotr out there
*1
line- 1 hello world
*+
line-2 hello world
*-
line- 1 hello world
*3
line-3 ed is perhaps the oldest ediotr out there
*;p
line-3 ed is perhaps the oldest ediotr out there
line-4 end of file
*%p
line- 1 hello world
line-2 hello world
line-3 ed is perhaps the oldest ediotr out there
line-4 end of file
WEEK 2 6
*.
line-4 end of file
*!date
Sun Jun 15 [Link] PM IST 2025
!
*r !date
32
*,p
line- 1 hello world
line-2 hello world
line-3 ed is perhaps the oldest ediotr out there
line-4 end of file
Sun Jun 15 [Link] PM IST 2025
*w
139
*q
1 → Line 1
$ → Last line
,p → Print all lines
2,3p → Print lines 2 to 3
/hello/ → Search for "hello"
r !date — reads the output of ‘date’ and appends it after the current
line
WEEK 2 7
,p —
thunder@thunder-VMware-Virtual-Platform:~$ ed [Link]
139
P
*%s/\(.*\)/PREFIX\1/
*,p
PREFIXline- 1 hello world
PREFIXline-2 hello world
PREFIXline-3 ed is perhaps the oldest ediotr out there
PREFIXline-4 end of file
PREFIXSun Jun 15 [Link] PM IST 2025
*%s/\(.*\)/PREFIX \1/
*,p
PREFIX PREFIXline- 1 hello world
PREFIX PREFIXline-2 hello world
PREFIX PREFIXline-3 ed is perhaps the oldest ediotr out there
PREFIX PREFIXline-4 end of file
PREFIX PREFIXSun Jun 15 [Link] PM IST 2025
WEEK 2 8
*3,5s/PREFIX/prefix/
*,p
PREFIX PREFIXline- 1 hello world
PREFIX PREFIXline-2 hello world
prefix PREFIXline-3 ed is perhaps the oldest ediotr out there
prefix PREFIXline-4 end of file
prefix PREFIXSun Jun 15 [Link] PM IST 2025
— but since
%s/\(.*\)/PREFIX \1/ PREFIX was already there, this added
another PREFIX in front:
ed / ex commands —
WEEK 2 9
a — a ppend at the current line
j — j oin lines
WEEK 2 10
🧪 What is pico —
pico is a simple, easy-to -use command -line text editor originally
ctrl + w — Search
which pico — the command pico runs the executable (or link) located
at /usr/bin/pico
— the command
which nano nano runs the executable (or link) is
located at /usr/bin/nano
WEEK 2 11
ls -l /usr/bin/pico — this means /usr/bin/pico is a symbolic link pointing to
/etc/alternatives/pico
of the path.
readlink -e path — like -f but only returns result if all path components
exist
readlink -m path — resolves path even if some component don’t exist
resolving furthur
readlink -v path — Verbose output — prints what it’s doing
thunder@thunder-VMware-Virtual-Platform:~$ ls -l .bashrc
-rw-r--r-- 1 thunder thunder 3808 May 31 23:26 .bashrc
WEEK 2 12
— where
-rw-r--r-- rw- is owner can read and write r-- groups
can read
Aliases
Prompt settings
Environment variables
Modes in vi —
p — paste below
u — undo
insert mode — i , o , a , I , O . A
WEEK 2 13
🧠Purpose — Type and edit text like a normal text editor
Anything you type is inserted into the file
ex mode — :
:q — Quit
Exiting vi —
:w — write out
WEEK 2 14
0 — start of the current line
WEEK 2 15
?string — search backward for string
WEEK 2 16
⛔ Emacs
Features —
Moving around —
WEEK 2 17
ctrl + e — Go to end of current line
Exiting emacs
Searching text
Copy Paste
WEEK 2 18
Lecture 2.4 (Networking commands and SSH)
WEEK 2 19
⛔ Accessing remote machines on command line —
WEEK 2 20
Ways to gain remote access—
VPN access
WEEK 2 21
users to access internal systems and services as if they were on
the local network.
SSH tunneling
WEEK 2 22
Port 21 is associated with FTP (File Transfer Protocol) which is used
to transfer files between a client and a server over a network
Port 631 is the default port used by CUPS (Common Unix Printing
System) to allow network printing and printer administration via
the Internet Printing Protocol (IPP).
Protecting a server
WEEK 2 23
SELinux
Network tools
WEEK 2 24
whois lookup Who owns which domain name
thunder@thunder-VMware-Virtual-Platform:~$ ifconfig
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 15
00
inet [Link] netmask [Link] broadcast 192.168.
85.255
inet6 fe80::20c:29ff:fe62:939b prefixlen 64 scopeid 0x20<link
>
ether [Link] txqueuelen 1000 (Ethernet)
RX packets 284280 bytes 335129717 (335.1 MB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 78604 bytes 24620823 (24.6 MB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
WEEK 2 25
TX packets 2575 bytes 300420 (300.4 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo — Loppback Interface
Non-authoritative answer:
[Link] canonical name = [Link].
Name: [Link]
Address: [Link]
your browser or any tool will use to connect to the IITM website
WEEK 2 26
; <<>> DiG 9.18.30-0ubuntu0.24.04.2-Ubuntu <<>> [Link]
m
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 49597
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL:
1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;[Link]. IN A
;; ANSWER SECTION:
[Link]. 5 IN A [Link]
WEEK 2 27
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;[Link].[Link]. IN PTR
;; ANSWER SECTION:
[Link].[Link]. 5 IN PTR [Link].
[Link].[Link]. 5 IN PTR [Link]
t.
WEEK 2 28
WEEK 3
Lecture 3.1 (Combining commands and files) —
WEEK 3 1
⛔ Executing multiple commands —
command1 || command2
thunder@thunder-VMware-Virtual-Platform:~$ ls || date
billo Desktop Downloads Music Pictures Public Templates tes
[Link]
clear Documents level1 mydir projects snap [Link] Video
s
as the first command succeeds that’s why 2nd command doesn’t run
WEEK 3 2
thunder@thunder-VMware-Virtual-Platform:~$ /blah || ls && date &&
wc -l /etc/profile
bash: /blah: No such file or directory
billo Desktop Downloads Music Pictures Public Templates tes
[Link]
clear Documents level1 mydir projects snap [Link] Video
s
Sun Jun 29 [Link] AM IST 2025
27 /etc/profile
as the first command didn’t run that’s why 2nd command run
without any problem
as the first command didn’t run that’s why next other commands also
stops
as the 1st command successfully run that’s why 2nd command was
executing but as it throws error that’s why next command doesn’t
executed
File descriptors —
WEEK 3 3
This image visually represents the concept of standard streams in a
Unix/Linux environment, particularly focusing on input and output
redirection in the command-line (shell). Here's what it means:
WEEK 3 4
Example commands:
command > [Link] 2>&1 → Redirects both stdout and stderr to same file.
The command takes input from the keyboard ( stdin , file descriptor
0).
📌 Important Note
"Warning: contents of file1 will be overwritten. New file1 will be created
if it does not exist."
WEEK 3 5
this refers to what happens when you use the > redirection operator:
ls > [Link]
Example —
If it doesn't exist → the error message (like No such file or directory ) also
goes to [Link] .
ls -l > file1
WEEK 3 6
It ran ls -l in your current directory.
As you can now see in the second ls -l result, file1 is there and its
size is 941 bytes, indicating the output was written correctly.
The file file1 was created or overwritten, but it's empty ( 0 bytes ).
🧠Why —
> only redirects stdout
or even:
any_command > file1
even if the directory does't exist like here /blah does it exist so it
makes my content loss in file 1?
Yes, exactly. Even if the directory /blah doesn't exist, and the
WEEK 3 7
command fails — your file file1 is still emptied (i.e., its previous
content is lost) if you use the > redirection operator.
WEEK 3 8
This diagram illustrates the append redirection operator >> in
Unix/Linux shell.
✅ Explanation of the Diagram:
🔹 Command Used:
bash
CopyEdit
command >> file1
🔍 What Happens:
stdin (0) : Takes input from the keyboard (not redirected here).
stderr (2) : Standard error still goes to the screen, not the file.
WEEK 3 9
✅ Green Note:
Contents will be appended to file1.
⚠️ Red Note:
New file1 will be created if it does not exist.
bash
CopyEdit
command >> file1 2>&1
WEEK 3 10
⛔
This diagram explains how to redirect only the error output ( stderr ) to a
file using:
🔹 file1
Will receive only the error messages, not the regular output.
WEEK 3 11
2 stderr Goes to file1
✅ This means:
If file1 exists → it will be cleared first (overwritten).
🧪 Example:
ls /nonexistentfolder 2> [Link]
goes to [Link]
WEEK 3 12
thunder@thunder-VMware-Virtual-Platform:~$ ls $HOME /blah 2> b
[Link]
/home/thunder:
[Link] clear Documents file1 Music Pictures Public Templat
es [Link]
billo Desktop Downloads level1 mydir projects snap [Link]
rc Videos
🔍 What it did:
ls $HOME→ lists the contents of your home directory /home/thunder
(works fine).
this shows the error message that was captured after running ls
WEEK 3 13
This diagram demonstrates how to separately redirect standard output
(stdout) and standard error (stderr) into two different files using:
🧾 In Simple Terms:
> → redirects stdout to file1
WEEK 3 14
"Contents of file1 and file2 will be overwritten."
🧪 Example:
ls /home/thunder /blah > [Link] 2> [Link]
💡 Useful Variants:
Append instead of overwrite:
WEEK 3 15
mydir
[Link]
Pictures
projects
Public
snap
Templates
[Link]
[Link]
Videos
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link]
ls: cannot access '/blah': No such file or directory
🧠 What It Did:
Part Purpose Result
$HOME A valid path Contents listed normally
/blah Invalid path Triggered an error
> Redirected stdout Wrote normal output to [Link]
2> Redirected stderr Wrote error message to [Link]
cat [Link]
cat [Link]
Shows:
WEEK 3 16
ls: cannot access '/blah': No such file or directory
❌ → goes to
stderr [Link]
Or append instead:
WEEK 3 17
This diagram explains how the input redirection operator < works in
Linux/Unix shells.
✅ Syntax:
command < file1
Output (normal)
stdout 1 Goes to screen
stream
stderr 2 Error stream Goes to screen
5
10
15
Run:
cat file1
Because cat reads input from stdin , and we redirected stdin from file1 .
WEEK 3 18
🧠 Why Use < Instead of Just Giving the File?
While most commands (like cat , sort , wc , etc.) can take a file name
directly, < file1 becomes very useful in:
Shell scripting
Input testing (for commands that only read from stdin, not files)
Never alters it
In the lecture —
wc /etc/profile
The output:
27 97 581 /etc/profile
This shows:
27 lines
97 words
581 bytes
from /etc/profile
👇 Next:
wc [Link]
Output:
WEEK 3 19
5 35 327 [Link]
That means:
5 lines
35 words
327 bytes
inside [Link]
Output:
5 35 327
Notice:
It gives the same line/word/byte count, but does not print the
filename.
WEEK 3 20
This image explains how input/output redirection works in a Unix/Linux
shell (like Bash), specifically for the command:
: Redirects stdout ( 1 ) to
> file1 file1 . This means normal output is
written to file1 .
WEEK 3 21
➡️ So both normal output and error messages will go to file1 .
📁 Final Effect
Input: Comes from keyboard (stdin)
Both the error message and any output (if any) will go to [Link] .
🧪 Example Command:
(ls /etc/passwd /notfound) > [Link] 2>&1
🔍 Explanation:
ls /etc/passwd /notfound tries to list two files:
/etc/passwd ✅ (stdout)
— this exists
WEEK 3 22
ls: cannot access '/notfound': No such file or directory
🧠 What it does:
ls $HOME /blah : Lists contents of two directories:
WEEK 3 23
The image you're looking at illustrates how pipes ( | ) work in the
Unix/Linux shell.
🔧 Syntax:
command1 | command2
Its stdout (1) — the normal output — is piped into the stdin (0) of
command2 .
It reads from stdin (0) — which now comes from command1 's stdout.
It produces its own stdout (1) and stderr (2) — both go to your
screen/terminal.
WEEK 3 24
🧠 Key Concept:
Only stdout (1) from command1 is piped to command2 .
✅ Example:
ls /home | grep Documents
Only ls 's stdout is piped to grep . Any error from ls will appear on
screen directly.
Now both stdout and stderr from command1 are piped to command2 .
Let me know if you want examples with that or how to split output into
files.
WEEK 3 25
✅ 1. ls /usr/bin > file1
✅ 2. wc -l file1
wc = word count
l = line count
📄 In this case:
2596 file1
It means there are 2596 lines in the file file1 — each line represents one
file or directory entry from /usr/bin .
✅ 3. less file1
Opens file1 using the less viewer so you can scroll and view its
contents page by page.
Useful when the file has many lines (like 2596 here).
✅ 4. ls /usr/bin | wc -l
So it counts how many lines are output from ls , without saving them
in a file.
📄 Output:
2596
WEEK 3 26
💡 Summary:
Command What it Does
ls /usr/bin > file1 Saves list of files in /usr/bin to file1
wc -l file1 Counts how many files are listed (2596)
less file1 Opens the file in a scrollable viewer
ls /usr/bin | wc -l Counts files directly using a pipe (no file created)
This diagram explains how redirection and piping work together in the
shell command:
🧠 Conceptual Breakdown
🔹 command1 | command2
This is a pipe:
WEEK 3 27
🔹 > file1
🔹 stderr
The stderr (2) of both command1 and command2 are not redirected:
✅ Example:
ls /usr/bin | grep python > [Link]
What happens:
2. grep python filters only entries that contain the word python .
WEEK 3 28
thunder@thunder-VMware-Virtual-Platform:~$ more file1
1804
🧠 Step-by-Step Breakdown:
1. ls /usr/bin
Lists all files and directories inside /usr/bin (typically many commands
and utilities).
2. | wc -l
3. > file1
Redirects the final output (the line count) to a file named file1 .
Part Description
ls /usr/bin Lists files in /usr/bin
` wc -l`
> file1 Saves that count into file1
more file1 Displays the contents of file1 (which is 1804)
What is /dev/null ?
is a special file in Unix/Linux systems — often called the "bit
/dev/null
It’s a special device file that discards all data written to it.
It's used when you want to get rid of output (stdout or stderr).
WEEK 3 29
Discard both stdout and command > /dev/null Silent — no output at
stderr 2>&1 all
bash
Copy code
command > file1 2> /dev/null
Let’s break this down visually and conceptually using the image:
🟥 2> /dev/null
WEEK 3 30
That means any error messages produced by command are
completely discarded — sent to the "black hole".
The command will still take input from the keyboard (or a script),
unless redirected.
✅ Example in Practice
bash
Copy code
ls /usr/bin /notarealfile > [Link] 2> /dev/null
🧠 Summary
Component Purpose
> Redirect stdout
2> Redirect stderr
/dev/null Discards whatever is sent to it
file1 Will contain only normal output
WEEK 3 31
thunder@thunder-VMware-Virtual-Platform:~$ ls $HOME /blah
ls: cannot access '/blah': No such file or directory
/home/thunder:
[Link] Desktop file1 Music Pictures snap [Link]
billo Documents file2 mydir projects Templates Videos
clear Downloads level1 [Link] Public [Link]
thunder@thunder-VMware-Virtual-Platform:~$ ls $HOME /blah > file
1
ls: cannot access '/blah': No such file or directory
thunder@thunder-VMware-Virtual-Platform:~$ ls $HOME /blah > file
1 2> /dev/null
thunder@thunder-VMware-Virtual-Platform:~$ cat file1
🧪 Step-by-step Explanation
🔹 Command 1:
bash
Copy code
ls $HOME /blah
Result:
Terminal shows:
🔹 Command 2:
bash
Copy code
WEEK 3 32
ls $HOME /blah > file1
Terminal shows:
file1 contains:
🔹 Command 3:
ls $HOME /blah > file1 2> /dev/null
Result:
/home/thunder:
[Link]
billo
...
Videos
WEEK 3 33
ls $HOME /blah Screen Screen Yes
ls $HOME /blah > file1 file1 Screen Yes (error)
What is a tee ?
The tee command in Linux is a useful tool for both redirecting and
displaying output at the same time.
🧠 What is tee ?
1. Writes it to a file
So it's like a “T-junction” pipe: it splits the stream into two directions.
📌 Syntax:
command | tee filename
✅ Example:
ls /usr/bin | tee [Link]
The screen ✅
Saved in [Link] ✅
➕ With append:
ls /etc | tee -a [Link]
🔄 Multiple files:
WEEK 3 34
ls | tee file1 file2
Duplicates the output to both file1 and file2 and the screen.
📊 Use Case:
Without tee :
🔹 Output goes to both the file and the screen — you see and save it.
💡 Summary Table:
Feature > or >> tee
Writes to file ✅ ✅
Displays on screen ❌ ✅
Can append with -a ✅( >> ) ✅( tee -a )
WEEK 3 35
This diagram visually explains how the tee command works in the shell:
🔧 Command:
command1 | tee file1
It sends:
📊 Diagram Breakdown:
Stream Flow Path
WEEK 3 36
stdin (0) Input to command1
stdout (1) command1 → tee → written to file1 and displayed on screen
🧠 Summary
What tee Does Behavior
✅ Step-by-step Breakdown:
🔹 Command 1:
WEEK 3 37
ls $HOME | tee file1
To the screen ✅
To the file file1 ✅
Then:
cat file1
Confirms that file1 contains the same output that was displayed on your
terminal.
🔹 Command 2:
ls $HOME | tee file1 file2
file1 ✅
file2 ✅
And also displayed on screen ✅
Then:
cat file2
WEEK 3 38
Use -a if you want to append instead:
🧠 Summary
Command Effect
WEEK 3 39
⛔ Need for a Package Manager —
● Tools for installing, updating, removing, managing software
● Install new / updated software across network
● Package – File look up, both ways
● Database of packages on the system including versions
● Dependency checking
● Signature verification tools
● Tools for building packages
WEEK 3 40
amd64 | x86_64
i386 | x86
arm
Architecture used in smartphones, tablets, and Raspberry Pi.
Known for power efficiency, especially in mobile and embedded
systems.
ppc64el | OpenPOWER
WEEK 3 41
all | noarch | src
Python/Java).
packages.
dnf (Dandified YUM): Modern replacement for yum , faster and more
efficient, used in Fedora and newer Red Hat distributions.
WEEK 3 42
(Advanced Package Tool): High-level tool for handling .deb
apt
packages.
: Text-based
aptitude frontend for APT with a rich interface and
advanced features.
Inquiring package db —
1. apt-cache search keyword
This lists all available package names in the APT package database,
one per line.
It doesn't show descriptions—just the names, which is useful for
scripting or searching manually.
Running it without arguments lists all packages; with an argument, it
filters by prefix.
3. apt-cache show -a package
WEEK 3 43
It helps you understand what the package does and choose the right
version to install.
Package Priorities —
WEEK 3 44
Installed only when explicitly requested, often for advanced or niche
needs.)
WEEK 3 45
Architecture: all
Version: 1:1.99.1-7.3build1
Priority: optional
Section: universe/games
Source: fortune-mod
Origin: Ubuntu
🔹 md5sum — 128-bit
🔹 SHA1 — 160-bit
WEEK 3 46
Sometimes used for checksums but no longer secure for
authentication or signatures.
🔹 SHA256 — 256-bit
Part of the SHA-2 family; secure and recommended for file integrity
and digital signatures.
bash
CopyEdit
md5sum [Link]
→ 29c23bed0ea90bac9018c50dfa322e86
md5sum [Link]
→ 3c1c140a2fa5b08388d0b2682fd493d2
The two hashes are different, proving that even a small difference in
content changes the checksum.
4. Generated SHA256 hash:
WEEK 3 47
bash
CopyEdit
sha256sum [Link]
→ db2f8f1d6f1cc4e4ad74eb8e7a70ef98740048d392096b49109
01d3e2005b3fb
WEEK 3 48
⛔ Only sudoers can install/ upgrade/ remove packages
/etc/sudoers
In Linux systems, only users with sudo privileges (sudoers) are allowed
to install, upgrade, or remove packages. This protects the system from
unauthorized or accidental changes.
/etc/sudoers File
This is the configuration file that defines who can run commands as
root or other users using sudo .
/etc/apt
Files : [Link]
Folder : [Link].d
📁 /etc/apt/
This is the main file listing software repositories (URLs) where APT
looks for packages.
nginx
CopyEdit
deb [Link] focal main restricted
📂 [Link].d/ (Folder)
WEEK 3 49
Each file inside can define a separate third-party or PPA repository.
Example use:
swift
CopyEdit
/etc/apt/[Link].d/[Link]
It is safe to use, but you should always review the list of packages
before confirming.
apt-get update
apt-get upgrade
Install a package:
WEEK 3 50
apt-get install package
Reinstall a package:
apt-get autoremove
apt-get clean
Remove a package:
/var/lib/dpkg
Files : arch, available, status
Folder : info
3. status
📂 Folder: info/
Using dpkg —
📦 List all packages matching a pattern
dpkg -l pattern
Lists all packages with names matching the given pattern (supports
wildcards like ).
Shows all the files installed on the system by the specified package.
WEEK 3 52
dpkg -s package
This image explains how to install a .deb package manually using dpkg ,
and provides an important caution:
📦 Installing a .deb file
dpkg -i package_version-revision_architecture.deb
WEEK 3 53
i stands for install.
⚠️ Important Notes:
✅ Preferred method: Use or from trusted repositories
apt apt-get
using:
WEEK 3 54
⛔ coproc is a built-in keyword used to run a command asynchronously (in
the background) while allowing communication with it through file
descriptors — essentially setting up a lightweight, built-in way to interact
with a subprocess.
The command’s input and output are available via file descriptors.
WEEK 3 55
The default NAME is "COPROC".
Exit Status:
The coproc command returns an exit status of 0.
ps --forest
: Shows how much CPU time the process has used (very low
TIME
fg [%job_id]
%job_id refers to the job number (as listed by the jobs command).
sleep 60 &
WEEK 3 56
this starts sleep 60 in the background
jobs
Might show —
fg %1
This brings job 1 (sleep 60) to the foreground. Now the terminal waits for
it to complete or be interrupted.
Summary —
1. Job Control Basics
Job control allows you to manage multiple processes (jobs) in a terminal.
Commands:
WEEK 3 57
🔹 2. coproc (Co-process)
Purpose:
Runs a command asynchronously while allowing input/output
communication via file descriptors.
Syntax:
Key Points:
🔹 3. Process Hierarchy
ps --forest
🔹 4. Process Management
To kill a foreground process: Ctrl+C
To list processes:
WEEK 3 58
ps -e — Show all processes
Flag Meaning
h hash all (remember command paths)
i interactive shell
m job control
B brace expansion
H history expansion ( ! )
s reading from standard input
$$ :
Gives the PID of the current shell.
$? :
Gives the exit code of the last command.
🔹 6. Exit Codes
Code Meaning
0 Success
1 General error / permission denied
2 Misuse of shell built-ins or syntax error
126 Command found but not executable
127 Command not found
130 Script terminated with Ctrl+C
137 Process killed by signal (e.g., kill -9 )
WEEK 3 59
Code Meaning
>255 Wrapped with modulo 256 (e.g., 300 → 44)
🔹 8. Brace Expansion
Allows generating sets of strings:
Examples:
echo {a..z}
echo {A..K}
echo {A,B}{1,2}
Outputs:
a b c ... z
A B C ... K
A1 A2 B1 B2
WEEK 3 60
Semicolon ; separates commands.
You’ll see fewer flags (e.g., hBc ) since it's not interactive.
🔹 11. Combining Commands with Logical Operators
cmd1 && cmd2 : Run cmd2 only if cmd1 succeeds (exit code 0)
cmd1 || cmd2 : Run cmd2 only if cmd1 fails (non-zero exit code)
kill -9 PID
Press q to quit.
WEEK 3 61
WEEK 4
Lecture 4.1 (Pattern Matching- 01)
WEEK 4 1
⛔ POSIX standard (Portable Operating System Interface) is a family of
standards specified by the IEEE to maintain compatibility between Unix-
like operating systems. POSIX defines a consistent API (Application
Programming Interface), command-line shells, and utility interfaces
Regex
● regex is a pattern template to filter text
● BRE : POSIX Basic Regular Expression engine
It is widely used in tools like grep , sed , awk , vi , perl , bash , etc.
🧩 Metacharacters Comparison
Feature BRE ERE
WEEK 4 2
Feature BRE ERE
WEEK 4 3
Language Regex Support
Python re module
WEEK 4 4
Scraping data from HTML or APIs
🎯 5. Practical Examples
Task Regex Pattern
✅ Summary
Benefit Explanation
Usage
✅ Basic Syntax:
grep 'pattern' filename
WEEK 4 5
Searches for lines matching the pattern in the specified file.
🔁 With Pipelines:
command | grep 'pattern'
Example:
Example:
WEEK 4 6
ERE allows more metacharacters without backslashes.
Examples:
📝 Summary Table:
Task BRE ERE
Match a or b a|b `a
Character Meaning
. Matches any single character except newline or null
WEEK 4 7
Quick example —
| Pattern | Meaning |
| -------- | ------------------------------------------ |
| `^Hi` | Lines that **start** with "Hi" |
| `end$` | Lines that **end** with "end" |
| `[a-z]` | Any lowercase letter |
| `[^0-9]` | Any **non-digit** character |
| `a*` | Zero or more `'a'` characters |
| `\.` | A literal period `.` (dot), not a wildcard |
Example
Character Meaning Matches
Pattern
WEEK 4 8
#Grouping \(\)
echo "hahaha" | grep 'ha\{2\}' # doesn't match (we need to gr
oup)
echo "hahaha" | grep 'h\(a\{2\}\)' # matches 'haa'
echo "hahaha" | grep '\(ha\)\{3\}' # matches 'hahaha' (ha 3 time
s)
#Grouping allows applying *, \{n,m\} to entire patterns like ha.
#In BRE, grouping must be escaped using \( and )\
Logical OR
` ` `cat
between patterns
WEEK 4 9
echo "google" | grep -E 'go+gle' # matches google
echo "color" | grep -E 'colou?r' # matches color
echo "dog" | grep -E 'cat|dog' # matches dog
Character Example
Matches Matches Example
Class Pattern
Lowercase letters ( a–
[:lower:] [[:lower:]] q, z
z)
Uppercase letters ( A–
[:upper:] [[:upper:]] M, T
Z)
Printable characters
[:print:] [[:print:]] #, A, 9
(including space)
Printable non-space
[:graph:] [[:graph:]] @, G, 4
characters
[:blank:] Space or tab only [[:blank:]] , \t
Any whitespace
[:space:] (space, tab, newline, [[:space:]] , \t , \n
etc.)
[:punct:] Punctuation symbols [[:punct:]] !, ., ?
WEEK 4 10
Character Example
Matches Matches Example
Class Pattern
Backreferences
● \1 through \9
● \n matches whatever was matched by nth
earlier paranthesized subexpression
● A line with two occurances of hello will be
matched using:
\(hello\).*\1
🔁 Backreferences in BRE
🔹 What Are Backreferences?
\1 to \9 refer to the 1st to 9th capturing group (i.e., patterns inside \
(...\) ).
They let you match repeated patterns within the same line.
🧪 Syntax:
Group: \(pattern\)
Backreference: \1 , \2 , ..., \9
WEEK 4 11
🔄 Example:
\(hello\).*\1
This matches:
✅ Example Matches:
hello there hello
say hello, again hello
❌ Non-Matches:
hello world
HELLO hello # case-sensitive
🔣 More Examples
1. Match repeated word (like word word ):
\([[:alpha:]]\+\)[[:space:]]\+\1
✅ Matches:
hello hello
test test
⚠️ Notes:
WEEK 4 12
Works in BRE (e.g. grep , sed ) with \(...\) and \1 .
✅ Try It in Practice:
echo "hello hello" | grep '\(hello\).*\1'
echo "test test" | grep '\([a-z]\+\) \1'
Character collation,
1️⃣ Highest [..] , [==] , [::] equivalence, and
[[:digit:]] → any
digit
classes
WEEK 4 13
Precedence Operator Description Example
2️⃣ \metachar
Escaped special
characters
\. matches a
literal dot .
3️⃣ []
Bracket expressions
for character sets
[aeiou] matches
any vowel
4️⃣ \( \) and \n
Grouping and
backreferences
\(ab\).*\1 matches
repeated "ab"
6️⃣ Concatenation
Implicit AND (patterns
next to each other)
ab matches "a"
followed by "b"
WEEK 4 14
It illustrates the operator precedence in POSIX ERE (Extended Regular
expressions) — which determines how regex patterns are evaluated
when multiple operators are present
Character collation,
1️⃣ Highest [..] , [==] , [::] equivalence, and
[[:digit:]] → any
digit
classes
Escaped special
2️⃣ \metachar characters (e.g., \. for \. matches .
literal dot)
3️⃣ []
Character classes /
bracket expressions
[a-z] matches
lowercase letters
Grouping (no
4️⃣ () backslashes needed in
(ab)+ matches
ab , abab , ...
ERE)
WEEK 4 15
Precedence Operator(s) Description Example
5️⃣ *, +, ? ,
{n,m}
Repetition operators
a+ = one or
more a s
Concatenation —
6️⃣ (implicit)
characters next to each
other must match in
abc matches
"abc"
sequence
7️⃣ ^, $
Anchors for line
beginning or end
^Hi$ matches
exactly "Hi"
8️⃣ Lowest ` `
Alternation
(logical OR)
Grouping \( \) ()
Alternation | `
WEEK 4 16
txt
ED229842 Raman Singh
thunder@thunder-VMware-Virtual-Platform:~$ grep 'Anu' [Link]
EE228905 Anu K. Jain
ED229902 Anupama Sridhar
thunder@thunder-VMware-Virtual-Platform:~$ grep 'Sa' [Link]
PH220895 Charles M. Sagayam
PH220841 Vel Sankaran
thunder@thunder-VMware-Virtual-Platform:~$ grep 'ai' [Link]
EE228905 Anu K. Jain
thunder@thunder-VMware-Virtual-Platform:~$ grep ri [Link]
ED229902 Anupama Sridhar
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep
'ai'
EE228905 Anu K. Jain
What is the difference between “ grep ri [Link] ” and “ grep ‘ri’ [Link] ”
unexpected results.
WEEK 4 17
Quotes ensure the entire string is passed as-is to grep .
WEEK 4 18
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep
'^M'
#^M → Match lines that start with "M"
M029024 Mary Kanchick
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep
'^E'
#^E → Match lines that start with "E"
ED229842 Raman Singh
EE228905 Anu K. Jain
ED229902 Anupama Sridhar
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep
'^e'
# ^e → Match lines starting with lowercase e
# No output, because no lines start with lowercase e (grep is case s
ensitive by default)
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep
-i '^e'
# -i → Ignore case ^e → Match lines that start with either e or E
ED229842 Raman Singh
EE228905 Anu K. Jain
ED229902 Anupama Sridhar
WEEK 4 19
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep
'am$'
# This matches "am" at the very end of the line.
PH220895 Charles M. Sagayam
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep
'an\b'
# Word ends with an.
ED229842 Raman Singh
PH220841 Vel Sankaran
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep
'an$'
# Matches only if the line ends in an.
PH220841 Vel Sankaran
WEEK 4 20
# \b = word boundary before S So it tries to match only if S is at the
start of a word
ED229842 Raman Singh
PH220895 Charles M. Sagayam
PH220841 Vel Sankaran
WEEK 4 21
CS22B904 Charles M. Sagayam
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep 'B9
0[123456789]'
#Match lines containing: B90 followed by 1–9 (excluding 0)
MM22B901 Mary Manickam
ED22B902 Raman Singh
ME22B903 Umair Ahmed
CS22B904 Charles M. Sagayam
EE22B905 Anu K. Jain
NA22B906 Anupama Sridhar
PH22B907 Vel Sankaran
WEEK 4 22
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep '\
(a.\)\{2\}'
#Match exactly 2 a. patterns anywhere
ED22B902 Raman Singh
CS22B904 Charles M. Sagayam
NA22B906 Anupama Sridhar
PH22B907 Vel Sankaran
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | grep '\
(a.\)\{2,3\}'
# Match 2 or 3 occurrences of a.
ED22B902 Raman Singh
CS22B904 Charles M. Sagayam
NA22B906 Anupama Sridhar
PH22B907 Vel Sankaran
WEEK 4 23
NA22B906 Anupama Sridhar
PH22B907 Vel Sankaran
WEEK 4 24
⛔ dpkg-query— It is used to query the debian package database. it’s helpful
for checking installed packages their versions, files, and status
dpkg-query -l # or dpkg -l
dpkg-query -L <package-name>
dpkg-query -W <package-name>
dpkg-query -S <filename>
dpkg-query -s <package-name>
thunder@thunder-VMware-Virtual-Platform:~$ dpkg-query -W -
f'${Section} ${(binary:Package)}\n' | egrep '.{4}$'
WEEK 4 25
#Match lines that end with exactly 4 characters, whatever they are.
#Specifically: match any line that ends with 4 characters total, not
#"a 4-character word".
thunder@thunder-VMware-Virtual-Platform:~$ dpkg-query -W -
f'${Section} ${(binary:Package)}\n' | egrep 'k.*'
#Matches any line that has the letter k followed by anything (.*)
#This will match as soon as it sees k anywhere in the line, regardless
#of where.
WEEK 4 26
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | gr
ep '[[:punct:]]'
#Match any line containing at least one punctuation character
hello : alphabetical stuff : 5g
l : start lower end upper : H
L : start upper and lower : h
5g : alpha numeric stuff : 42
42 : solution to everything :
: start with control C end with dot : .
, : start with comma end with equals : =
: start with blank end with control char :
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | gr
ep '^[[:punct:]]'
#Match lines that start with a punctuation character
, : start with comma end with equals : =
thunder@thunder-VMware-Virtual-Platform:~$ cat [Link] | gr
ep '[[:punct:]]$'
#Match lines that end with a punctuation character
42 : solution to everything :
: start with control C end with dot : .
, : start with comma end with equals : =
: start with blank end with control char :
WEEK 4 27
Pattern Meaning
'^[[:lower:]]' Line starts with lowercase letter
'[[:lower:]]$' Line ends with lowercase letter
'[[:upper:]]' Line contains at least one uppercase
'^[[:digit:]]' Line starts with digit
WEEK 4 28
Week 5
Slides 1 ($hell variables)
Week 5 1
⛔ echo
● $USERNAME
● $HOME
● $HOSTNAME
● $PWD
● $PATH
printenv, env, set
Variable Meaning
$USERNAME Your login/user name (often $USER )
$HOME Your home directory path ( /home/user )
$HOSTNAME Name of your machine on the network
$PWD Present Working Directory (current path)
Week 5 2
echo $PWD # /home/thunder/somefolder
echo $PATH # /usr/local/bin:/usr/bin:/bin:...
Command Description
printenv Prints only environment variables (used by programs)
env Similar to printenv ; shows variables for the current environment
echo $0 #bash
echo $$ #5507
echo $? #0
echo $- #himBHs
Process control
● Use of & to run a job in the background
● fg
Week 5 3
● coproc
● jobs
● top
● kill
echo $$
Command Purpose
& Run in background
jobs List background jobs
fg Bring job to foreground
coproc Start co-process
top Monitor system processes
kill Terminate a process
echo $$ Show shell’s PID
0 : success
1 : failure
2 : misuse
126 : command cannot be executed
127 : command not found
130 : processes killed using control+C
137 : processes killed using kill -9 <pid>
Flag Meaning
h hash: Hash commands to speed up lookup
B brace expansion is enabled (e.g., echo file{1,2} → file1 file2 )
i interactive shell (i.e., you’re typing commands directly)
m job control is enabled (background jobs, fg , bg , etc.)
H history substitution using ! (e.g., !! to repeat last cmd)
s Commands are being read from stdin (non-interactive shell)
c Commands are being read from a command string (via bash -c )
Lecture 5.1
Week 5 4
⛔ What is echo ?
The echo command in linux is used to display a line of text of the value of a
variable to the terminal
name="billo"
echo $name
#output
billo
echo -e "Line1\nLine2"
#output
Line1
Line2
Suppress newline
Sequence Meaning
\n Newline
\t Tab
\\ Backslash
Week 5 5
\” Double quote
Even though typed many spaces between hello and world bash treats all
consecutive spaces/tabs as one when passing arguments to a command.
You started with a double quote " but ended with a single quote ' .
The > prompt appears because the shell is waiting for you to finish the
string (i.e., close the starting double quote).
Week 5 6
It keeps reading input as part of that same string until you finally type a
matching " .
$HOME
Meaning — This stores the path to your home directory — where your
personal files and configurations are stored.
this is where land when you log in, and where things like Documents ,
Downloads , bashrc , ect are located.
$HOSTNAME
Meaning — This shows the name of your machine on a network (how it’s
defined)
Useful in networking and when using ssh or scripts running across multiple
machines.
Week 5 7
st $HOSTNAME
welcome to the host thunder-VMware-Virtual-Platform
$PWD
Meaning — This gives you the present working directory — the directory
you are currently in when you ran a command.
thunder@thunder-VMware-Virtual-Platform:~$ pwd
/home/thunder
thunder@thunder-VMware-Virtual-Platform:~$ $PWD
bash: /home/thunder: Is a directory
thunder@thunder-VMware-Virtual-Platform:~$ echo my working space
$PWD is cozy
my working space /home/thunder is cozy
$PATH
If you run python , the shell looks in these directories (in order) for an
executable named python .
You can even add custom directories to PATH if you want to run your own
scripts from anywhere.
Week 5 8
soumya@Soumyadip:~$ printenv USER
soumya
Scope: Shows everything the shell knows about — not just exported
variables
Shell functions
Special parameters
Can
Shows Shows
Temporarily Shows
Command Environment Local Shell
Set Vars for a Functions
Vars Vars
Command
printenv ✅ Yes ❌ No ❌ No ❌ No
env ✅ Yes ❌ No ✅ Yes ❌ No
set ✅ Yes ✅ Yes ❌ No ✅ Yes
printenv → to see/exported environment variables only.
set → to see everything in the current shell (env vars + shell vars +
functions).
Week 5 9
Special shell variables
Meaning —
soumya@Soumyadip:~$ echo $0
-bash
soumya@Soumyadip:~$ echo "Script name: $0"
Script name: -bash
soumya@Soumyadip:~$ echo $$
308
Meaning — shows whether the last command succeeded (0) or failed (non-
zero)
soumya@Soumyadip:~$ echo $?
0
soumya@Soumyadip:~$ cd billo
-bash: cd: billo: No such file or directory
soumya@Soumyadip:~$ echo $?
1
Week 5 10
0 —> success and non-zero ( 1 ) —> error code
soumya@Soumyadip:~$ echo $-
himBHs
Each letter represents a shell option (like h for hashing commands, i for
interactive shell)
Shell/program/script
$0 bash or ./[Link]
name
$$ PID of current shell 12345
Process Control — Process control commands help you manage programs that
are running on your system — whether they’re in the background, foreground
or even paused
Runs a command without locking your terminal so you can keep typing
other commands
if something takes a long time you don’t want to stare at the terminal
until it finishes
Week 5 11
here first you tell your shell to “run sleep 20 in the background” which gives
the output [1] 594 where
Brings a background job back into focus so you can interact with it
If you started a process in the background but now want to see its
output or stop it with ctrl+c
Week 5 12
soumya@Soumyadip:~$ cat <&"${COPROC[0]}"
Thu Aug 14 [Link] UTC 2025
[1]+ Done coproc COPROC date
soumya@Soumyadip:~$
Lists processes started in the current shell that are running in the
background or stopped
lets you see what’s still running or paused so you can fg or kill them.
example
jobs
[1]+ Running sleep 60 &
[2]- Stopped nano [Link]
Helps spot programs using too many resources so you can stop or
optimize them.
top
press q — quit
Week 5 13
top is a scrolling “task manager” for linux
fg → Bring to foreground
0 —> Success
ls /home
echo $? # prints 0
ls /nonexistent
echo $? # prints 1
Often used for general errors like wrong arguments, missing files etc.
cd
exit 2
Week 5 14
#Reason: Shell uses 2 to indicate incorrect usage of its internal comma
nds.
touch [Link]
./[Link]
echo $? # 126 (no execute permission)
#Reason: Permission issue or incompatible file type.
nosuchcommand
echo $? # 127
# Reason: Typo in command name or not installed.
sleep 30
# press Ctrl+C
echo $? # 130
Week 5 15
#Reason: Signal math — Bash exit codes for killed processes are 128 +
signal_number.
Any exit code ≥ 128 usually means the process was killed by a signal
Meaning: When you run a command, Bash stores the full path in a hash
table so it doesn’t have to search PATH every time. (Speeds up command
execution for repeated calls)
i — Interactive mode
example —
Week 5 16
echo test
!ec # runs the last command starting with 'ec'
Week 5 17
1. Variable name rules
❌ 1var=value → invalid
✅ var1=value → valid
3. Value types
today=$(date)
✅ myvar=”value string”
Week 5 18
❌ myvar=value string —> would be interpreted as two commands
Example
export myvar
Week 5 19
💡 Why export?
without export the variable only exists in the current shell session:
myvar="Hello"
bash -c 'echo $myvar' #output: (blank)
export myvar="Hello"
bash -c 'echo $myvar' #output: hello
1. echo $myvar
myvar="hello"
echo $myvar
#output -- hello
Week 5 20
2. echo ${myvar}
Works the same as $myvar but safer when your variable is next to other characters.
myvar="hello"
echo ${myvar}
#ouput -- hello
3. echo “${myvar}_something”
myvar="hello"
echo "${myvar}_something"
#output-- hello_something
Week 5 21
myvar="hello"
unset myvar
echo "$myvar"
myvar="hello"
myvar=
echo "$myvar"
#output -- (blank, but variable still exits)
1. [[ -v myvar ]] — here -v checks whether the variable myvar is set (exists in the shell),
regardless of whether its value is empty.
Week 5 22
2. echo $?
0 → success (true)
unset myvar
[[ -v myvar ]]; echo $? # myvar is not set → 1
myvar= # set but empty
[[ -v myvar ]]; echo $? # myvar exists → 0
myvar="hello"
[[ -v myvar ]]; echo $? # myvar exists → 0
If myvar is set (even if empty), this expands to "x" (or whatever you put instead
of x ).
Week 5 23
Case ${myvar+x} expands to -z test result Exit code from echo $?
unset myvar
[[ -z ${myvar+x} ]]; echo $? # 0 → not set
myvar=""
[[ -z ${myvar+x} ]]; echo $? # 1 → set (even if empty)
myvar="hello"
[[ -z ${myvar+x} ]]; echo $? # 1 → set
#example
soumya@Soumyadip:~$ hello=""
soumya@Soumyadip:~$ [[ -z ${hello+x} ]]; echo $?
1
soumya@Soumyadip:~$ [[ -z ${billo+x} ]]; echo $?
0
soumya@Soumyadip:~$
Week 5 24
${variable:-default_value} —
unset myvar
echo ${myvar:-"default"} # → default
myvar=""
echo ${myvar:-"default"} # → default
myvar="hello"
echo ${myvar:-"default"} # → hello
#example
soumya@Soumyadip:~$ billo=""
soumya@Soumyadip:~$ echo ${billo:-"hagu"}
hagu
soumya@Soumyadip:~$ echo ${billo:-"default"}
default
Week 5 25
— if
${myvar:="default"} myvar is unset (or empty in this case), Bash will set it to "default"
unset myvar
echo ${myvar:="hello"} # prints hello
echo $myvar # now it's actually set to hello
"${myvar:+default}" means:
myvar="something"
echo ${myvar:+"default"} # prints default
echo $myvar # still "something"
unset myvar
echo ${myvar:+"default"} # prints nothing
Week 5 26
${!prefix*} expands to all variable names starting with the given prefix.
Here, H is the prefix, so ${!H*} lists all variable names whose names begin with
H.
HELLO="hi"
HOME="/home/user"
HOSTNAME="my-pc"
PATH="/usr/bin" # won't match because it doesn't start with H
echo ${!H*}
#output -- HELLO HOME HOSTNAME
Week 5 27
echo ${#myvar} —
myvar="Hello"
echo ${#myvar} # 5
myvar=""
echo ${#myvar} # 0
#example
soumya@Soumyadip:~$ salt=""
soumya@Soumyadip:~$ echo ${salt:="namak"}
namak
soumya@Soumyadip:~$ echo $salt
namak
soumya@Soumyadip:~$ echo ${#salt}
5
Week 5 28
echo ${myvar:5:4 —
myvar="ABCDEFGHIJ"
echo ${myvar:5:4}
#output -- FGHI
salt="namak"
soumya@Soumyadip:~$ echo ${salt:2:3}
mak
Week 5 29
${myvar#pattern} → remove shortest match of pattern from the start of $myvar
myvar="abcabc123"
salt="namak"
soumya@Soumyadip:~$ echo ${salt#*a}
mak
soumya@Soumyadip:~$ echo ${salt##*a}
k
Week 5 30
echo ${myvar/pattern/string} # replace first match
echo ${myvar//pattern/string} # replace all matches
salt="namak namak"
echo ${salt/na/xx} # replaces first "na"
# xxmak namak
echo ${salt//na/xx} # replaces all "na"
# xxmak xxmak
Week 5 31
echo ${myvar/#pattern/string} # replace if pattern matches at the START
echo ${myvar/%pattern/string} # replace if pattern matches at the END
salt="namak"
Lowercasing:
Uppercasing
Week 5 32
${myvar^} # Change first character to uppercase
${myvar^^} # Change all characters to uppercase
word="HeLLo"
This image shows how to restrict variable value types in Bash using declare :
declare -l name
name="HELLO"
echo "$name" # hello
declare -u code
Week 5 33
code="abc"
echo "$code" # ABC
declare -i num
num="42"
echo "$num" # 42
num="hi"
echo "$num" #0
This image explains how to remove restrictions from variables in Bash using declare +
instead of declare - :
that restriction.
declare -l name
name="HELLO"
echo "$name" # hello
declare +l name
Week 5 34
name="HELLO"
echo "$name" # HELLO (restriction removed)
declare -a fruits
fruits=("apple" "banana" "cherry")
echo ${fruits[1]} # banana
echo ${#fruits[@]} # 3
fruits+=("date")
echo ${fruits[@]} # apple banana cherry date
Week 5 35
— -A specifies that
declare -A hash hash will be an associative array (keys are
strings, not just numbers).
unset 'hash["a"]' — Removes the element with key "a" from the array.
Syntax Meaning
declare -a arr Declare indexed array
arr[i]=value Assign value at index i
${arr[i]} Access element at index i
${#arr[@]} Number of elements in array
${arr[@]} All elements in array
${!arr[@]} All indices in array
unset 'arr[i]' Remove element at index i
Week 5 36
Week 6
Lecture 6.1
Common Options:
. – current directory
Week 6 1
size +10M – files larger than 10MB
This finds all log files and deletes them. is replaced by each file found.
Common Options:
x – extract files
v shows progress
make reads a file called Makefile to determine how to build or process files based
on rules
Structure of a Makefile:
Week 6 2
target: dependencies
command
Example
How It Works:
clean:
rm -f *.o app
#Run with
make clean
Week 6 3
-name Match filenames against a simple pattern (supports wildcards like * and
? )
-type
f → regular file
d → directory
l → symbolic link
c → character device
b → block device
find . -atime -3
#finds files accessed within the last 3 days
Week 6 4
Option Meaning Updates When… Typical Use
-atime Access Time File was read (opened) Find unused files
Modification
-mtime File content changes Find old or updated files
Time
complex patterns
Week 6 5
Term / Option What It Means Common Usage Example
Week 6 6
Does not compress by itself — just bundles.
2. gzip - Compression
Reduces disk usage, especially useful for tiny files that compress well.
Applications
Reduce Disk Usage Compression saves space, especially for text-heavy files.
Compression Tools
Tool Notes
compress /
Legacy Unix compression; rarely used today.
ncompress
Week 6 7
Tarballs — Package + Compress
Performance Trade-offs
Compression Speed
Format Memory Usage
Ratio (Compression/Decompression)
Lecture 6.2
Week 6 8
1. Do one thing well
5. Don’t Be Chatty
Week 6 9
Example: wc -l [Link] returns just the line count.
Example: sort takes plain text and outputs plain text — easy to feed into uniq ,
head , etc.
Example: make delegates compilation to gcc ; tar uses gzip for compression.
Example: diff and patch are specialized tools for comparing and applying
changes.
Week 6 10
Element Purpose Quick Example
Human-readable
notes ignored by
# comments the interpreter; # This script backs up my files
useful for
documentation.
The actual
instructions or
Commands ls -l /home
operations to
perform.
Repeat a block of
Loops code for multiple for file in *.txt; do echo "$file"; done
items or conditions.
Branching logic to
Case handle multiple
case $day in Mon) echo "Start of week";; esac
statements specific cases
cleanly.
Group reusable
Functions code blocks under a greet(){ echo "Hello $1"; }
single name.
Choosing an interpreter
Processes,
Shell Orchestrating commands, Quoting, error
pipelines,
(sh/bash/zsh) file ops, simple glue handling, portability
ubiquity
Libraries,
Automation, data work, Startup time vs one-
Python readability,
APIs, cross-platform liners
testing
Week 6 11
Tool Sweet spot Strengths Watch-outs
Sourcing a Script
When you source a script, you’re not starting anything new — you’re inviting
that script to run inside your current shell session.
When to use
# [Link]
export PROJECT_HOME="$HOME/myproj"
cd "$PROJECT_HOME"
source [Link]
echo $PROJECT_HOME # still set
Week 6 12
pwd # still in the new directory
# [Link]
export TEMP_VAR=123
./[Link]
echo $TEMP_VAR # nothing printed, variable died with child process
Absolute path:
/home/soumya/scripts/[Link]
Relative path:
./[Link]
Week 6 13
Works if the script is in your current directory (you need ./ because . isn’t
usually in $PATH for safety).
commands:
echo $PATH
/usr/local/bin:/usr/bin:/bin:/home/soumya/bin
If your script is in one of these folders (and has execute permissions), you
can run it without specifying the path:
[Link]
The shell searches $PATH from left to right, so the first matching name
wins.
which [Link]
To override, either:
Week 6 14
A login shell is typically the first shell you get after logging into a system (via a
console, SSH, or display manager). It loads a set of startup files aimed at setting
up your full working environment.
Load order (first file found in each step stops that step’s search):
~/.bash_login
~/.profile
A non-login shell is usually any shell you start inside an existing session — for
example, opening a new terminal tab, or running bash inside a terminal.
Week 6 15
Key Differences
Portability
⚠ Can behave differently in POSIX vs
Bash
✅ Consistent across shells
Newline Auto (unless -n ) Only if you explicitly \n
%d / %i Integer (decimal) 42
%o Integer in octal 52
%c Single character A
Week 6 16
read var
read— prompts the shell to accept input from standard input (keyboard,
unless redirected).
Whatever the user types (until Enter) becomes the value of $var .
Week 6 17
What Is Command Substitution?
It means: “Run this command, take its output, and use it as a value.”
var='command'
Week 6 18
var=$(command)
user=$(whoami)
echo "Logged in as: $user"
How it works —
[Link] shell assigns each value in list to variable var , one at a time.
2. For each value, the commands inside do ... done run once.
Week 6 19
#I like mango
#I like banana
How it works:
3. ;; tells the shell “stop checking further patterns” and move on.
file="[Link]"
case $file in
*.txt)
echo "Plain text file"
;;
*.pdf)
echo "PDF document"
;;
*.jpg|*.png)
echo "Image file"
;;
Week 6 20
*)
echo "Unknown file type"
;;
esac
#output -- PDF document
case $action in
start)
echo "Starting service..."
;;
stop)
echo "Stopping service..."
;;
restart)
echo "Restarting service..."
;;
*)
echo "Unknown option: $action"
;;
esac
Week 6 21
here first orange one is Multi-line style and then the next one is Compact style
How It Works
If the command returns exit status 0 (success), the then block runs.
Week 6 22
1. test Expression — test -e file
Equivalent to [ -e file ] .
POSIX-compliant.
Bash-specific.
Arithmetic evaluation.
Week 6 23
Combines commands.
Summary Table
Week 6 24
Week 6 25
How it works
1. Evaluate condition
Week 6 26
2. After running the commands, go back to step 1.
How it works —
Week 6 27
#Wait for a file to exist
until [ -f "[Link]" ]
do
echo "Still waiting for [Link]..."
sleep 3
done
echo "File found!"
Step-by-Step Flow
Define the function — give it a descriptive name and put your command
sequence inside.
Call the function — the shell jumps into its code, runs each command in order.
Return to caller — once complete, control goes back to where you left off.
#A greeting function
say_hello() {
Week 6 28
echo "Hello, $1!"
}
say_hello "Soumyadip"
Week 6 29
Week 7
Every command (and its expanded arguments) will be printed to stderr before
execution.
bash -x ./[Link]
Same effect as set -x , but applied from the outside — no code changes needed.
Week 7 1
1. Logical AND ( && )
2. Logical OR ( || )
[ $a -lt 3 ] || [ $a -gt 7 ]
Week 7 2
Quick Comparison
Week 7 3
for the left one
a = 2.5, b = 3.2, c=4
scale = 5
($a+$b)^$C #(2.5+3.2)^4 -- 1055.6001
Week 7 4
How it works
The first true condition executes its block, and the rest are skipped.
Week 7 5
Components
case $var in : Begins the case block, testing the value of $var .
case $fruit in
apple)
echo "Red and crunchy.";;
banana | mango)
echo "Sweet and tropical.";;
orange | lemon | lime)
echo "Citrusy goodness.";;
*)
echo "Unknown fruit.";;
esac
Week 7 6
Components
a = $begin : Initialization
a++ : Increment
1
2
3
...
9
Week 7 7
Components
1 10
29
38
47
56
65
74
83
92
Week 7 8
: Creates a temporary file using the current process ID ( $$ ) to
filename=tmp.$$
ensure uniqueness.
> $filename : Redirects all output from the loop to the file.
Week 7 9
while [ $i -lt $n ] : Loop runs while i is less than 10 .
(( i++ )) : Increments i .
0
1
2
3
4
Week 7 10
Outer loop: while [ $i -lt $n ]
The outer loop prints i , and the inner loop prints numbers from 0 to i .
When j reaches 7 , break 2 exits both loops, halting the entire script
Week 7 11
: Skips printing when
continue j is between 4 and 5 (i.e., 4 and 5 are
skipped)
j=4 and j=5 are skipped in every loop due to the continue condition.
What it does
$2 becomes $1
$3 becomes $2
Week 7 12
What exec really do?
the shell process you were in is gone. It's replaced in memory by the new
program. No new process is spawned — the PID stays the same — and if the
program ends, there’s no shell to “return” to.
This doesn't replace the shell; it just changes where the shell's standard
output goes (here, to [Link] ) for the rest of that shell session or script.
Week 7 13
Argument joining → It concatenates all arguments into a single string.
Re-parsing → That string is then fed back into the shell for execution.
Exit status → You get the return code of whatever that executed command
produced.
step by step
a → flag, no argument.
On each loop, getopts grabs the next option from the command line and:
Week 7 14
1. echo select a middle one
2. select i in {1..10}
Bash automatically prompts with #? and waits for the user to type a choice
number (not the value itself).
3. do ... done
1, 2, 3 → “small one”
8, 9, 10 → “big one”
5. break
Week 7 15
Week 7 16
Week 8
Automating Scripts
Tool Purpose
at Run a job once at a specific time.
crontab Edit, list, or remove your personal cron jobs.
Like cron, but ensures jobs run even if the system was off
anacron
at the scheduled time (good for laptops).
Week 8 1
Cron jobs use five time fields before the command:
Week 8 2
These contain scripts that start or stop system services.
In the classic SysV init system, /etc/init.d/ holds the actual service control
scripts (start, stop, restart).
With newer upstart or systemd , /etc/init/ or /lib/systemd/system/ may take over, but the
concept is similar.
Week 8 3
When sed processes data, it works in cycles — one per input line — and
maintains two key buffers:
Buffer Purpose
An auxiliary buffer where you can store data for later use.
Hold space Content here survives between cycles until you explicitly
swap or append to/from it.
Read → sed reads one line from the input stream into the pattern space.
Execute → It runs through your script from top to bottom, checking each
command’s address pattern.
Output → Unless the n option is used, the (possibly modified) pattern space
is printed.
Repeat → Load the next line, pattern space is overwritten, hold space remains
unchanged unless you modify it.
Week 8 4
Inline command mode —
sed -e 's/hello/world/g' [Link]
Week 8 5
Here, -e introduces the editing script directly on the command line. The
s/hello/world/g command replaces all occurrences of “hello” with “world” in each
line of [Link] .
The -f flag tells sed to read its editing commands from a file ( [Link] in this
case).
Week 8 6
Component Purpose & Notes Example
1. It checks the address pattern — if the current line matches, the action is
executed.
#!/usr/bin/sed -f
# Label for looping
:again
/^#/d # Delete comment lines
/ERROR/{
s/ERROR/WARNING/g
t again # If substitution happened, jump back to :again
}
Grouping commands
{ cmd; cmd; }
How it works
Week 8 7
This grouping is useful when you want multiple edits to apply to the same
match before the next line is read.
If it matches:
Select by numbers
These operate purely on line positions:
Week 8 8
Selecting by text
Uses regular expressions wrapped in slashes:
/regexp/ → matches any line whose text matches the given pattern
Range Addresses
Target continuous spans of lines:
(inclusive)
extension)
Week 8 9
Week 8 10
Week 9
AWK — A language for processing fields and
records
Pattern → decides when a block runs (can be regex, range, expression, or omitted)
Input as Records
Week 9 1
awk sees your input as a stream of records.
By default:
You can change RS to split on other delimiters (e.g., blank lines, a comma, even a regex).
Records as Fields
By default:
Fields are accessed with $1 , $2 , …, $NF (last field), where NF is the number of fields in
the current record.
Pattern-Action Cycle
BEGIN { ... } → runs before any records are processed (good for headers, setup).
END { ... } → runs after all records are processed (good for summaries, totals).
Week 9 2
cat /etc/passwd | awk -F":" '{ print $1 }'
cat /etc/passwd | ... feeds the file into awk via a pipe — though you could skip cat and just do:
Week 9 3
1. Pattern half
Think of patterns as awk ’s gatekeepers. They decide whether the procedure block should
run for a given line.
BEGIN → special block that runs once before reading input (good for setup like FS=":" ).
END → runs once after all input is processed (great for summaries/totals).
General expression → any condition that evaluates to true/false, e.g. $3 > 1000 .
Regex → matches text patterns, e.g. /bash$/ for login shells ending in bash .
💡 If there’s no pattern, awk just runs the procedure for every record.
2. Procedure Half
Once a pattern allows a record through, the procedure defines the action.
Week 9 4
Built-in functions → length($1) , toupper($2) , split() .
Can appear
Setup: set FS ,
Once, before anywhere in
initialize
BEGIN { ... } reading any the script; runs
counters, print
input before the first
headers
record
Week 9 5
If pattern matches, run its associated commands.
1. Assignment Operators
2. Logical Opertor
3. Algebraic Operators
^ or * — exponentiation.
[Link] Operator
> , < , >= , <= , == , !=
Week 9 6
Week 9 7
Associative → indexes (keys) don’t have to be numbers — they can be strings like "root" or
"bash" .
Sparse storage → only stores elements you actually assign; no fixed size, no wasted
memory for unused indices.
Dynamic typing → keys and values can be assigned on the fly without declarations.
Iterate for (u in arr) print u, arr[u] Loops over all keys (unordered).
Count count[$7]++ Tally how many times a value (e.g., shell path) appears.
Week 9 8
Type Syntax Example Purpose in awk scripts
Counter loop for (i=1; i<n; i++) { print i } Classic index‑based iteration for numeric ranges.
Can call built‑in functions (like rand() ) or use $n fields from the current record.
Week 9 9
Control letter Meaning Example output
%c ASCII character printf "%c", 65 → A
%d / %i Integer (decimal) 42
%s String "hello"
%x / %X Hexadecimal (lower/upper) 2a / 2A
printf "format", a, b, c
#"format" → a string containing format specifiers (placeholders)
#a, b, c → values to insert in order into those placeholders
width → minimum field width: %10s (pads left with spaces to width 10)
bash + awk
● Including awk inside shell script
● heredoc feature
● Use with other shell scripts on command line
using pipe
Week 9 10
AWK
awk '{ print NR ": " $0 }' [Link] = Print Line nos.
> awk '{print $1 + $2}' [Link] = Print sum of fields for each line.
-> awk '{print "Total row sum: " $1 + $2}' [Link] = Concatenate.
-> awk '$1!~/^-/ {print $1+$2}' [Link] = takes lines whose 1st field is +ve.
awk '{sum += $1+$2; print "Running total= " sum}' [Link] = Running total, last print will be
total sum.
> awk 'BEGIN { sum=0 } { sum += $1 + $2 } END { print "Grand Total: " sum }' [Link] =
Prints the complete total at the end
> awk '{ if ($1 % 2 == 0) print $1 " even"; else print $1 " odd" }' [Link] = Prints num at 1st
field and even/odd.
Week 9 11
> Loops: While, For, Do-While
For: for (i=1 (init), i<=NF (stop condition), i++ (increment/decrement) {print $i} (action)) =
loops through fields
eg: awk '{ for (i=NF; i>=1; i--) printf "%s ", $i; printf "\n" }' [Link] = prints fields backwards
(uses C-syntax, cuz simple {print $i} will print fields one by one on seperate lines).
Level 6: Arrays
Access: array[index]
awk '{ count[$1]++ } END { for (fruit in count) print fruit ": " count[fruit] }' [Link] = how
many times each fruit appears at the beginning (1st field).
awk '{ for (i=1; i<=NF; i++) count[$i]++ } END { for (fruit in count) print fruit ": " count[fruit] }'
[Link] = count of each fruit.
Level 7: Functions
awk 'function add(a,b) { return a+b } { print add($1, $2) }' [Link] = prints sum of 1st and 2nd
field for each line.
length(string) = Lenght ; toupper(str) = Uppercase ; split(str, arr, sep) = Split into array
echo "a,b,c" | awk '{ split($0, arr, ","); print arr[3] }' = split into array, seperated by commas,
print 3rd entry (indexing starts from 1).
awk 'BEGIN { FS="," } NR > 1 { print $1 " is " $2 " years old" }' [Link] = Print 'name' is 'age'
years old for every line, staarting from 2nd line.
#!/bin/bash
BEGIN { print "Starting fruit count" }
{ for (i=1;i<=NF;i++) counts[$i]++ }
END {
for (f in counts) {
Week 9 12
if (counts[f] > 1) {print f " appears " counts[f] " times."}
}
print "Done!"
}
= prints 'fruits' and how many times they appear for all such fruits appearing >1 times.
Week 9 13
Week 10
Lecture 10.1 (Version Control)
“Make” —> compile only those parts of code that have changed
Week 10 1
⛔ clinfo
Clock frequency
Memory sizes
Global memory
Local memory
Constant memory
Options
Week 10 2
--human — produces readable output
⛔ coreutils
⛔ dmidecode
Week 10 3
⛔ fdisk
⛔ hardinfo
⛔ hdparm
Week 10 4
⛔ hwinfo
⛔ memtester
Use case: Detect bad memory (like memtest86+, but runs inside a
running OS).
⛔ net-tools
Includes commands:
⛔ pciutils
Week 10 5
⛔ procps
Includes commands:
ps → list processes
⛔ sysstat
Includes commands:
Week 10 6
⛔ upower
⛔ util-linux
Managing Storage
Week 10 7
⛔ LVM (Logical Volume Manager)
PV (Physical Volume)
Actual storage devices (e.g., /dev/sda1 , /dev/nvme0n1p2 ) initialized for
use by LVM.
VG (Volume Group)
A pool of storage created by combining one or more PVs. Think of it
as a "storage container.”
LV (Logical Volume)
Virtual partitions created from a VG. These act like "logical disks"
that you can format and mount (e.g., /home , /var ).
Week 10 8
lvcreate -L 10G -n my_lv my_vg
# 5. Mount it
mount /dev/my_vg/my_lv /mnt
Week 10 9
RAID (Redundant Arrays of Independent Disks)
Hardware RAID
Software Raid
RAID 0 – Striping
Needs ≥ 3 disks.
Needs ≥ 4 disks.
Needs ≥ 4 disks.
Week 10 11
Prompt Strings
Week 10 12
Context for prompt strings
● bash, dash, zsh, ksh, csh
● python
● octave
● gnuplot
● sage
Bash Prompts
● PS1 : primary prompt string : $
● PS2 : secondary prompt for multi-line input : >
● PS3 : prompt string in select loops : #?
● PS4 : prompt srting for execution trace : +
Week 10 13