0% found this document useful (0 votes)
7 views33 pages

Introduction To Linux Notes

The document provides an introduction to Linux, covering its philosophy, features, and various distributions. It emphasizes the importance of practical learning, scripting, and the command-line interface, along with the history and advantages of open-source software. Additionally, it outlines the structure of lectures, including rules, objectives, and references for further learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views33 pages

Introduction To Linux Notes

The document provides an introduction to Linux, covering its philosophy, features, and various distributions. It emphasizes the importance of practical learning, scripting, and the command-line interface, along with the history and advantages of open-source software. Additionally, it outlines the structure of lectures, including rules, objectives, and references for further learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Linux Notes

Lecture 1
Rules

No mobile phone
No recording
If you start a sentence with a language you must keep it till end
Presence is important
Quiz at end of each Lecture to mark presents and explain more not to evaluate

Objective

Introduce the linux concept and philosophy , not just learn the commands , focus on practice
A guided tour of the Unix operating system.
Become familiar with Unix and its data
processing capabilities.
Use various scripting languages to write filters
for transforming data.
Develop a proficiency for UNIX, a basic
understanding of the shell programming and a
familiarity with tools including AWK, Make...

Linux

Free Open source software


Operating system ==> System software ==> Familiar with Unix , data processing capabilites , scripting
languages , shell programming , AWK , Make , ..
Software that allows communication between hardware and software managing tasks and ressources.
Kernel : Primary module of OS
GNU LINUX : OS , layer between hardware and user-level applications
LINUX : Kernel
OS roles :
Hide hardware complexity and diversity
manage ressources
provide isolation and protection for applications
Multitasking : Several tasks at one time
Several distributions == different roles

Main OS features

1. Help / assistance :
Hide complexity
APIs of devices are often very complex
Access to all features (even those that are rarely used)
Simplify access to devices
Modularity and maintainability of code
Manage all situations (even exceptional)
2. Abstraction :
Different devices provide similar services
reduced functionality, increased reusability, code portability
3. Augmentation :
Performance improved
Extend ressources virtually
Multitasking
4. Arbitration :
Distribute access to ressources
Reliability of system
5. Authorization :
Privacy and system integrity
Limit access to ressources
Security

Outline

Intro to Linux
Utilities and commands
File system and permissions
Shell
GUIs
AWK, Sed, Grep
Advanced shell scripting
Networking and internet
System administration and security
Programming tools

References

Sumitabha Das, Your UNIX/LINUX: The Ultimate Guide. McGraw


Hill, 2012.
Mike Joy, Stephen Jarvis and Michael Luck. Introducing Unix and
Linux. Palgrave Macmillan. 2002
Mokhtar Ebrahim and Andrew Mallett, “Mastering Linux Shell
Scripting: A practical guide to Linux command-line, Bash scripting,
and Shell programming”. 2018
Plenty and free online books and MOOCs...

Lecture 2
Lab 1: 2 weeks to submit one PDF file (Lab report)
Who and When:
Linus Torvalds : Linux in 1991
Richard Stallman : GNU utilities 1983
1980 : 100% of softwares were properiatory
Advantage of open source software : everyone in the world is able to be a test and develop engeneer ==>
Less money investiment , software belongs to community
Statistics :
67% of servers run linux
41.8% of websites with known os use linux
2020, 96% of top 1 million websites were powered by linux
2022, 91.5% of supercomputers (top 500) use linux
84% of enterprise business run linux
58% of IoTs run linux
IoTs Two main problems : Power and Security
83% of software industry use linux as primary os
Modern smartphones and devices like : Android phones , Amazon kindle , smart tvs
Android is a framework built on top of linux kernel
Why Linux :
Free and open source
Powerful for research datacenters
Personal, Universal
Community and business driven
Linux distrubutions
Customized version of linux
Collection of packages and applications with the same linux kernel
Distributions are based on other ones
Beginners : Mint , K/Ubentu , Solus
Beginners to Intermediate : Fedora, OpenSUSE , Mageria (Some post-install needed)
Codec : library needed for code and decoding videos
Advanced : Debian , RHEL , Arch (need to read documentation and get comfortable with cmd
lines)
Experts : Slacware, nixOS, Gentoo (Additional distro specific knowledge: compile the source
depending on the use, they dont just install)
Criterias of choosing a distribution :
1. Target audience and systems (desktop , server , old machines , ..)
2. Process of installing and updating applications (package management tools : cmd lines to install ,
unistall , update specific application)
3. Supports and updates (by volunteers or commercial vendor)

Red hat Enterprise Linux

Most popular commercially supported linux distribution


Commnly used by organizations as server platfroms
2019, IBM acquired it
RPM and YUM tools are used in software installation and management of packages
Learning to use one tool then easy to switch

CentOS Linux

Derivation of RHEL without brand name and support


Only rely on community for support
Used by small companies (want to use RHEL for free)
RHEL features are first tested in CentOS to let community test and validate it

Fedora Linux

Supported by red hat entreprise

SUSE Linux

Support is paid

Debian Linux

Free, Project started in 1993


Largest free software package collection

Ubentu Linux

Based on debian
Free and easy use

Linux Mint

Used for educational purposes


Based on ubentu

Kali Linux

Based on debian
Used for security of networks and systems , hacking and cracking ..

Distribution choice criterias

No rules for selecting a specific distribution


Only choose based on requirements, skills and budget

Recommandation

Red hat derived distributions :


Entreprise (Large) size network
Ubentu derived distributions :
Small / Mide size network
Personal use

Lecture 3
==> Good News (or No actually) : Introduction slides ONLY will be sent by the end of this week.

Definitions

GNU : os is complete free software system, upward compatible with Unix


GNU stands for "GNU's not Unix"
The free software Foundation (FSF) was founded in October 1985, initially to raise funds to help
develop GNU.
FSF was made by " Richatd M. Stallman " emacs editor author and other important programs with
goal of making high quality software "freely" available.
Bash (Shell) , GCC (C compiler) , GDB (Debugger) , GIMP (Image manipulator) , Gnome (Desktop
environment) , Emacs (Text editor) , Ghostscript and Ghostview (files with extension .ps / Interpreter
and graphical frontend for PostScript files) , GNU Photo (Interaction with digital cameras) , G++ (C++
Compiler) , Octave (PL used to perform Computing and Image processing) , GNU SQL, Radius
Open source : its users have freedom to run, copy , distrbute, change and improve the software
Software licence : legal instrument govering the use or redistribution of software
During 80s, GNU designed GNU General public license (GNU GPL) to release free software under a
license designed to protect freedom for all users of a program
Linux was placed under the GNU GPL.
Under GPL :
(Contaminating = Evrything will become of the same licence)
Software distributed under it may be changed as well as sold at any time, but the (possibly
modified) source code must always be passed along-thus open source-and that the recipient
must receive the same rights of modification and redistribution
Copyleft : Any distribution must be published under same name and same conditions.
Open source Licenses : now we are using :
GNU GPLv3 : strong copyleft licence.
GNU LGPLv3: Distribute under different terms without source code.
License Choosing is Legal departement Decision.
- Reverse engeneering : Reading Binary code (Which can lead to discovering stollen code , code taken
from GPLv3 softwares)

