Operating System Lab Lecture Notes
Operating System Lab Lecture Notes
Page 1/130
قل لي وسوف أنسى
أرني وربما أتذكر
أشركني وسوف أفهم
كونفوشيوس
Page 2/130
Table of Contents
1 Introduction.............................................................................................................................4
2 File hierarchy and essential commands................................................................................18
3 Permissions and user management.......................................................................................36
4 File system and mounting.....................................................................................................47
5 Input/output redirection and piping......................................................................................58
6 Process control and system startup.......................................................................................66
7 Introduction to shell (Bash) scripting...................................................................................77
8 Text processing.....................................................................................................................95
9 Networking..........................................................................................................................111
10 Extra topics.........................................................................................................................125
Page 3/130
1 Introduction
Page 4/130
Unix history
✔ The development began in 1960’s under the name Multics.
✔ First Version was created in Bell Labs in 1969 by Ken Thompson and Dennis Ritchie, and
it was named Unics.
✔ Unix was entirely written in C language.
✔ In 1980’s, AT&T Bell Labs implemented commercial license on Unix distribution and the
first version System V was commercialized.
✔ The University of California, Berkeley, continued the development of its own version of
Unix, called BSD (Berkely Software Distribution).
✔ Through 1980’s and 90’s, many companies commercialized and licensed their own
versions of Unix.
✔ In early 1990’s, AT&T sold all their rights including its further development to Novell.
✔ In 1995, Novell sold all their rights including its further development to SCO (Santa Cruz
Operation).
✔ In 2005, Sun Microsystems released the majority of its code with Open Solaris BSD
continued its development and released free version of Unix, called FreeBSD.
Page 5/130
Unics
1969 1969
Open Source
UnixTSS
1971 to 1973 1 to 4 1971 to 1973
Mixed/Shared Source
UnixTSS
1974 to 1975 5 to 6 PWB/Unix 1974 to 1975
Closed Source
Page 6/130
Unix philosophy and advantages
✔ Unix was designed to operate multi-user computers and mainframes.
✔ It is mainly characterized by its security and high performance.
✔ Unix philosophy:
▸ A program does one thing and does it well.
▸ The output of a program can become the input of another (piping).
▸ Focus on text to interchange information between programs and storing configuration.
▸ Everything is a file.
Page 7/130
Richard Stallman and the GNU project
✔ Stallman launched the GNU Project in 1983 to write a
Unix-like computer operating system composed entirely of
free software.
✔ GNU stands for GNU is Not Unix
✔ He also founded the Free Software Foundation (FSF) in
1985, and founded the GNU Public License (GPL) under
which GNU software is distributed.
✔ GNU projects provides many free (open-source)
applications and utilities, such as GNU Compiler Collection (GCC), GNU Debugger,
GNU Emacs text editor, Gnome desktop environment, and many essential libraries and
utilities used mainly in Linux distributions.
Page 8/130
Linus Torvalds and the Linux kernel
✔ Linus Torvalds creator the Linux kernel in 1991, when he was a
21-year-old student at the University of Helsinki. He published the
Linux kernel under the GPL license. At this time the GNU project
was developing its own kernel, called GNU Herd; however its
development was slow and Linux kernel got the developer
attention worldwide.
✔ He also created the distributed version control system Git.
✔ Linux kernel is mainly used by Linux-based distribution, supercomputers, Raspberry Pi,
and many embedded systems such as smart TVs, networking equipment, machine control,
industrial automation, navigation equipment, spacecraft flight software, medical
instruments, etc. Android is also based on Linux.
✔ Linux runs most of the internet and it is very popular in scientific research and security.
✔ Linux use in personal computer is increasing.
Page 9/130
Open-source
✔ Open-source software has an open license that gives the user
the freedom to use, modify, and share, the source code of the
program without any financial or legal difficulties.
✔ Some open licenses (like GPL) requires that if the software is
modified and published publicly, then the modifications must
be available under the same license. R
Page 10/130
Linux is just a kernel
✔ The operating system kernel is responsible for managing hardware and computer resources
requested by the applications.
✔ Linux is just a kernel.
Page 11/130
Linux distributions
✔ A Linux distribution (or distro) is a collection of open-source utilities and applications
built around the Linux kernel and presented to the user in a usable form.
✔ Usually, distributions are provided to the users as an installable ISO file that can be run
directly from a flash memory.
✔ Open-source applications are collected, compiled, and stored on servers, called
repositories, in a form of packages.
✔ Packages are compressed files and include scripts and information that help controlling
installation and dependency.
▸ Examples: Debian (deb) and RPM packages.
✔ A package manager is used to control the package installation process.
▸ Example: APT package manager for Debian distribution and its derivatives like
Ubuntu.
✔ Fixed-release distributions (such as Debian, Ubuntu, and Fedora), are released at a certain
date, and the included software are not updated until the next release, except for security
and maintenance updates.
Page 12/130
✔ Rolling-release distributions
(such as Arch and Manjaro)
are continuously updated so
that the latest software
version is provided in the
package repositories;
however, they are less stable
compared to fixed-release
distros.
✔ There are main distributions
(like Debian, Arch, Fedora,
Slackware) and they are used
as a base for other derived
distros (for example Ubuntu
is derived from Debian).
Derived distros has many
similarities with their base
distros.
Page 13/130
Linux advantages
✔ Based on Unix design and philosophy, and it complies with POSIX (Portable Operating
System Interface) standards for Unix and Unix-like operating systems.
✔ Secure and not prone to viruses like windows.
✔ Stable and lightweight, and can be run on older PCs.
✔ Can run completely from CLI (Command Line Interface) with
out GUI (Graphical User Interface) and that saves memory and
processing power.
✔ Highly customizable.
✔ Quieter fan and longer battery life.
✔ Free and open-source.
✔ Easy to get and install.
✔ Ability to run it completely from a USB memory.
✔ Many distros and desktop environments to select from.
Page 14/130
Ubuntu distribution and its flavors
✔ Established in 2004 and it is based on Debian distribution.
✔ Has new release every 6 months, in April and October. Each release is supported for 9
months, except for Long Term Support (LTS) releases which are supported for 5 years.
LTS releases are released in April each even-numbered year. For example 20.04 and 22.04
are LTS releases.
✔ Ubuntu has many flavors that have the same software repositories of Ubuntu but differs in
their desktop environment, some of them are listed below:
▸ Ubuntu: Gnome desktop environment.
▸ Kubuntu: KDE Plasma desktop environment.
▸ Xubuntu: XFCE desktop environment.
▸ Many other flavors.
Page 15/130
The distro to be used for this lab
✔ A modified version of Kubuntu 22.04 is chosen to be used in this lab.
✔ Kubuntu disro combines the power of Ubuntu and KDE plasma desktop environment.
✔ KDE plasma is will known for its powerful applications and customization, and it has a
look and feel similar to Windows.
✔ Link for the distro ISO file:
https://bit.ly/mykubuntu
Page 16/130
Practical tasks
✔ Watch "Revolution OS" documentary, which talks about Linux and open source history.
✔ Watch the following video that describes why Windows is prone to viruses.
▸ https://www.youtube.com/watch?v=E9qb24SQe1o
✔ Join the following Facebook group that has many videos about Linux.
▸ www.facebook.com/groups/ahu.linux
✔ Download the selected distro from the link below:
▸ https://bit.ly/mykubuntu
✔ Use Ventoy application (www.ventoy.net) to install the ISO file on a USB memory.
✔ Boot the distro directly from the USB memory.
✔ Navigate through the KDE plasma desktop environment and its applications and tools, like
Dolphin file browser, Konsole terminal, Kate text editor, etc.
Page 17/130
2 File hierarchy and essential commands
Page 18/130
File hierarchy
Linux has a single file hierarchy. Forward slash (/) is used to separate directories, as follows:
/ Root directory
/boot Boot loader files, e.g., kernels, initrd.
/dev Device files, such as storage drives and partitions (sda, sda1, sda2, sdb, etc).
/etc System-wide configuration files.
/home Users’ home directories, containing personal files and configuration.
/lib, /lib32, /lib64 System libraries.
/media Mount points for removable media.
/mnt Temporarily mounted filesystems.
/opt Optional application software packages.
/bin, /sbin Essential system executable binaries (i.e. programs).
/tmp Temporary files. Often not preserved between system reboots.
/usr Secondary hierarchy for read-only user data; contains the majority of
(multi-)user utilities and applications.
/proc Virtual filesystem providing process and kernel information as files.
/var Variable files whose content is expected to continually change during normal
operation of the system, such as logs, databases.
Page 19/130
Special directory symbols
Symbol Directory
~ User home, i.e. personal, directory. For example /home/ahmad/
. Current directory
.. Parent directory
Page 20/130
Command structure
Page 21/130
Notes
✔ Multiple commands can be separated with semicolon ( ; ). The execution of the next
command starts after finishing the previous one.
command 1; command 2; command 3
✔ Use backward slash ( \ ) at the end of a line to continue a command on the next line.
Remember to put space before \.
beginning of a command \
next part of the command \
next part of the command \
end of the command
Page 22/130
cd command
✔ Used to change the current directory.
✔ Examples
cd Go to user's home directory
cd /var Go to /var directory
cd ~/Desktop Go to Desktop directory, which is inside user's home directory
cd .. Go to parent directory
cd - Go to previous directory
✔ Remember: Linux is case-sensitive, so the commands CD /var, cd /VAR, cd /Var will give
you an error.
Page 23/130
ls command
✔ Used to list files
✔ Examples
ls List files in current directory
ls /dev List files in /dev/ directory
ls -l List files details
ls -a List hidden files that start with a dot ( . )
ls -lh Use -h option to list file size in human-readable format
ls ~/Desktop -ld Use -d option to list directories, not their contents.
Page 24/130
TAB key and wildcard matching
✔ When typing in the Linux command line, just press TAB to autocomplete commands,
filenames or directory names. If more than one option is available, press TAB two times to
show the available options.
✔ Wildcard matching:
▸ * Matches any group of characters.
▸ ? Matches a single character.
▸ [] Matches a range of characters.
ls /dev/sda* List all files in /dev/ directory that start with sda
ls /dev/sd?1 List files such as sda1, sdb1, sdc1
ls /dev/sda[1-3] List the files sda1, sda2, sda3
ls /dev/sd[ab]* List all files that start with sda or sdb
Page 25/130
mkdir and rmdir commands
Used to create (or remove) a directory, removed directory must be empty.
mkdir new_directory Create a directory named new_directory
rmdir new_directory Remove a directory named new_directory
mkdir -p ~/dir1/dir2/dir3 Create dir1 directory with its subdirectories in the user's home
ls -a List hidden files that starts with a dot ( . )
ls -lh List file size in human-readable format
Page 26/130
cp, mv, and rm commands
Used to copy, move, and remove files or directories
Copy file1.c and file2.c to mycode directory. If files exits in
cp file1.c file2.c mycode
the destination directory, they will be overwritten.
Copy all files that end with .c to ~/mycode directory and
cp -i *.c ~/mycode
check if the file exists.
Copy directory dir1 and its contents to directory dir2, -r
cp -r dir1 dir2
means recursive and must be used in this case.
rm file1.c Remove file1.c file.
rm -r dir1 Remove dir1 directory and all of its contents.
mv oldfile.c newfile.c Move (i.e. rename) oldfile.c to newfile.c
mv dir1 dir2 Move dir1 and all of its contents into dir2 directory.
Page 27/130
Quotes and escape characters
✔ Use single ( ' ) or double ( " ) quotes for file or directory names that contains spaces.
✔ Also escape character ( \ ) can be used with spaces.
Examples:
mkdir "new folder1"
mkdir 'new folder2'
mkdir new\ folder3
Page 28/130
More commands
pwd Print name of current/working directory
date Print or set the system date and time
clear Clear terminal
man command Manual pages for certain command. Press q to exit. Example: man ls
apropos keyword Search manual pages name and description, example: apropos date
which command Print command executable file location, example: which cp
touch filename Create empty file, example: touch newfile.txt
uname -a Print information about the kernel
lsb_release -a Print information about the distro
whoami Print username
hostname Print host (i.e. computer) name
echo text Display text on screen, example: echo "hello world"
cat files Concatenate files and print on screen, example: cat /etc/passwd
clear Clear terminal screen
file filename Show file type
alias Show command aliases
Page 29/130
Shell variables
✔ Some variables are declared by default when you run a terminal.
✔ To show variable value use the command echo $variable_name
✔ To declare a variable use the command variable_name=value
✔ Some variables:
$USER Current username. Example: mahmoud
$HOME Current user's home directory. Example: /home/mahmoud
$UID User ID
$HOSTNAME Host (i.e. computer) name
$PS1 Controls prompt appearance
✔ Examples:
echo "My home is $HOME" Using a variable. Use double quotations ( " ).
echo "My home is ${HOME}" Other way to use variable
MYTXT="Hello" Assign Hello string to MYTXT variable
Page 30/130
Single and double quotes
✔ When using a variable inside double quotes ( " ), its value will be substituted.
✔ Any text inside single quotes ( ' ) will be printed as it is.
Example: If your username is ahmad, the following commands will give the following output:
Page 31/130
Package management using apt
✔ Debian based distros use apt package manager and deb packages.
Update package index. It is good to run this command before
sudo apt update
installing packages, especially after new system installation.
sudo apt install packages Install a package or packages. Example: sudo apt install nmap
sudo apt install ./package Install local package
Remove a package or packages.
sudo apt remove packages
Example: sudo apt remove nmap
sudo apt purge packages Remove packages and their system-wide configuration files.
sudo apt remove packeges Remove packages and unneeded packages.
--auto-remove Example: sudo apt remove nmap --auto-remove
sudo apt autoremove Remove unneeded packages
sudo apt upgrade Upgrade all packages to the latest version.
Page 32/130
Cheat sheet
✔ Link:
https://cheatography.com/davechild/cheat-sheets/linux-command-line/
Page 33/130
Practical tasks
✔ Perform the following tasks inside the Desktop directory:
▸ Create the directories dir_x, dir_y, and new dir .
▸ Create two empty files code1.c and code2.c inside dir_x directory.
▸ Copy the contents of dir_x into dir_y .
▸ Copy the dir_x directory into dir_y .
▸ Rename new dir to new_dir .
▸ Delete dir_y directory and its contents.
▸ Use wildcards to delete all files inside dir_x directory that end with .c .
✔ Perform the following tasks:
▸ List all files and directories in /dev directory that start with tty .
▸ List all files and directories in /dev that consist of 3 letters.
Page 34/130
✔ Perform the following tasks:
▸ Use which command to locate the executable files for mkdir and kate programs.
▸ Use file command to show the file type for the executable files of mkdir and kate
programs.
▸ Use ldd command to show the libraries to which mkdir and kate executable files are
linked.
✔ Use history command to list previously entered commands?
✔ Display $HISTFILE variable to know where the previously used commands are stored.
✔ Shell variables:
▸ Define a variable called MYVAR and its value is "Hello world", then display it.
▸ Use shell variables to display the following, where username is your username.
▸ My username is username.
▸ My home directory is /home/username.
Page 35/130
3 Permissions and user management
Page 36/130
Introduction
✔ Everything is a file: In Unix-like operating systems, every source or destination of data is
represented as a file, whether it is a file on the disk or a piece of hardware that gives or
receives data. Directories are also treated as files.
✔ Device files: Computer devices are presented as files inside the directory /dev. For
example the first storage device is assigned the file /dev/sda, and its partitions are assigned
the files /dev/sda1, /dev/sda2, /dev/sda3, etc. These files should not be confused with
devices drivers.
✔ Groups: In addition to users, Unix-like operating systems support groups, where users are
assigned to groups to get permissions specific to these groups.
✔ Default group: Every user will be assigned to a default group with same name as its
username. For example, user ahmad will have will be assigned a default group called
ahmad.
✔ Root user: A number is assigned to each user and group. The user with the number 0 is
called root user. This use has unlimited permissions over the system. System files are
assigned to the root user.
Page 37/130
✔ Permissions: Linux is based on Unix operating system, which is a multi-user operating
system. This dictates to give users permissions to access files as needed in order to protect
the system from users and protect users' file, if wanted, from being accessed by other
users. There are three essential permissions, which are:
▸ Read (r): Read from a file or list the contents of a directory.
▸ Write (w): Modify the content of a file or creating/removing files and subdirectories
from a directory.
▸ Execute (x): Execute, i.e. run, a file or entering a directory.
✔ Permission levels: Each file is assigned an owner user and a group. There are three levels
for permissions, and each level has the basic three permissions. Permissions levels are:
▸ User (or owner): The owner of a file.
▸ Group : The users that are assigned to the group of the file.
▸ Others: other users in the system
Page 38/130
Illustration
Use cat or less commands to display files. Press q to quit less command. Examples: less /etc/passwd
Page 40/130
sudo command
✔ Short for Super-user do.
✔ By default, sudo command is used to execute other commands as root user. It also can be
used to execute command as another user using -u option.
✔ sudo command is used to make changes to files that are owned by the root user or perform
system administration, like changing system configuration files or installing packages.
✔ The user must be in sudo group to be able to use sudo command.
▸ Use groups command to see if you are in sudo group.
Page 41/130
Commands
id Print real and effective user and group IDs
su username Switch user, example: su user2
sudo adduser newuser Add new user, example: sudo adduser ahmad
groups username Show user groups, example: groups ahmad
sudo usermod -aG group Add a user to a group, exampe: usermod -aG group1 ahmad.
user User must log out and log in again to activate new group.
sudo deluser user group Remove user from a group, example: sudo deluser ahmad group1
Remove user account. Use -r option to remove user's home
sudo userdel user -r
directory. example: sudo userdel ahmad -r
sudo chown user:group Change owner and group. Use -R option to apply recursively on
files subdirectories. Example: sudo chown ahmad:ahmad mydir -R
exit exit user account or exit terminal
Page 42/130
chmod command
✔ User to modify permissions.
✔ Permission can be represented using binary numbers, as shown:
✔ Examples:
chmod 640 *.c Change permissions to rw- r-- --- to all files ending with .c
Apply execution permissions to all levels for all files and directories in
chmod a+x *
the current directory (a means all)
Remove execute and write permissions from group and other from the
chmod go-rw mydir -R
directory mydir and all of its contents. (-R means recursive)
Apply execute permission for user for the directory mydir and all of
chmod u+X mydir -R
its subdirectories. (X apply execute permission only to directories)
chmod u+r,g+x *.c Apply read permission to user and execute permission to group
Page 43/130
/etc/skel
✔ The directory /etc/skel/ (skel stands for skeleton) is used to initiate home directory when a
user is first created. When a new user is created, the contents of the /etc/skel directory is
copied to its home directory.
Page 44/130
Practical tasks
1. Add a new user named user2
2. Display the permissions of the home directory for user2
3. Open two terminal windows. In the second terminal switch to the user user2
4. In your terminal:
►Enter /home/user2 directory using cd /home/user2 command.
►List files in /home/user2 directory using ls /home/user2 -al command.
►Create the file /home/user2/file1.txt
5. From user2 terminal, change its home directory permissions to 754.
►Repeat step 4. What are the changes?
6. Add yourself to user2 group.
►Repeat step 4. What are the changes?
7. Logout and login again to activate joining the group.
►Repeat step 4. What are the changes?
Page 45/130
8. From user2 terminal, apply rwx permissions to the group on its home directory.
►Repeat step 4. What are the changes?
9. From user2 terminal, remove write permissions from the group on its home directory.
►Repeat step 4. What are the changes?
►Create the file /home/user2/file2.txt . What do you notice?
10. From user2 terminal, remove read permissions from the group on its home directory.
►Repeat step 4. What are the changes?
11. From user2 terminal, remove execute permissions from the group on its home directory.
►Repeat step 4. What are the changes?
12. Remove yourself from user2 group.
13. Delete user2 account, including its home directory.
Page 46/130
4 File system and mounting
Page 47/130
What is a file system
✔ A file system is the way data are stored on a storage device.
✔ Linux has many file systems that are designed for it and can't be accessed by defaults from
windows. Some of these file systems are: ext, ext2, ext3, ext4, JFS, XFX, btrfs, swap.
✔ Usually, ext4 file system is used for Linux partitions; however, other files systems can be
used for certain cases.
✔ Swap is a storage space that is used when the system runs low on memory.
✔ Linux also support file systems that are used by other operating systems, such as NTFS,
FAT32, and exFAT that are used by Windows.
Page 48/130
Mounting
✔ In Linux, each partition can be plugged into any directory in the file hierarchy, this is call
mounting. The directory into which a partition is plugged is called mount point.
✔ Usually, storage devices has device files such as /dev/sda, /dev/sdb, etc. The partitions in
each storage device are distinguished by numbers, like: /dev/sda1, /dev/sda2, etc.
/dev/sda6
/dev/sda5
✔ Mounting gives the flexibility to put any directory in the system on a separate partition.
For example, /home directory can be put on a separate partition so that the users' files will
not be deleted when the system is reinstalled.
Page 49/130
Configuration files
✔ Universally Unique Identifier (or UUID) is used to uniquely identify storage devices. It
usually consists of 32 hexadecimal number separated by dashes, and it occupies 128 bit.
✔ The file /etc/fstab (or file system table) stores information about devices that are
automatically mounted on system boot. The content of this file are:
▸ Device: Device name (like /dev/sda1) or the UUID of the mounted device.
▸ Mount Point.
▸ File System Type.
▸ Options: lists any active mount options. If using multiple options they must be
separated by commas.
▸ Backup Operation: 1 = dump utility backup of a partition. 0 = no backup. This is an
outdated backup method and should NOT be used.
▸ File System Check Order: 0 means that fsck will not check the file system. Numbers
higher than this represent the check order. The root file system should be set to 1 and
other partitions set to 2.
Display the content of the /etc/fastab.
Page 50/130
Commands
mount Show mounted file system
sudo mount /dev/sda2 /mnt Mount /dev/sda2 partition in /mnt mount point
sudo mount -a Mount all file systems listed in /etc/fstab
sudo umount /dev/sdb1 Unmount /dev/sdb1 device
sudo umount /mnt Unmount the device in /mnt mount point
lsblk -f List storage devices with full information about them
sudo mount myfile.iso /mnt -o loop Mount mfile,iso file in /mnt directory
Page 51/130
MSDOS and GPT partition tables
✔ MSDOS, or Master Boot Record (MBR), partition tables is used in old computers with
legacy BIOS (Basic Input Output System), and still supported by new computers UEFI
(Unified Extensible Firmware Interface). In MSDOS partition table:
▸ The first 512 byte are called Master Boot Record (MBR) and it stores information on
how system will boot.
▸ Only 4 primary partitions are supported. If more portioning needed, one of the primary
partitions is designated as an extended partition and logical partitions are created
within it. The first logical partition has device name /dev/sda5.
▸ Only support storage up to 2 TB (Terabytes).
✔ GPT partiton table (which stands for GUID Partition Table) is supported only by new
computers with UEFI. In GPT you can have 128 primary partitions and 256 TB disk size.
Page 52/130
Mounting removable storage devices
✔ In the GUI, removable storage devices, such as USB flash memories and external hard
drives, are mounted inside /media/username/label if they have labels, or inside
/media/username/UUID if they don't have labels.
Use KDE Partition Manager or gnome-disks to remove the label for a partition on
a USB flash memory and notice where it is mounted in Dolphin file browser. Set a
label for the partition and notice where it is mounted in Dolphin file browser.
Page 53/130
Inodes
✔ An inode is a data structure that keeps track of all the files and directories within file
system. So, every file and directory in a file system is allocated an inode. Inodes store
metadata about each file and directory.
Page 54/130
Link files
✔ A link is a pointer to a file. Links allow more than one file name to refer to the same file.
✔ There are two types of links:
▸ Soft (Symbolic) Links: Each soft linked file contains a separate inode value that points
to the original file.
▸ Hard Links: Each hard linked file is assigned the same inode value as the original,
therefore they reference the same physical file location. Hard links remain linked even
if the original or linked files are moved throughout the file system.
▸ Links have actual linked file contents.
▸ ls -l command shows all the links with the link column shows number of links.
▸ We cannot create a hard link for a directory.
ln target_file link_name Create hard link for a file
ln -s target link_name Create soft link for a file or directory
Page 55/130
Practical tasks
✔ Link files:
▸ Go to the Desktop directory.
▸ Create a file file.txt
▸ Create a soft link called file_s.txt for the file file.txt
▸ Create a hard link called file_h.txt for the file file.txt
▸ Using the command ls -l display the files in the Desktop directory. Notes number of
hard links for the files file.txt, and file_h.txt. Notice the soft link for the file file_s.txt
▸ Using the command nano file.txt, edit file.txt, and store the string hello world in it.
▸ Using cat command, display the content of file.txt, file_s.txt, and file_h.txt.
▸ Delete file.txt
▸ Using cat command, display the content of file_s.txt, and file_h.txt. Does you have
any errors?
▸ Using the command ls -l display the files in the Desktop directory. Notes number of
hard links for the file file_h.txt. Notice the soft link for the file file_s.txt
Page 56/130
✔ Mounting:
▸ Mount the first partition in the USB memory in the directory /mnt
▸ List the file in the directory /mnt
▸ Unmount the partition from the directory /mnt
✔ File systems:
▸ List the mounted file systems using the mount command
▸ Use lsblk -f command to get the UUID for the first partition in USB memory.
▸ Use lsblk -f command to get the file system types for all storage devices.
Page 57/130
5 Input/output redirection and piping
Page 58/130
More commands
grep pattern Print lines that matches pattern. Other similar commands are
wc file Print number of lines, words, and bytes in a file
sort file Sort lines of a file
head files Print the first part of files
tail files Print the last part of files
rev file Reverse text in a file
Page 59/130
Input/output (I/O) redirection
✔ Input/Output (I/O) redirection is changing the standard input (stdin), standard output
(stdout), and standard error (stderr) to be connected to other files. By default, stdin is
connected to the keyboard and stdout/stderr is connected to the screen.
✔ stdin, stdout, and stderr are represented by the device files /dev/stdin, /dev/stdout, and
/dev/stderr, respectively.
Page 60/130
Examples
command > file Redirect output to a file, example: echo "hello world" > hello.txt
command >> file Append output to a file
command < file Redirect input from a file, example: wc -l < /etc/passwd
command 2> file Redirect error to a file, example: ls /root/ 2> error.txt
command 2>&1 Redirect error to output
command 1>&2 Redirect output to error
command &> file Redirect both output and error to a file.
command <<< text Redirect text to input, example: rev <<< "hello"
command > /dev/null Use /dev/null to ignore output, example: ls /root 2> /dev/null
Page 61/130
Piping
command1 | command2 Redirect standard output of command1 to command2
command1 |& command2 Redirect standard error of command1 to command2
Page 62/130
dd command
✔ dd (direct dump) reads blocks from a block device file and writes them to a file.
✔ dd command is very powerful because it can deal directly with devices such as storage
devices (/dev/sda, /dev/sda1, etc), so it should be used with caution.
✔ Examples:
▸ Create a 100M file that contains random data.
dd if=/dev/urandom of=random.data bs=1M count=100
Page 63/130
hd command
✔ hd (hexadecimal dump) is used to display data in a file in hexadecimal format.
✔ Example:
echo "Hello world" | hd
Page 64/130
Practical tasks
✔ Save the output of ls / -l command in the file ~/Desktop/ls.txt
✔ Save the error from the command ls /root in the file ~/Desktop/error.txt
✔ From the file /etc/group, save the first 3 lines into the file ~/Desktop/group3.txt
✔ From the file /etc/group, get only lines that have "sys" string in them, then sort the output
and save it in the file ~/Desktop/sys.txt
✔ From the file /etc/group, display all groups that have an id of 27
✔ From the file /etc/group, find the number of groups in the system
✔ Reverse the text "Hello world" and save the output in the file ~/Desktop/reverse.txt
✔ Sort the file /etc/group in reverse order, and save the output in ~/Desktop/sorted.txt
✔ Create the file ~/Desktop/rand.data that has a size of 10 MiB and contains random data.
✔ View the phrase "I use Linux" in hexadecimal format.
Page 65/130
6 Process control and system startup
Page 66/130
Process control shortcuts and commands
ctrl + c End process
ctrl + z Suspend (i.e. pause) process in the background.
bg [job] Resume suspended process in the background, examples bg , bg %1
fg [job] Bring suspended process to the foreground, examples fg , fg %1
command & Run process in the background, example: kate &
nohup command & Run process in the background and keep it if the terminal is closed
jobs [job] List processes in the background, example: jobs , jobs %1
top Display process
ps List process, example: ps , ps -ef
pstree Show processes as tree
kill [job] Terminate process, example: kill %1
kill -l List possible signals that can be send to a process
kill -signal process_id Send a signal to a process, example: kill -9 1935
killall processname Kill all process, example: killall kate
Page 67/130
Process exit codes and command chaining operators
✔ When a process exits, it returns exit code 0 for success and 1 to 255 for error.
✔ The exit code is returned in the variable $?
✔ The last command id is returned in the variable $!
✔ Chaining operators
▸ command1 && command2 (Run command2 only if previously executed command is
successful)
▸ command1 || command2 (Run command2 only if previously executed command is not
successful)
✔ Examples:
Page 68/130
Command grouping
✔ Place a semicolon (;) between commands to execute them sequentially.
var1="hello world"; echo $var1
✔ Placing a group of commands inside parentheses ( ) will execute them as a group inside a
subshell environment, where variable assignments do not remain in effect after the
subshell completes.
(var1="hello world"; echo "$var1 inside"); echo "$var1 outside"
✔ Placing a group of commands inside curly braces {} will execute them in the current shell,
no subshell is created. A semicolon is required after last command in the group, and a
space should be after {.
{ var1="hello world"; echo "$var1 inside";}; echo "$var1 outside"
✔ What is the difference between these commands:
ls /boot &>/dev/null || echo "Error"; echo "Command exit"
ls /boot &>/dev/null || (echo "Error"; echo "Command exit")
✔ What is the output of each of the following commands, why?
ls /root &>/dev/null || echo Error && echo Success
ls /root &>/dev/null && echo Success || echo Error
Page 69/130
System startup and run-levels
✔ Linux system startup in the following steps:
▸ Power on.
▸ BIOS/UEFI: Performs a POST (Power-On Self-Test), initializes your hardware, and
passes control to the boot loader. BIOS/UEFI is stored in ROM memory on computer
motherboard.
BIOS (Basic Input Output System) for older PCs.
UEFI (Unified Extensible Firmware Interface) for newer PCs.
✔ BIOS/UEFI loads information about booting the operating system as follows:
▸ BIOS (or legacy mode): Loads information from MBR (Master Boot Record), which
is the first 512 bytes in the storage device.
▸ UEFI: Loads information form EFI (Extensible Firmware Interface) partition.
✔ Boot loader: GRUB (GRand Unified Bootloader) is responsible for loading kernel and
initial ram drive (initrd). GRUB configuration files are in the directory /boot/grub/
Page 70/130
✔ Kernel and Initrd: loaded by the boot loader. Configuration files are in /boot/
✔ Systemd/Init: Responsible for initializing processes and run-levels. Systemd is newer and
used by most Linux distros, init is older but still used by some distros.
✔ Run-levels:
▸ 0: Power off.
▸ 1: Rescue mode. Only command line with root user.
▸ 2, 3, 4: Only command line with multi-users.
▸ 5: (Default) Full operation with GUI (Graphical User Interface).
▸ 6: Reboot
✔ Directories /etc/rc0.d, /etc/rc1.d, ... , /etc/rc6.d contain the process that are started (their
names begin with S) or stopped (their names begin with K) when starting run levels 0 to 6.
✔ Commands:
▸ runlevel Show current run-level
▸ sudo telinit 0-6 Change run-levels, example: sudo telinit 1
Page 71/130
Display Server
✔ Unlike windows, the GUI in Linux is separate from the kernel, which means it is possible
to run Linux operating system without a GUI at all. This makes the system more
lightweight, more stable, and more secure.
✔ The display server (or X-server) is responsible for controlling the GUI in Linux. The
display server receives input from input devices, such as mouse, keyboard, etc, and
displays the GUI elements.
✔ X11 display server is still used by most Linux distributions, but it is slowly being replaced
by Wayland. You can also switch between them in most distros.
✔ The login manager or display manager (not to be confused with display server) is the first
graphical program that shows up to give you a list of users so you select one and login.
✔ The window manager controls windows, gives them borders, and allows
moving/maximizing/minimizing them. The window manager is usually a component of
the desktop environments.
Page 72/130
Page 73/130
Virtual terminal mode
✔ Press Ctrl+Alt+(F2 to F6 ) to switch to Virtual Terminal (i.e. no GUI) mode
✔ Press Ctrl+Alt+F1 to switch back to GUI mode.
✔ If you are running Linux using VirtualBox, press Host key (usually right CTRL) and F1 to
F6 instead.
✔ Use tty command to know which virtual terminal you are running.
Page 74/130
Practical tasks
✔ Task1:
▸ Run kate program in the background.
▸ Run kcalc program in the background two times.
▸ Bring kate program to the foreground.
▸ Suspend (i.e. pause) kate program. Try to write some text in it, can you?
▸ Resume kate program in the background. Try to write some text in it, can you?
▸ Terminate (i.e. kill) kate program using its process id.
▸ Kill all instances of kcalc program.
✔ Run kate process in the background so it keeps running if the terminal is closed.
✔ Show the process tree using pstree command.
✔ Run top command and quit it.
✔ Use the command free -h to display memory usage in a human-readable format.
Page 75/130
✔ Complete ls some_directory command so the message "Error" will be displayed if the
directory contents can not be displayed and "No error" will be displayed otherwise. The
original error message and the output from ls program should not be displayed. Apply
your command on /root and /boot directories.
✔ Show the current run-level.
✔ Run the following command to show the display manager used by the distro.
systemctl status display-manager
✔ Run pstree | less command to and locate the display manager among other process.
✔ show the variable $XDG_SESSION_TYPE to know which display server is running.
Page 76/130
7 Introduction to shell (Bash) scripting
Page 77/130
Shell vs terminal
✔ User writes commands to the terminal and receives
output from it.
✔ Terminal transfers commands to the shell and
receives output from it.
✔ Shell is responsible for interpreting and executing
the commands.
✔ Kernel runs the programs and manages their access
to the hardware and the file system.
Run kate application from the terminal then
use the system monitor to see the processes
as a tree.
Page 78/130
Bash script file
✔ The shell commonly used in Linux is calld bash (The GNU Bourne-Again Shell).
✔ Other shells: sh (Bourne Shell), csh (C shell), ksh (Korn Shell), zsh (Z Shell).
✔ Shell commands can be written in script files (sometimes end with .sh).
✔ Example:
▸ Write a shell file revtxt that receives a text and then displays it in reverse.
▸ Make the file revtxt executable and run it by typing ./revtxt or bash revtxt
▸ What does "./" mean?
#!/usr/bin/env bash
# Put the previous line in the begging of a shell file
# to determine which program runs it (in this case its bash)
# Put the symbol (#) at the begging of a line to comment it
read -p 'Enter a string ' myStr # Reading input from user
# Displaying string in reverse
echo $myStr | rev
Page 79/130
Running script files
✔ The line #!/usr/bin/env program is used at the beginning of a script file to determine
which program will handle its execution. The symbols ( #! ) are called shebang.
▸ #!/usr/bin/env bash 🡆 bash script file
▸ #!/usr/bin/env python3 🡆 python3 script file
✔ To execute a file, its full path should be entered at the terminal, and to run a script file in
the current directory "./" can be used before its name. Examples:
▸ /home/ahmad/Desktop/revtxt (full path)
▸ ./revtxt (if Desktop is the current directory)
✔ bash script_file : Running script file into separate shell. No need for shebang.
▸ bash example1.sh
✔ source script_file : Running script file into the current shell. No need for shebang.
✔ export command is used to pass variables to child processes.
Page 80/130
✔ Example1
echo 'MYVAR=Hello' > example1.sh
bash example1.sh
echo $MYVAR
source example1.sh
echo $MYVAR
✔ Example2
VAR1="One"
export VAR2="Two"
echo 'echo $VAR1; echo $VAR2' > example2.sh
bash exmaple2.sh
source example2.sh
Page 81/130
System path
✔ $PATH is an environment variable that tells Linux system in which directories to search
for executable files.
✔ To show the path, run the command echo $PATH
✔ To add a directory to the path, run the command export PATH=$PATH:your_directory
✔ Notice that the current directory is not listed in the system path by default.
Page 82/130
Configuration files
A script file that contains user's specific configuration, like $PS1 variable for
~/.bashrc
prompt configuration. It is executed when a user log in or starts a terminal.
~/.profile A script file that is executed when a user log in.
Contains Linux system wide startup scripts. It is executed when the system
/etc/profile
starts, and it executes the scripts in /etc/profile.d directory.
Modify the corresponding file to display the text "Hello world" when you start
the terminal?
Page 83/130
Command arguments
✔ The arguments for a shell script are stored in the variables $0, $1, $2, etc.
✔ Example: Write the following script in the file arg.sh and run it using the command
./arg.sh arg1 arg2 arg3 and bash arguments arg1 arg2 arg3
#!/usr/bin/env bash
echo "Command is $0"
echo "First argument is $1"
echo "Second argument is $2"
echo "Third argument is $3"
Page 84/130
If statement
✔ The general structure for the if statement is :
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
Page 85/130
Example
✔ Write the script checknum that receives a number and check if the number is less than 10.
#!/usr/bin/env bash
read -p "Enter a number " NUM
if [ $NUM -lt 10 ]; then
echo "$NUM is less than 10"
else
echo "$NUM is greater than or equal 10"
fi
Page 86/130
Command substitution and arithmetic expansion
✔ Use $(command) or `command` to substitute the output of the command. Backtick ( ` ) is
not a single quote, it is in the top left corner of the keyboard, as in the picture below.
The $ sign must be used before variables inside command substitution
✔ Use $((expression)) to get the output of integer arithmetic expression. The $ sign is
optional before variables inside arithmetic expansions.
✔ Arithmetic operators are + , - , * , / , % (modulus) , ** (power).
✔ Write a script number.sh that receives a number and determines if its odd or even.
#!/usr/bin/env bash
read -p "Enter a number " NUM
if [ $((NUM % 2)) -eq 1 ]; then # $NUM can be used
echo "$NUM is odd"
else
echo "$NUM is even"
fi
Page 87/130
For loop
✔ The general structure of for loop is:
Page 88/130
While loop
✔ The while loop is executed as long as the condition is true.
✔ The general structure of while loop is:
while [ condition ]; do
commands
continue # continue is used to skip the current iteration
break #break is used to exit the current for loop
done
Page 89/130
Until loop
✔ The until loop is executed as long as the condition is not true.
✔ The general structure of until loop is:
until [ condition ]; do
commands
continue # continue is used to skip the current iteration
break #break is used to exit the current for loop
done
Page 90/130
and, or, not
✔ And operation:
[ condition1 ] && [ condition2 ]
✔ Or operation:
[ condition1 ] || [ condition2 ]
✔ Not operation
[ ! condition1 ]
Page 91/130
Example
✔ The following exist script checks the existence of two files. Run it as ./exist file1 file2
#!/usr/bin/env bash
if [ -e $1 ] && [ -e $2 ]; then
echo "File1 exists. File2 exists."
elif [ -e $1 ] && [ ! -e $2 ]; then
echo "File1 exists. File2 does not exist."
elif [ ! -e $1 ] && [ -e $2 ]; then
echo "File1 does not exist. File2 exists."
elif [ ! -e $1 ] && [ ! -e $2 ]; then
echo "File1 does not exist. File2 does not exist."
fi
Page 92/130
Example
✔ Write the script dir5 to create directories dir1, dir2, ..., dir5 in the Desktop directory, and in
each directory it creates subdirectories dir1, dir2, ..., dir5.
✔ Use seq command to generate a sequence of number. What is the output of the following
commands?
▸ seq 5
▸ seq 2 8
#!/usr/bin/env bash
for dir1 in $(seq 5); do
mkdir "$HOME/Desktop/dir${dir1}"
for dir2 in $(seq 5); do
mkdir "$HOME/Desktop/dir${dir1}/dir${dir2}"
done
done
Page 93/130
Practical tasks
✔ Write the script fact that shows the message "Enter a number" and receives a number,
then displays its factorial. If the number is negative, it should displays "Invalid number".
✔ Write the script pyramid that shows the message "Enter text" and receives a text, then it
displays the first character, then the first two characters, and so on. Use cut command to
get characters. For example if the text is "Good", it will display:
G
Go
Goo
Good
✔ Write a script called prime that receives a number as an argument, then it displays all
prime numbers less than or equal to it separated by a comma. If the number is less than 1,
it displays "Invalid number". For example, ./prime 10 will display 1,2,3,5,7
Page 94/130
8 Text processing
Page 95/130
nano text editor
✔ It is a simple CLI based text editor.
nano filename Edit or create a file, example: nano myfile.txt
sudo nano filename Edit file with root permission, example: sudo nano /etc/fstab
✔ Shortcuts: Short cut are displayed on the screen, some of them are:
▸ Ctrl-O: Save file
▸ Ctrl-X: Exit
▸ Alt-A: Start/end select mode
▸ Alt-6: Copy a line or selected text
▸ Ctrl-K: Cut a line or selected text
▸ Ctrl-U: Paste
▸ Ctrl-W: Search
▸ Alt-W: Next match
▸ Alt-Q: Previous match
vi is another text editor. Find more about this editor on the internet.
tilde is another simple-to-use text editor. Install and try using it.
Page 96/130
less command
✔ Used to display a file. Examples:
▸ less /proc/cpuinfo
▸ ls /dev -l | less
✔ Press:
▸ q to exit.
▸ /string to search for string, press / to find next match.
Page 97/130
grep command
✔ Short for Global Regular Expression Print. It is used to search for lines that has a matching
string in a file or group of files.
grep string files Search for string in file(s), example: grep root /etc/passwd
grep -r string Search in all files in a directory and its subdirectories. Current directory
directory is used if no directory is specified. Example: grep -r root /etc/
grep -i string files Ignore case, example: grep -i mhz /proc/cpuinfo
grep -v string files Print lines that do not contain the string.
grep -c string files Count the number of lines where the match found
grep -w string files Search for complete word, not part of it. grep -w wp /proc/cpuinfo
Display n line after found match. Use -B n to display n line before
grep -A n string files
found match. Example: grep -A 5 root /etc/passwd
grep -n string files Display line number. Example: grep -n MHz /proc/cpuinfo
command | grep string Using pipes. Example: ls -l / | grep -i bin
Page 98/130
Regular expressions
✔ A regular expression (regex or regexp) is a sequence of characters that specifies a search
pattern. Some of these expressions:
Character Explanation
. Any character except newline
a The character a
ab The string ab
a|b a or b
a* 0 or more a's
\ Escapes a special character
\n Newline
\t Tab
[] Character class, for example [.] is the dot character, not any character.
* 0 or more
+ 1 or more
? 0 or 1
Page 99/130
{2} Exactly 2
{2, 5} Between 2 and 5
{2,} 2 or more
^ Start of string
$ End of string
\b Word boundary
\B Non-word boundary
[ab-d] One character of: a, b, c, d
[^ab-d] One character except: a, b, c, d
[\b] Backspace character
\d One digit
\D One non-digit
\s One whitespace
\S One non-whitespace
\w Word
\W Non-word
. Any character except new line (\n) \c Control character ^ S tart of string, or start of line in multi- g Global match
(a|b) a or b \s White space line pattern i* Case-insensitive
(...) Group \S Not white space \A S tart of string m* Multiple lines
(? :...) Passive (non-capturing) group \d Digit $ E nd of string, or end of line in multi-line s* Treat string as single line
pattern
[abc] R ange (a or b or c) \D Not digit x* Allow comments and whitespace in
\Z E nd of string pattern
[^abc] Not (a or b or c) \w Word
\b Word boundary e* E valuate replacement
[a-q] Lower case letter from a to q \W Not word
\B Not word boundary U* Ungreedy pattern
[A-Q] Upper case letter from A to Q \x Hexadecimal digit
\< S tart of word
[0-7] Digit from 0 to 7 \O Octal digit * PCR E modifier
\> E nd of word
\x Group/subpattern number "x"
E scape S equences
Assertions S tring R eplacement
R anges are inclusive.
\ E scape following character
?= Lookahead assertion $n nth non-passive group
POS IX \Q Begin literal sequence
?! Negative lookahead $2 "xyz" in /^(abc( xyz ))$/
[:upper:] Upper case letters \E E nd literal sequence
? <= Lookbehind assertion $1 "xyz" in /^(? :abc)( xyz)$/
[:lower:] Lower case letters ? != or ? <! Negative lookbehind "E scaping" is a way of treating characters
$` Before matched string
[:alpha:] All letters which have a special meaning in regular
?> Once-only S ubexpression $' After matched string expressions literally, rather than as special
[:alnum:] Digits and letters ? () Condition [if then] $+ Last matched string characters.
[:digit:] Digits ? ()| Condition [if then else] $& E ntire matched string
[:xdigit:] Hexadecimal digits ?# Comment S pecial Characters
S ome regex implementations use \ instead
[:punct:] Punctuation of $. \n New line
[:blank:] S pace and tab Common Metacharacters \r Carriage return
[:print:] Printed characters and spaces < > ? 0 or 1 {3,5} 3, 4 or 5 \xxx Octal character xxx
[:word:] Digits, letters and underscore The escape character is usually \ Add a ? to a quantifier to make it ungreedy. \xhh Hex character hh
Page 101/130
egrep command
✔ Some regular expressions (like: ^ , $ , . , [a-z] ) can be used with grep command.
✔ Use grep -E or egrep command for extended regular expression options.
Page 102/130
sed command
✔ Stands for Stream EDitor and it a powerful text stream editor. Can do insertion, deletion,
search and replace.
✔ It supports regular expression which allows it perform complex pattern matching.
✔ Examples:
echo "Unix, Unix, Unix" | sed 's/Unix/Linux/' # replace first match
echo "Unix, Unix, Unix" | sed 's/Unix/Linux/2' # replace second matches
echo "Unix, Unix, Unix" | sed 's/Unix/Linux/g' # replace all matches
echo "Unix, Unix, Unix" | sed 's/Unix//g' # delete all matches
echo "Unix, Unix, Unix" | sed 's/Unix/Linux/2g' # start from the second match
sed 's/:x:/:PASSWD:/' /etc/passwd # replace pattern in a file
sed '3 s/:x:/:PASSWD:/' /etc/passwd # replace pattern in the 3rd line
sed -n '3 s/:x:/:PASSWD:/' /etc/passwd # no output
sed -n '3 s/:x:/:PASSWD:/p' /etc/passwd # print only lines with matches
sed '5d' /etc/passwd # delete the 5th line
sed '5,$d' /etc/passwd # delete from the 5the to the last line
Page 103/130
ls / | sed 's/^b/B/' # Uppercase items start with b
# In the file /etc/group, replace the words "mail" or "news" with "AAA"
sed -E 's/mail|news/AAA/' /etc/group
Page 104/130
head and tail commands
✔ Print the beginning and end of a file
Page 105/130
cut command
✔ Cut sections from each line of files or piped text.
Page 106/130
awk command
✔ It is has advanced text search and processing features.
✔ Lines are divided into fields $1, $2, $3, etc. $0 is the whole line.
✔ Default delimiter is whitespaces (one or more)
echo 'I use linux' | awk '{print "We " $2 " " $3}'
Page 107/130
printf command
✔ printf command is used for displaying formatted text and escaped formatting characters
like newline \n, tab \t, double quote \", etc. Use man printf command to see more
escaped characters.
✔ Unlike echo command, printf command does not print newline at the end. Use \n to print
a newline.
✔ Example:
printf "Name\tAge\nAli\t23\nOmar\t30\n"
Output:
Name Age
Ali 23
Omar 30
Page 108/130
find command
✔ Used to find files and directories in the specified location and its subdirectories according
to certain conditions such as permissions, user, group, file type, date, size.
✔ General format for find command is: find location conditions pattern [-options]
find all files and directories start with c in
find /dev -name "c*"
/dev directory and its subdirectories
find /etc/rc5.d/ -iname "[sk]*" -name case insensitive search
find /dev -type d -name "c*" -type specifies file type. See man find
find /dev ! -type d -name "c*" ! inverts condition
-exec executes command. "{}" represents
find /dev -name "c*" -exec ls {} -ld \;
found files. Put "\;" at the end.
find . -perm 700 -exec ls {} -ld \; -perm specifies permissions
find -L /bin -name "*" Use -L when directories are symbolic links.
Page 109/130
Practical tasks
✔ View the file /etc/group using less command and search for the string "sudo" in it.
✔ For the file /etc/passwd and using grep command, view lines that start with the letter w or
the letter p
✔ For the file /etc/group and using egrep command, view the lines that start with "mail" or
"news". Display line numbers.
✔ For the file /etc/passwd and using egrep command, view the lines that start with the letter
"s" and end the word "login". Display line numbers.
✔ For the file /etc/passwd and using egrep command, view the lines where the letters "s" is
followed by any two characters, then followed by the letter "n".
✔ For the file /etc/passwd and using sed command, replace ":x:" with ":y:".
✔ Using cut command, display only the first 4 characters of each line in the file /etc/group
✔ Using awk command, print "User username is in group GID" where username and GID
are taken from the file /etc/passwd .
✔ Use awk command to print the username with ID equals 102. Use the file /etc/passwd .
✔ Find all files in the directory /sbin where their names consist of three characters, and copy
them into the Desktop folder. Notice that /sbin is a symbolic link.
Page 110/130
9 Networking
Page 111/130
Notes
Install the required package using the commands:
Link:
https://mindmajix.com/linux-networking-commands-best-examples
Page 112/130
ifconfig command
✔ ifconfig stands for interface configurator.
✔ It is one of the most basic commands used in network inspection and configuration.
✔ An interface is is the device through which network traffic goes.
✔ The loopback device ( lo ) is a virtual network interface that computer uses to
communicate with itself. It is used mainly for diagnostics and troubleshooting, and to
connect to servers running on the local machine.
✔ ip command can also be used to show/manipulate routing, network devices, interfaces and
tunnels
ifconfig -a Display all interfaces both enabled and disabled
Assign an IP address an interface.
sudo ifconfig interface address
Example: sudo ifconfig wlan1 122.140.201.66
sudo ifconfig interface netmask Assign network mask to an an interface.
mask Example: sudo ifconfig wlan0 netmask 255.255.255.0
sudo ifconfig interface up To enable an interface, example: sudo ifconfig eth0 up
sudo ifconfig interface down To disable an interface, example: sudo ifconfig eth0 down
ip a Display all interfaces
Page 113/130
traceroute command
✔ Used to detects the delay and determines the pathway to your target.
✔ Each line shows the hop number, the system's IP address, and the round trip times of three
packets in milliseconds. The round trip times (or RTTs) tell us how long it took a packet to
get from one hop to the next and back again.
✔ The asterisks (*) mean that the timeout was reached before getting a response.
The output indicates network delays.
traceroute address
Example traceroute www.google.com
traceroute --resolve- Resolve hostnames.
hostnames address Example: raceroute --resolve-hostnames www.google.com
traceroute -I address Use ICMP packets instead of UDP
Page 114/130
ping command
✔ It stands for Packet INternet Groper and it basically checks for the network connectivity
between two nodes.
✔ It sends the ICMP echo request to check the network connectivity, and it keeps executing
until it is interrupted. Use Ctrl+C Key to interrupt the execution.
Page 115/130
netstat command
✔ It refers to the network statistics, ant it provides statistical figures about different interfaces
which include open sockets, routing tables, and connection information.
Page 116/130
ss command
✔ It is the replacement for netstat command. It is regarded as a much faster and more
informative command than netstat.
ss -ta Show TCP sockets, a show the connected and listening sockets.
ss -ua Show UDP sockets.
ss -xa Show UNIX sockets.
ss -tl Show TCP sockets, l show the listening sockets.
ss -t4 state established Get a list of all the established sockets of TCP for IPV4,
ss -t4 state closed Get a list of all closed TCP sockets,
ss dst ip-address Get a list of all connected ports for a specific IP address
Page 117/130
dig command
✔ It stands for Domain Information Groper. This command is used in DNS lookup to query
the DNS name server. It is also used to troubleshoot DNS related issues.
✔ The command nslookup can be used for same purpose.
Page 118/130
route command
✔ Display and manipulate the routing table existing for your system.
route Display routing table
route -n Displaying numerical IP address
sudo route add default
Add a gateway
gw ip_address
Page 119/130
host, arp, iwconfig, and hostname commands
✔ host command displays the domain name for a given IP address and IP address for a given
hostname.
host domainname Example: host www.google.com
✔ arp command stands for Address Resolution Protocol. It is used to view and add content to
the kernel's ARP table.
✔ iwconfig command is used to configure the wireless network interface.
✔ hostname command used to view and set the hostname of a system.
hostname Show the hostname (i.e. computer name)
sudo hostname newname Set the hostname for the computer.
Page 120/130
curl and wget commands
✔ Used in downloading files from the internet through CLI.
Page 121/130
mtr, whois, ifplugstatus, and iftop command
✔ mtr command is a combination of ping and the traceroute command. It continuously
displays information regarding the packets sent with the ping time of each hop. It is also
used to view the network issues. Example: mtr www.google.com
✔ whois command is used to fetch all the information related to a website. You can get all
the information about a website including the registration and the owner information.
Example: whois mindmajix.com
✔ ifplugstatus command is used to check if a cable is plugged into the network interface.
Example: ifplugstatus
✔ iftop command is used in traffic monitoring.
Page 122/130
tcpdump command
✔ It is the most used command in network analysis among other Linux network commands.
It captures the traffic that is passing through the network interface and displays it.
✔ This kind of access to the packet will be crucial when troubleshooting the network.
Page 123/130
Practical Tasks
✔ Using ifconfig command show all network interfaces, and determine if they are up
(enabled) or down (disabled).
✔ Using traceroute command, trace the connection to www.google.com and show the
hostname of the hops.
✔ Using ping command, check the connection for 7 times to www.google.com.
✔ Using netstat command, show information about the interfaces and the sockets in the
system. Show program PIDs and names.
✔ Using ss command, show information about all TCP and UDP sockets.
✔ Using route command, show the system routing table.
✔ Using host command, show the IP for www.google.com.
✔ Using tcpdump command, show all TCP traffic on the interface you are using. Go to
www.google.com and show the change in traffic.
Page 124/130
10 Extra topics
Page 125/130
Virtualbox
✔ Learn more about Virtualbox and how to use it to run Linux inside windows or Windows
inside Linux.
Page 126/130
System installation
✔ Try to learn the different aspects when installing Linux operating system, such as:
▸ Downloading distro ISO file and installing it on a USB memory.
▸ BIOS/UEFI settings.
▸ Booting from a USB memory.
▸ MSDOS/GPT partition tables.
▸ Mounting points.
Page 127/130
Emulation using dosbox and wine
✔ dosbox emulator is used to run DOS programs inside Linux.
✔ wine emulator is used to run Windows programs inside Linux.
Page 128/130
General discussion and conclusion
✔ Share any discussion and conclusion about Linux operating system.
Page 129/130
The End
Page 130/130