Introduction To Linux Notes
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
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
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)
CentOS Linux
Fedora Linux
SUSE Linux
Support is paid
Debian Linux
Ubentu Linux
Based on debian
Free and easy use
Linux Mint
Kali Linux
Based on debian
Used for security of networks and systems , hacking and cracking ..
Recommandation
Lecture 3
==> Good News (or No actually) : Introduction slides ONLY will be sent by the end of this week.
Definitions
Shell
Lecture 4
Script : set of commands assembled in a specific way, like a program
Commands
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
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
.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
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 floppy
==> This will show the man pages that related to the keyword "floppy"
Lecture 5
General Notes
User management
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.
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
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
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
Lecture 6
General Notes
File types
(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.
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
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 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
The partitions
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 path
A path : the way to follow in the tree structure to reach a given file.
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
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
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.
If you run the ps command with the l option (ps l), the 'Stat' column displays the status of all running
processes.
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.
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.
ls /dev
ls -l
ls /dev/pts
echo "good morning" > /dev/pts/1
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..
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)
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
The script can then be executed using any of the mentioned methods
sh [Link]
bash [Link]
./[Link]
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
Lecture 11
Variables and data types in bash
Variable naming
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-)
[ -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:
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 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 :
Example :
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-
When calling:
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 :
By Arslene |