Shell

Shell : main part of Linux


- Software that acts as an interface between User and Kernel
- Not graphical Interface (Command Line Interface)
- We can use only keyboard , No mouse.
- Examples of Bash : (B stands for Bourne, A for Again, SH for Shell)
- GNU version of 1977.
- Bourne is the author's name (English computer scientist)
- First existing Shell is called Sh.
- Other Shells : Zshell , KShell
- BASH is the generic Shell , contains the most of features.
- Being familliar with bash will make it okay to use any other shell.
- Bash checks syntax errors.
- Once Shell make sure that Command is correct it will give the result.
- Shell : Program that interprets commands and sends them to the OS.
- It provides :
- Built-in commands : commands that come with the shell (pre-defined commands inside the shell)
- Programming control structures : Write programs (Scripts: set of commands)
- Scripts are interpreted and not compiled.
- Environment variables : Pre-defined variables that you can manipulate, modify and create your own
variables within a script.
- Linux supports multiple shells : Bash, csh, zsh, ksh, ..
- MacOS uses zshell by default but can install other one.
==> We will be exploring Bash.
Command : Software , you can create your own commands by writing Code and calling it in the shell.
Or use Aliases : use commands that exist but customize it : Put command with some options under
new name.
Pormpt (Green Part): Waiting for commands :
username@systemname (~)currentdirectory $/#
~: For home directory
$: For normal (regular) user
#: For super user
The input : command --option argument
- Command : Program that does one thing
- Options : Change the way a command does that thing :
- Short Form : Single-dash and one letter e.g. ls -a
- Long Form : Double-dash and a word e.g. ls --all
- Argument (Parameters) : Provides the input/Output that commands interract with.
==> It's advisable to keep this order (Command - Option Argument)
Command : "Small Programs that do One thing Well"
.".. at its heart is the idea that the power of a system comes more the relationships among programs than
from the programs themselves. Many UNIX programs do quite trivial things in isolation, but, combined
with other programs, become general and useful tools."
Source: The Unix programming Environment Kemigham & Pike.

==> It's better to search for information in google.

Lecture 4
Script : set of commands assembled in a specific way, like a program

Commands

whoami : Prints the username


- You may forget which user you are logged in as
- hostname : Prints the name of the machine
- You can open a new terminal in another machine
- echo "I wanna sleep": Prints characters to screen
- echo $HOME: Print the value an environment variable
- $HOME gives the path to Home directory
- echo my login is $(whoami) : Prints the string then replace whoami with the username
- Without brackets : The value of the variable
- With brackets : Execute the command and print the output in same line
- date : Prints current time/date
- cal : Prints this month's calendar
- Youtube ==> Not that easy
==> You can create your own manual
==> A manual is used to know more about commands
==> There are meany tools to know more about "date" command :
type date
date --help
help date
man date
apropos date
whatis date
info date
You have also Google, ChatGPT, ...

Commands types

Built-in commands(pre-defined)
added commands (software installed in the machine)
- Type command : is a shell built in command that displays the kind of command of the shell will execute
given a particular command name
it works like this : type command
- --help : Display usage info: displays a description of the command's supported syntax and options
It works like this : command --help (-h : abreviation)
- help (command): Get help for shell built-ins
It works like this : help shell-built-in-command
- man command : Display a program's manual page, most executable programs intended for command-
line use provide a formal piece of documentation called a manual or a man page. A special paging
program called man is used to view them like : man program
a title, a synopsis of the command's syntax, a description of the command's purpose, a listing and
description of each of its options
Man pages do not usually include examples
It is used literally by everyone
It is used for reading the command line manual page for linux commands , a configuration file, or any
other feature
On most Linux systems, man uses less to display the manual page
- less : a command that allows reading text files
- Ways of scrolling :
- space , f Page forward
- b page backward
- < go to first line of file
- > go to last line of file
- / search forward (n to repeat)
- ? search backward (N to repeat)
- h display help
- q quit help
==> You dont have to remember all commands options but commands like less all options are needed
and you must know them
Script : This a script example

#!/bin/ bash #It means this is a bash script [Link]


if ["$1" == "h"]; then
echo "Hello"
fi
if ["$1" == "b"]; then
echo "Bye"
fi

To execute the script : ./test in a bash shell


To transmit a prameter to a script : ./test h
The script prints "Hello" if "h" is specified as an argument
The script prints "Bye" if "b" is specified as an argument
How to create a manual page
we use Manual page for different type :
Something all developers agree on :
The section of the manual are:
1. General commands manual
2. System calls manual
3. Library functions manual
4. Kernel interfaces manual
5. File formats manual
6. Games manual
7. Miscellaneous Information manual
8. System manager's manual
9. Kernel developper's manual

A man page is created using the very old roff markup language (troof nroff are variants)
It has commands (read markers) for various titles and sections :
TH - This should be first commands in the man file. It is used to specify the title heading of the man
page
SH - Section Heading
B - It is used to display the text next to it in bold
TP - It is used to display information about an argument (flag) to the command
BR - It is used to display text in bold and in the normal Roman font

1. Create a text file test.1 :

.TH [Link] 1
.SH NAME
[Link] \- Print Hello or Bye
.SH SYNOPSIS
.B [Link]
[ h ]
[ b ]
.SH DESCRIPTION
.B [Link]
This is a simple script wich does only 2 things. It either prints "Hello" if argument is
"h" or it prints "Bye" if argument is "b"
.SH OPTIONS
.TP
.BR h
Print Hello
.TP
.BR b
Print Bye

man ./test.1 to get this manual page


==> For more info about manual pages syntax we use man man pages

The system stores its man pages at /usr/share/man/


The directory /man/man1 stores man pages for user shell commands.

cd /usr/share/man/man1
ls -l
zcat [Link]

==> zcat is used to read compressed files without decompressing (zip files or gz files)
==> It is recommended to store your own man pages in /usr/local/man

apropos command : Display appropriate commands


It is used like this : apropos keyword
Search the list of man pages for possible matches based on a search term (the keyword)

apropos floppy

==> This will show the man pages that related to the keyword "floppy"

Whatis Command : Display a very brief despcription (One line) of a command


Display the name and a one-line description of a man command
It is used like this : whatis command
Info Command : Display a program's info Entry
The GNU project provides an alternative to man pages called info pages. Info pages are displayed with a
reader program named info.
Info pages are hyperlinked much like web pages
It is used like this : info command

Lecture 5
General Notes

You can custom the prompt


man -k with a key word == apropos with keyword
man -f == whatis
If it's not the same check this :
Same running shell
Update (man --version , apropos --version)
Check if there's any aliases
Check where are the man files and check if they are identical and not missing or modified
Regular expression : A pattern which checks if a given input is compatible for the given pattern
Linux is very customizable system
Modifications in linux is safer than other systems
Being a root in Linux needs some experience (We have certifications to become Linux administrator)

User management

Three types of users/accounts

1. Root account : also called superuser. Has a complete and unfettered control of the system. A superuser
can run any commands without any restrictions. This user should be assumed as a system adminstrator.
2. System accounts : Created by the system during installation and are used to run system services and
applications. These accounts are usually needed for some specific function on the system, and any
modifications to them could adversely affect the system.
3. User accounts : Created by the administrator and can access the system and its resources based on
their permissions. Provide interactive access to the system for users and groups of users. General users
are typically assigned to these accounts and usually have limited access to system files and directories.
Root account can do everything it has all possible permisions (# in the prompt)
The system creates a lot of accounts when processes are launched
To know why a system account is created you can try killing a process or deleting an account and see the
result !
We can show system accounts , see priviliges , ...
In the course , accounts we'll manage are root and users accounts.
Linux was created with the capacity of managing different users.
Problems we can face :
Security
Ressources management
Permissions management (Privacy)
Interupt handling
Groups (Instead of giving each user priviliges , create a group and add users to have the same
priviliges)

User group

1. Groups are collections of users. creating and managing groups is one of the simplest ways to deal with
multiple users simultaneously, especially when dealing with permissions.
2. Permissions are assigned to a collection of users who are organized into logical groups wih identical
permissions.
A group can be modified , users can be moved from a group to another.
A user can belong to several groups. (The user will have the Union)
3. Admins can manage permissions for an entire user group instead of managing individual user accounts.

User account properties

Username
You cannot start with a number, use spaces
We have a specific policy to choose usernames
This policy is defined as a regular expression
UID (User ID)
First user ID assigned by the machine is 1000 and it keeps incrementing
IDs < 1000 are system accounts
0 is root ID
GIDs (Group IDs)
You can have different group IDs because a user can belong to different groups
Home directory
By default /home/username/ (You can modify)
Default shell
You can change the shell
Password
Protecting your account to avoid other users to access your data

How user management works ?

Linux stores user and group data in specific files and directories
Theses files & directories contain :
User account info
User passwords
Group configurations
System administrators can interact with these files to control and modify user and group settings in Linux
In the begining users were modifying these files to modify permissions thats why root user is an
expert user
Before modifying these files you must be aware of the risk
To modify permissions without modifying these files you have to use commands
There are several commands to modify these properties and configurations
Passwords are hashed, it is considered that it's not possible to recover hashed passwords for NOW
The main files and directories for storing user data in Linux include :
1. /etc/passwd contains a list of user accounts and the corresponding info redeable by most users by
only root and sudo accounts can add/remove users and modify user data.
2. /etc/group contain a list of user groups. Each line in the file represents a group and displays the
group name , GID and group members.
3. /etc/sudoers specfies which users have elevated permissions (Users that can run sudo command) ,
on which machines and for which directories. Admins can use this file to configure permissions for
users and groups to use the sudo command.
4. /etc/shadow stores encrypted User password information and other password-related data such as
the password expiration date, last change date, and account expiration date.
5. /etc/gshadow stores encrypted group password information and other password-related data such
as the password expiration date, last change date, and account expiration date.
6. /etc/skel contains default configuration scripts and templates such as .bashrc and bash_profile. The
templates are copied to the user's home directory when a new user is created.
7. /etc/[Link] contains system wide user account policy settings like poassword assigning policy.
System administrators can refer to and modify this file to enforce specific security and user
management rules.
Where can we define group permissions ??
=> What is the purpose of giving permissions ??
=> Security of files
=> Permissions are defined in the ressources
Only file owner and root user can modify ressources files (You can decide if it's seen or hidden, modified
or not by who ...)

Commands

Many ways to find user account details and login details in Linux:
id - show user and groups IDs id usrnm
groups - view user group membership groups usrnm
finger - show user information finger usrnm
getent - fetch user info system database getent passwd usrnm
grep - search for patterns or specific text in files grep usrnm /etc/passwd
lslogins - displays user information in linux lslogins -u
users - list current logged-in Users on Linux users
cat - List all users cat /etc/passwd
who - show information of currently logged-in users who -u
last - Show most recent login session last
lastb - show failed login attempts lastb

Create user (useradd/adduser)


The useradd command s used to create a new user in linux. it requires root or sudo priviliges.
Sudo useradd test_account
==> The system does not need any information
The adduser command in an interactive command
The command automatically creates a home directory for the user , sets a default shell and prompts the
user to enter a password ..
Sudo adduser test_content

Modify default user settings (usermod)

The usermod command in Linux is used to modify various attributes of an existing user account
-d changes the home directory
-s changes default shell
-e sets expiry date
-c adds commands to user entry
-u changes the id
-aG adds adds the user to supplementary groups without removing existing group membership

Delete user (userdel)

The userdel command removes a user from the /etc/passwd file.


sudo userdel test_account
to remove all related files from system
sudo userdel -r test_account

How to add members to a group

sudo adduser test_acc test_group

How to remove members from a group

sudo deluser tes_acc test_grp

Lecture 6
General Notes

Even a screen is considered as a file.


French name of "Computer Science" is more meaningful "Informatique"
Everything in Computer Science is about DataFocus on practical aspects not theorical ones.
Next Week : Shell programming (Scripts)
We will learn to create dynamic and static libraries.

Linux File System

A simple description of the UNIX system, also applicale to Linux , is this :


" On a UNIX System, everything is a file; if something is not a file, it is a process."
- in linux the screen is an output device but for the system view it is a file , asking for output is like writing on
that file

Data in Linux is organized into files.


Files are organized into directories.
Directories are organized into a tree-like structure called the filesystem.
Directory is just a file which contains identifiers of the files that belong to it.
Linux : just as UNIX, makes no difference between a file and directory : A directory is just a file containing
names of other files.
Input and output devices, and generally all devices, are considered to be files, according to the system.
Programs, services , text, images and so forth are all files.
There are three basic types of files :
1. Ordinary files : an ordinary file is a file on the system that contains data, text or prgram instructions.
2. Directories : Directories store both special and ordinary files. For users familiar with windows or Mac
OS, UNIX directories are equivalent to folders.
3. Special files : Some special files provide access to hardware such as hard drives, CD-ROM drives,
modems, and Ethernet adapters.
Other special files (links) are similar to aliases or shorctucts and enable you to access a single file
using different names.
Shortcut : Raccourci : Shorter way to access something.
To list content of a directory we use the command ls
The commands ls supports -l option which would help you to get more information about the listed files.
drwxrwxr-x 2 blabla blabla 4096 Jul 3 22:14 [Link]:
Type of file Permissions (Read/Write/Exectue) 9 Chars Number of links owner group associated size in
bytes date and time of creation/last modification File or directory name

File types

1.- : Regular File


2. d: Directory
3. l : Link
5. c: Special file
6. s: Socket
7. p: Name pipe
8. b: Block device

(domain) Sockets : a special file type, similar to TCP/IP sockets, providing inter-process networking
protected by the file system's access control - biderctional communication. (Remotly from different
systems)
Canal de communication pour envoyer et recevoir.
Named piped : act more or less like sockets and form a way for processes to communicate with each
other, within the same system - Unidirectional communication. (Locally)
Block devices : typically used to describe a device that provides persistent data storage such as
traditional hard drive or an SSD.

9. Nothing : Regular file.


10. / : Directory
11. : Executable file
12. @ : Link
13. = : Socket
14. | : Named pipe
ls -F : To know the type of the file, suffixes file names with one of the characters "/*=|@ to indicate the file
type.

Metacharacters
A metacharacter has a special meaning
We use * and ?
we use * to match 0 or other charectrs

Hidden files

an invisible file is one , the first character of which is the dot or the period char (.)
UNIX programs (including the shell) use most of these files to store configuration information.
Example :
.profile - The bourne shell (sh) initialization script.
Command to list all files (including invisible) : ls -a

Permissions

Every file in UNIX has the following attributes :

Owner permissions - Determine what actions the owner of the file can perform on the file.
Group permissions - Determine what actions a user, who is a member of the group that a file belongs to,
can perform on the file.
(A file belongs to only one group , a user belongs to multiple groups)
The persmissions are advised to be like subsets ( the permissions of the others are less or equal to the
permissions of the group and the permissions of the group are less or equal to the permissions of the
owner) ,However It is possible to change that (not recommended)
Other (Wolrd) Permissions - Indicate what action all other users can perform on the file.
w: Write permission (You can delete the file)
r: Read permission (You can read the file)
x: Execute permission
To change the file or directory permissions ==> Command chmod
There are two ways to use chmod :
1. The symbolic mode :
$ chmod u-x, g=rx, o+wx, testfile // Remove x permission for user ,give r and x permissions for
group, add w and x permissions for other, g for group , u for user o for other
You must be the owner or the root to modify permission
= Overwrites permissions, so it will replace previous permissions with the newly assigned permissios
+ appends
$ ls -l
test file -rw-r-xrwx 1 armood users 1024 Nov 2 00:10 testfile
2. The Absolute mode :
We have 9 characters each one is considered as a flag
If it is 1 it means it is enabled(set) , 0 means disabled(unset).
For each type of permission we have 7 possiblities (000 to 111)
$ chmod 743 testfile //7 is 111 so it gives w,r,x permissions for owner, 4 is 100 so it gives r
permission for group, 3 is 011 so it gives w, x permissions.
We need to note that writing 2 digit numbers or even one digit is possible( 10 will be recognised as
010, 5 as 005)
in the binary format, we can only set the permissions, we cannot append or remove a permission
since it is availabe in the binary format
$ ls -l
test file -rwxr---wx 1 armood users 1024 Nov 2 00:10

The owner and the group


chown - The chown command stands for "change owner" and is used to change the owner of a file.
chgrp - The chgrp command stands for "change group" and is used to change the group of a file
A default group created with the same username once a user account is created.
Every file created at first, it is asociated to the default group of the user
Each file can belong to ONE group , a user can belong to MULTIPLE groups at same time.
In the very recent distributions of linux, we have more sophisticated linux commands and options.

Linux File System Layout

The tree of the file systems starts at the trunk or slash, indicated by a forward slash / the root.
This directory , containing all underlying directories and files, is also called the root directory or "the root"
of the file system.
Make a difference between the root directory / & the root user home directory /root/
/ directory : The directory which is the root of your system , every dir is a subdir of this one.
Root home directory : a directory that the root uses to store its own files.
Root user : The super user that can do whatever he want in the system (check Lecture 5)
Main directories content :
/bin : common programs, shared by the system, the system administrator and the users.
/boot : The startup files and the kernel
/dev : Contains references to all the CPU peripheral hardware, which are represented as files with special
properites.
/etc : Most important system configuration files are in /etc, this directory contains data similar to those in
the control panel in windows.
/home : Home directories of the common users.
/lib : Library files, includes files for all kinds of programs needed by the system and the users.
/lost+found Files that were saved during failures are here
/mnt : Standard mount point for external file systems, e.g.a CD-ROM.
/root : The home directory of the root user
/media : Standard mount point for removable media like CD-ROMs, floppy disks, etc
/usr : Programs, librairies, documentation
/sbin : Programs for use by the systel and the system administrator
/tmp : Temporary space for use by the sysytem , cleaned upon reboot.
/var : Storage for all variable files and temporary files created bu ysers, such as log files, the mail
queue....

Use man hier to know the exact description of your system tree.

Lecture 7
Midterm Exam
- Midterm will be online.
- Make sure to bring your computer.
- If you have a problem with your computer , tell Mr Berrani before exam.
- Midterm will be QCM + Some open questions in which we'll have to write.
- There's 2 exams, each student has an identifier which will decide the exam
- Identifier thing is related to the app well be using in midterm
- Your exam will be decided based on your sit.
- There are 60 questions , each question has a timer.
PS : I am not very sure about this.

General Notes

In the next lab, well have a part about partitions.

/dev and /media and /mnt

/dev is essential to the operating system, and it cannot be removed.


/dev contains special files (device files) corresponding to physical devices or system components.
A device file is an interface to a device driver
/media and /mnt are only a placeholder directories; removing them will not influence the OS core
operation but might cause errors with certain applications.
For example : /dev contains a referece to physical CD-ROM drive, /mnt might contain a subdirectory
through which you can access the iles stored on the disc inserted to the same CD-ROM drive
In some distributions we have only mnt.
There is a difference between /mnt and /media (which i couldn't understand)

The partitions

Storage is organized as a set of partitions.


Linux uses more than one partition on the same disk.
One of the goals of having different partitions is to acheive higher data security in case of disaster.
Partitioning a disk allows the disk to be regarded as a group of independent storage areas.
Partitions also make backups easier and help to restrict and confine potential problem areas.
BASICALLY :
Security
Organization
Backup
We dont have to bakup system data, in case of problem just reinstall from scratch
Normally, only backup config files.
If you want to encrypt data which is costly and increasing access time so the system becomes slow, you
can do it only for sensitive data (specific partition for this data and only this one should be encrypted) so
system files wont be encrypted.
By deviding the hard-disk in partitions, data can be grouped and separated.
When an accident occurs :
Only the data in the partition that got the hit will be damaged.
The data on the other partitions will most likely survive.
Hard disk is not infinte and one of your duties administrator is managing the available finite space.
For instance, a simple way to restrict the total storage area or disk where users can store their
personal files is to create a separate partition for the users' home directory (quotas also can be
used).

There are two kinds of major partitions on a Linux system :

1. data partition : normal linux system data, including the root partition containing all the data to start up and
run the system.
2. swap partition : expansion of the computer's physical memory , extra momory on hard disk.
Virtual data : when physical memory is full , system will add memory using the disk virtually

Most linux systems use fdisk at installation time to set the partition type.
The division of hard disks into partitions is determined by the system administrator.
When choosing a disk to be expaned, we choose the faster one.
In file system, we can have different format (Windows we have NTFS, FAT32, ...)
Format in Linux well be expalined in the lab :)
Partition once formated you lose everything.

The file system in Reality

In a file system , a file is represented by an inode.


inode : a kind of serial number containing information about the actual data that makes up the file; to
whom this file belongs , and where is it located.
Physical location (The pointer to the data in the disk) is needed by commands that print it like more.
Each inode describes a data structure on the hard disk, storing the properties of a file including the
physical location of the file data.
When a hard disk is initialized to accept data storage, usually during the initial system installation process
or when adding extra disks to an existing system, a fixed number of inodes per partition is created.
This number will be the maximum amount of files, of all types (including directories, special files, links,
etc) that can exist at the same time on the partition.
We typically count on having 1 inode per 2 to 8 kilobytes of storage.
If in a program you ask to read from a file and the full path is provided, and u explain to ur pl whether
youre reading or writing ,the system will check the permissions (w,r,x) through the inode
If you dont have the right to write or read you cant even open it and youll get an error message.
You can create a file with one user, log out, create a program in other user session , youll see
that u are not able to open it unles youre a super user (root)
inode is like a class in which you have some properties + the pointer to the data in the disk.
You can consider inodes as a set of ressources.
A part of a disk is reserved for information about files like inodes.
When formating a partition , you create a large table of inodes, one data is being created inodes are
assigned.
Capacity/2KB to get the maximum number of inodes == max num of files.
WHEN IT IS NOT A FILE IT IS A PROCESS.
Inodes are stored as system data, if you want to read this data you have to read physically the content of
the disk.
At the time a new file is created, it gets a free inode.
The inode contains the following information :
Owner and group owner of the file
File type
permissions of the file
Date and time of creation, last read and change
Date and time this inofmartion has been changed in the inode
Number of links to this file
File size
An address defining the actual location of the file data.
The information appart last one are the one we get using ls -l
To recover the data, powerfull softwares will check all storage devices, youll lose all the names.
Files that are deleted from long time are harder to recover because they might have been
overwritten.
The best way to protect data is to create backups.
Removing a file will only declare the inode as free but the file is still present in the system.
In this case the data is in the system untill you write another file in its place.
if the inode is used for another file, the file is still here but there's no way to find it so you need to
check all your disk thats why you can find the file but not the name.
These recovery softwares are very expensive because of this, even when using it you still have
to do it manually and check each part of your system.
When this problem happens to you, IT HAPPENS ONCE cuz youll use backups more frequently
It happened to Mr Berrani in 2019 he lost 3 months work (idk why did i write this)
When backing up you add the difference , edited added and deleted files.
There are tools to do it.
Overwrting files is related to names, sizes and last time of modification.
files with similar names, sizes and last time of modification they are statistically identical.
To make sure that a file is completely erased you have to overwrite it.
When Mr Berrani worked for a company in Europe they had a software that write 0s
over everything then they give the computers to schools and people in need (Same idk
why)
Mr Berrani said that it will 100% happen to us once and it is okay , the second time it is
completely our fault.
The only information not included in an inode, in the file name and directory.
These are stored in the special directory files.
By comparing file names and inode numbers, the system can make up a tree-structure that the user
understand
User can display inode numbers using the command : ls -i and ls -il (For a better reading)
inode have their own separate space on the disk.
Why do we different directories with the same inode ???
We should have one inode with one directory to distinguish them so ???
In linux, different directories are in different partitions even if they appear in same directory , even
the system is stored in different partitions , so they can have the same id but in different
partitions
Use df file_name to know the partition a file is stored in
Moving a file from a partition to another assigns a new inode to it
The numbers shown when using ls -l represent the id of the inode

The path

A path : the way to follow in the tree structure to reach a given file.

1. Absolute path (/usr/share/aclocal/pkg.mp4) :


- Make no assumptions about
- Always begins from the absolute start of your hard drive and describes every step you must take through
te filesystem to end up at the taget location
2. Relative path (../dir/[Link]) :
- System makes assumptions about the .. (couldnt write everything)
- Relative to the current directory
- the locations of a file or directory in relation to the current working dir

Links

A link is nothing more than a way of matching two or more files names to the same set of file data.
It is a shortcut.
We have 2 kinds of links
1. Hard link : Associate two or more file names with the same inode. Hard links share the same data
blocks on the hard disks, while they continue to behave as independent files.
2. Soft link or symbolic link : a small file that is a pointer to another file. A symbolic link contains the path
to the target file instead of physical location on the hard disk.
Removing hard link i have another link the data is completely protected but if we have a soft link and the
file is removed it will useless and points for nothing and still exist in the system.
Removing all hard links and the original file means you removed the data.
using ls -l we have the number of links and ls -ln to know their types.

Lecture 8
Last week session ==> This Saturday (We'll discuss the aswers of the midterm)
You'll get your grades in the lab sessions

Processes

Whenever you issue a command in Linux, it creates or starts a new process


In simple terms :
A process is an instance of a running program
A process is a program in execution
When a process is started, its either created by a clone of an existing process or loaded from a binary
executable file.
A process can create an other process (Child process) as a clone.
You can create another terminal and launch another process.
A process is always created by another process (Parent process).
We have a hiarechy in processes.
When the parent process is killed, all the children processes are killed too.
Sometimes we can have a child process while the parent is killed.
Only way to solve this problem : reboot the machine.
This type of process is called The Zombie
The operating system tracks processes through a five-digit ID number known as the PID (The Process ID)
At any point of time, each process in the system has a unique ID
a PID can be reused later once the process is killed.
YOU CANNOT KILL THE ZOMBIE PROCESS (Killing a process is sending a signal to the process, in this
case the operation will fail)
The top parent is init it’s PID is 1

Process management

Linux is based on UNIX: It has been common policy to have multiple user running multiple
commands, at the same time and on the same system.
Measures have to be taken to have the CPU manage all these processes.
Functionality has to be provided so users can switch between processes.
Resource arbitration and competition between processes have to be handled
Processes will have to continue to run even when the user who started them logs out.
A process is related to users but not with sessions so even when you log out your process will
continue working.
Users need a mean to reactivate interrupted processes (Sometimes a process can take days and
weeks so you'll need to reactivate them once intrrupted)
Objective of os : Create a situation where every process can have the needed resources.
==> You can notice that these functionalities are not available in other operating systems like windows

Three types of processes

1. Interactive processes:
Initialized and controlled through a terminal session.
In other words, someone connected to the system has to start these processes.
2. Automatic (or batch) processes:
These are not connected to a terminal
These are tasks that can be queued into a spooler area, where they wait to be executed on a FIFO
(First In, First Out) basis
At certan date and time, using the command at
3. Daemons :
A program that runs continuously in the backgroun of a multitasking OS.
Most of the time, they are initialized at system startup and then wait in the background until their
service is required.
Most daemon file names ends with letter d.
Most common daemons :
httpd, mysqld, crond
Crond is using a file (Cron Tab) where you can schedule a set of tasks and the crond checks the
content of this file every minute
httpd is a process used for networking and if it receives a query from the web server it works.

Main process states

1. Running (R): Running process.


Even when you see the process in the running processes list, it doesn't mean the process is running
it may be paused
A process is running only when it uses the CPU and takes instructions.
2. Sleeping (S): Waiting for an event to complete. For instance, this could be waiting for user input or a
system resource to become available
3. Stopped (T): Thid id a process that has been stopped, usually by receiving a signal. For example, when a
user is debbuging a program, they can stop the process to inspect its current state.
4. Zombie (Z): This a terminaed process, which has finished execution but still has an entry in the process
table to report to its parent process. (It is an abnormal situation)
5. Dead (X): A dead process. It is a transient state set just before the process descriptor is deadllocated (A
moment when the process is not in the memory but still present in the list)

If you run the ps command with the l option (ps l), the 'Stat' column displays the status of all running
processes.

Diagram of Processes States

Most of the problems well study in ai are Optimization Problems.


Training a Neural Network Model is only a matter of optimization.
The response time is the time taken by a process to start and terminate by user point of view.
You can measure the exact time spent using the CPU or Networking by a program, thats called Program
Profiling.
When you need an I/O operation a system call is made and the process is waiting.
CPU resources are given to a process for a very small time interval, if the execution is not finished the os
will interrupt it and the process return to ready.
This impression of Paralilisme may not work properly when machine is not powerful and processes take
more time, we can see things freezing.
Something good with Linux is the process of creating, terminating and managing processes is very formal
and transparent

Ending Process

When a process ends normally (It is not killed or otherwise unxpectedly interrupted), the program returns
its exit status to the parent.
This exit status is a number returned by the program providing the results of the program's execution
The system of returning information upon executing a job has its origin in the C programming language in
which UNIX has been written.
Processes end also because they receive a signal. There are multiple signals that you can send to a
process. The kill command is used to send a signal to a process.

Process attributes

A process has a set of attributes which can b viewed with the ps command :
The process ID or PID.
The parent process ID or PPID
Nice Number : The degree of friendliness of this process toward other processess (not to be confused
with process priority), which is calculated based on the nice number and recent CPU usage of the
process)
Terminal or TTY: Terminal to which the process is connected.
Username of the owner (User) of the process.
The primary group of the user who started the process.
The username of the owner and his primary group defines the rights of the resources.
The parent process that doesnt have a parent process (The first process to execute when the
machine starts is innit and in most distributions it executes systemd)

Lecture 9
General notes
Lab 4 will be modified
A week will be added (2 exercices de plus tho)
The problem with Quotas will be fixed
Only way to terminate a program in an infinite loop is by killing it.
Orphan process is a normal situation, Zombie process is a abnormal situation.

Process Scheduling

Some processes are started automatically (e.g. service processes the computer needs to do its work)
Other starts manually
There are two parts in cron
Scheduling is about managing the access one critical resource (CPU)
Scheduler is a module from the operating system.
Sheduling a process (I'd like my process to start at a specific time)
Reasons of using Scheduling : Resource management, Automation, cleaning, updating, executing
dependent processes, high performance computing (Expensive, consume a lot of power) power prices
depend on day (Pour eviter les heures de pointes et regulariser l'utilisation d'electricité, Economiser
l'argent)
There are two parts in cron :

1. The cron daemon crond: Process that is automatically started started on all computers and will check its
configuration every minute to see whether it has to issue a certain task.
2. The configuration file /etc/crontab. This file is read by crond.

This file contains three different elements.


1. An indication of the time when a command should run.
2. The name of the user with whose permissions the job has to execute.
3. The command that has to be run.
Five time positions can be used to indicate when a job has to run:
Minute
Hour
Day of month
Month
Day of week
a star( * ) means every day week ....
the number 17 means every hour when it reachs the 17th minute the process will be launched. (NOT
EVERY 17 MINUTES)
10 5 3 12 * nobody /usr/bin/false
This task would start 10 minutes after 5a.m. on December 3 only.
5 * * * nobody /usr/bin/false
Run the task every minute between 5:00 a.m. and 5:59 a.m.
('*' means every)
0 5 * * * nobody /[Link]/false
Run the task at 5 a.m. every morning.

Ending Processes
A process can exit using _exit system call, this will free up the resources that process was using.
Also, when a process is ready to terminate, it lets the kernel know why it's terminating with something
called a termination status
The parent process has to acknowledge the termination of the child process : Using the wait systrem call
and that checks the termination status of the child process.
We cannot kill zombie processes because their parent process doesn't exist.
When a parent process is terminated, what happens to its children processes????
When a parent process dies before a child process :
The kernel knows that it is not going to get a wait call (when the children processes terminate)
It makes these processes "orphans"
Puts them under the care of init
init will eventually perform the wait system call for these orphans processes.
Terminals
Orginally, the word terminal was used to refer to certain physical hardware devices that were used to send
inputs to and read outputs from a computing device.
On modern-day computers, the word terminal refers to software programs known as terminal emulators.
These are programs emulate the old-day terminals on a personal computer by providin a similar loop-
based input-output interface.
In Linux, TTY (TeleTYpewriter) refers to an interface that enables access to the terminal
Image of a terminal (IBM 2741 terminal).
Image of Teleprinter used in the world war
The name of the terminal TTY is inspired from this machine.

Two types of terminals


1. Regular terminal devices (TTY): a native terminal device that you can type into and that can send output
to the system.
2. Pseudoterminal devices (PTS/PTYs): It emulates terminals with the shell terminal window.

Processes are usually bound to a controlling terminal.


For example, if you were running a program on your shell window and you closed the window, your
process would also go with it.
BUT NOT ALL PROCESSES ARE CONNECTED TO A TERMINAL!
/dev contains all the devices and pseudo devices
In linux mint, terminals devices are stored in /dev/pts
We can write from a terminal in another one. (echo "hello" > /dev/ttys001)
ps, ps x to get all processes or to get all the processes with connected terminals.

ls /dev
ls -l
ls /dev/pts
echo "good morning" > /dev/pts/1

Creating processes in C language


fork()
exec()
Both are used to create a process.
Processes are like a tree, fork is like creating a child but in this case the child is just a clone of the parent.
WHY WE USEEEE THE CLONE == You'll see it in the Lab.
Threads is another thing, because threads are about programming.
In general, it is not advised to create threads using commands.

Lecture 10
General Notes
Lab 4 was modified, parts were added, problem fixed
We can modify the default permissions for the created files
Partitions problem was fixed, we create an additional partition which is real, one way to do it is increasing
the size of the disk or creating a free space by reducing the size of one of the existing ones by using the
tool gparted.
added part about using system calls using C/C++ programs to create processes
Next week lab: Shell script Programming
Today Lecture: We finish the processes part then introduction to Bash Script.
Processes with PID=0 are internal process part of the kernel that you cannot modify or kill.
If you have multiple distributions of Linux in OS, the might have the same kernel but we have multiple
copies
Bash Shell is the first one, the most famous one, the most used one, thats why bash not zshell..

Linux boot Sequence


When the computer boots, it will start a kernel.
The kernel on its turn is responsible for starting the first process, which normally is the process init
(PID=1)
This process is responsible for all other processes.
In Linux process management, there is a parent-child relationship.
Waiting for the machine to boot is like Une vache qui regarde un train passer.
The boot process can be broken down into four stages :
1. Bios Post
2. Boot Loader (GRUB2)
3. Kernel Initialization
4. INIT Process (Systemd)
What is the BIOS ?
BIOS : Basic Input/Output system.
The program the microprocessor uses to start the computer system after it is powered on.
The manufacturer of the machine is responsible of adding this program to the machine.
We cannot modify it because it is stored in OnlyRead Memory.
If you dont have BIOS, you cannot start the machine.
It also manages data flow between the computer's operating system (OS) and attached devices,
such as the hard disk, video adapter, keyboard, mouse and printer.
BIOS comes included with computers, as firmware on a chip on the motherboard.
Firmware : A software that provides low-level control of computing device hardware.

1. BIOS Post :
The first stage, called BIOS POST has very little to do with Linux itself.
POST stand for Power On Self Test.
In this stage, BIOS runs a POST test to ensure the hardware components that are very attached to
the device are functioning correctly.
If POST fails, the computer may not be operable and the system will not proceed to the next stage of
the boot process.
BIOS cannot be changed but there are parameters.
We can change the order in the sequence, the time, the cpu speed(Overclocking), another more
important parameter we can modify is ... THE PASSWORD
It is important to modify the password because if you have a machine and you put all this security
configurations but you forget to put a password to the BIOS anyone can access the BIOS boot from a
USB-key and access all the machine data.
If the BIOS is stored in ReadOnly memory and cannot be modified, these parameters are stored in a
ship near to the cpu powered by a small battery (CMOS)
2. Boot Loader :
The next stage is Boot Loader if the POST test is successful.
BIOS loads and executes the boot code (from the boot device) which is located in the first sector of
the hard disk.
The boot loader will provide the user with the boot screen, often with mutliple options to boot into (MS
Windows/ Ubuntu 18.04 in an example of a dual boot system).
Once the selection is made at the boot screen, boot loader loads the kernel into the memory
A popular example of the boot Loader is GRUB2 (GRand Unified Bootloader Version 2)
3. Kernel Initialization (Tarek agreed to skip this)
4. The init Process :
In most of the current Linux Distribution, the init process calls the systemd daemon.
Systemd is responsible for mounting the file systems, starting and managing system services.
To check the init system used run ls -l /bin/init if it is system then you’ll see a pointer to
/lib/system/system

Managing processes
Starting processes : background and foreground.
Killing processes kill with pkill and killall
Adjusting process priority with nice and renice
Process management using top (lab4)
multitasking and scheduling (next year operating system)

Bash Shell scripting


A Bash script is a file containing a sequence of commands that are executed by the bash program line by
line.
It allows you to perform a series of actions, such as navigatin to a specific directory, creating a folder and
launching a process using the command line.
By saving these commands in a script, you can repeat the same sequence of steps multiple times and
execute them by running the script.

Advantages of Bash Scripts


A powerful tool for atuomating system administration tasks, managing system resources, and performing
other routine taks ...
Automation : Shell script allow you to automate repetitive tasks and processes, saving time and reducing
the risk of errors that can occur with manual execution.
Portability : Shell scripts can be run on various platforms and operating systems including Unix, Linux,
MacOS, and even Windows through the use of emulators or virtual machines.
Flexibility : Shell scripts are highly customizable and can be easily modified to suit specific requirements.
Accessibility : Shell scripts are easy to write and do not require any special tools or software. They can be
modified using any text editor, and most operating systems have a built-in interpreter.
Integration : Shell scripts can be integrated with other tools and applications, such as databases web
servers, and cloud services, allowing for more complex automation.
Debbuging.

How to create and execute Bash scripts


Script naming conventions
A bash script is text file whose name ends with .sh
However, bash scripts can run perfectly fine without the ".sh" extension

Adding the shebang

the characters #! tell the system what interpreter to use to execute the script
bash scripts start with a shebang
shebang is a combination of bash # and bang! Followed by the bash shell path
this is the fist line of the script (#!/bin/bash)
shebang tells the shell to execute it via bash shell
shebang is simply an absolute path to the bash interpreter
to execute a script it must be executable

#!/bin/bash

We add "$" sign to get the value of a variable


To make a file executable we have to modify the permisssions. (Default permissions : rw-rw-r--)
We have to assign execution rights to your user using this command : chmod u+x [Link]

Executing the bash Script

The script can then be executed using any of the mentioned methods

sh [Link]
bash [Link]
./[Link]

Comments in Bash Scripting

comments start with a # in bash scripting


Any line that begins with a # is a comment and will be ignored by the interpreter.
Comments are very helpful in documenting the code, and it is a good practise to add them to help others
understand the code

# This is an example comment


# Both of these lines will be ignored by the interpreter

A comment is useful when writing a new function for example, you have to describe the purpose and the
parameters and the output
When assigning a specific value to a variable we have to explain why*
When we have a sequence of commands that are complicated we need a comment
Comments in Bash are more important than comments in C/C++ because C programs are well structured
(Auto(Self)-documentation) but with scripts it is a collection of long and complicated commands.
in exams a code without comments will get half of the mark

Variables and data type in Bash

Variables allows to store data


Variables can be used to readaccess and manipulate data throughout your script
There are no data types in bash in bash a variable is capable of storing numeric values individual
characters or strings of characters
In Bash, variable values can be set and used in the following ways :
Assign the value directly country=algeria
Assign the value based on another variable same_country=$country

Lecture 11
Variables and data types in bash

Variables allows to store data


Variables can be used to read access and manipulate data throught your script
There are no data types
in bash in bash a variable is capable of storing numeric values individual chars or strings of char
In bash variable values can be set and used in the following ways
Assign the value directly
Assign the value based on another variable
To access the value of a variable append $ to the variable name
- 2 forms:
var : simplyref erencesthevalue {var} : is also a way to reference a variable value the braces allow for a
more controlled parsing

1. when concatenating variables with other strings without introducing whitespaces


Eg: if A=”world” then echo “hello ${A}!” delimits the variable name A from the !
2. for a parameter expansions (substring extraction or length calculation)
Eg : ${A:0:3} extracts the first three chars of A

Variable naming

Variable names should start with a letter or an underscore


variable names can contain letters numbers and underscores
Variable names are case sensitive
Variable names should not contain spaces pr special chars
Use descriptive names that reflect the purpose of the variable
Avoid using reserved keywords such as (if,then,else,fi…)
-just like c++-

Echo “hello world” ; echo ‘hello world’


Will give the same output
N=10
Echo “$user earns $N” ; echo ‘$user earns $N’
1st: username earns 10
2nd: $user earns $N

useful command whereis


PATH variable contains the paths to specific programs so you can execute them without specifying the full
path
if we want to print username earns
$N
Echo “$user earns $N”
Arithmetic operations using ( (

The double parenthesis construct in bash allows for arithmetic expansion


a=$( (2+3) )
let a=2+3
In both cases the variable a=2+3 -let will treat them as integers-
( (a++) )
( (a=a+1) )
to increment
Spaces between the parentheses is important

Input and output in bash scripts

Command line arguments

In bash script or a function


1denotesthef irstargumentpassed$2denotesthesecondargumentpassedAndsoon$0nameof thescript * all the
parameters as a unique word
@alltheparametersasasequenceof separatedwords(equivalentto‵‵$1′′,′′$2′′… . # number of parameters
$! PID of the last process launched in background

Read command

#! /bin/bash
Echo “today is “ ‘date’
Echo -e “\n enter the path to directory”
Read the_path
Echo -e “\n your path has the following files and folders: “
Ls $the_path
(-e option allows you to use special chars)
Reading the user input and storing it in a variable the read command read -p prompt variable
Read -p “please enter your name” name
(read function will print the message then waits for the input)
Other parameters
Read -sn1 -p “press anu key to exit”
Echo
(n1 means that it’s waiting for only one chars is for not printing the entered key on the screen -like when
entering the password after sudo command-)

The command test

The test command will always return either true(0) or false(1)


Test expression or [ expression ]
Test ! expression -if it’s false-
Test expression -a expression (-a is and)
Test expression -o expression (-o is or)
Test $user = root [ $user = root ]
Test ! $user =root [ ! $user=root ]
[ -z $1 ] if the first argument is empty it’s equivalent to test -z $1
Test $A = hello && echo true || echo false
[ $A=hello ] && echo true || echo false
Testing integers

Test $# -gt 0 (number of arguments greater than 0)


-eq equal to
-ne not equal to
-ge greater than or equal to
-gt greater than
-le less than or equal to
-lt less than
[ 5 -eq 10 ] && echo true || echo false
( ( count >1 ) ) && echo “count is greater than 1”

Testing file types

[ -e [Link] ] && mv [Link] [Link] (if the photo exists we change it’s name)
-d it is a directory
-e the file exists in anu form
-x the file is executable
-f the file is regular file
-r the file is readable
-p the file is a named pipe
-b the file is a block device
-c the file is a character device

Lecture 12
Test advanced using [[
offers a more robust and feature rich solution for writing conditional expressions in bash
It allows enhanced string comparisons
Pattern matching using == and !=
Ex : $file == “.pl ,ends with .pl
Inside [[]] we can use && and || for logical AND and OR operations
Regex matching using =~ operator :
$a =~[0-9]+$ checks if $a contains only digits
$a =~^[0-9]$ -to check if a is only one digit-
$a =~^[0-9]*$ strings that may be empty or consist only of digits
$a =~^[0-9]+$ string non empty and consist only of digits
$FILE =~\.pl$ -to check if it ends with .pl (\ is for not interpreting the dot as a char)-

Conditional statements

If condition ; then
Statement 1
Statement 2
Fi
Or
If condition ; then
Statement
Else
Statement
Fi
Or
If condition; then
Statement
Elif condition; then
Statement
Else
Statement
Fi

Example of script :

#!/bin/bash
#prompt the user for their age
Read -p “how old are you:” age (-p option can be decomposed into echo “how old are you”
then read age)
#check if the input is a valid age
If [[ ! $age =~^[0-9]+$ ]]; then
Echo “Error: please enter a valid value”
Elif [ $age -lt 18 ]; then
Echo “you are a minor”
Else
Echo “you are an adult”

Case statements :

Case expression in
Case1)
Statement1
Statement2;;
Case2)
Statement1
Statement2;;
*)
Statemtnt1;; # -;; similar to break is c++-
Esac # reverse of case to indicate the end of the block-

If there is no match the case else statement indicated by the * will be matched this has to be the last item
in the list -default in c++-
Example:

Read -p “select a color (red,green,blue):” color


Case $color in
Red)
Echo “you have chosen red”
;;
Green)
Echo “you have chosen green”
;;
Blue)
Echo “you have chosen blue”
;;
*)
Echo “invalid”
;;
Esac
Other example

Case $age in
[1-9] | 1[0-7]) -we can use intervals-
Echo “you are a minor”
;;
[1-5][8-9] | [2-5]? | 6[0-4]
Echo “you are an adult”
;;
Esac

The for loop

For item in [LIST]


Do
[commands]
Done

The for loop can be used both in scripts and directly at the command line
Basename keyword takes only the name of file without its extension-
$* list of all the parameters separated by spaces; treated separately once each iteration
“$*” all the parameters are treated as one string
Another form :

For ((INITIALIZATION ; TEST ; STEP)) -similar to c++-


Do
Commands
Done

The while and until loops

While [condition] do -leaves when condition becomes false-


Commands
Done

Until [condition] do -leaves when condition becomes true-


Commands
Done

Example :

While read line do


Echo $line
Done < [Link] (takes its input from [Link])

Loops allow us to run one or more commands multiple times until a certain condition is met
Sometimes we may need to alter the flow of the loop and
Terminate the loop break - Break: exit completely from the loop-
Terminate only the current iteration continue - Continue: skip the current iteration-

Functions
A bash function is essentially a set of commands that can be called numerous times
The purpose of a function:
Make your bash scripts more readable
Avoid writing the same code repeatedly
Always try to keep your function names descriptive
A comment is required for each new function you define
it has do describe the function’s purpose, parameters and return statues-

(function) Function_name (){ /function keyword is optional


Commands
}
(function) Function_name () {commands;}

When calling:

Function_name() argument1 agrument2 ….

Variables scope

Global variables are variables that can be accessed from anywhere in the script regardless of the scope
In bash all variables by default are defined as global even if declared inside the function
To make it local for that function we have to use keyword local
Return value
Unlike functions in other programing languages bash functions don’t allow you to return a value when
called
The return status can be specified by using the return keyword and it is assigned to the variable $?
The return statement terminates the function

Arguments :

the same mechanism as for scripts:


The passed parameters are $1 $2 … corresponding to the position of the parameter after the function’s
name
The $0 variables is reserved for the function’s name
The $# variable holds the number of positional parameters/ arguments passed to the function

By Arslene |

You might also like