0% found this document useful (0 votes)
89 views78 pages

Linux Notes 1

The document summarizes file and directory management in Linux. It discusses commands to list, create, display, copy, move, rename, and delete files. It also covers creating, removing, renaming directories and changing between directories. File permissions and access modes are explained, including owner, group, and other permissions for read, write and execute access for files and directories. Changing permissions with the chmod command is also mentioned.

Uploaded by

Onkar Jadhav
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)
89 views78 pages

Linux Notes 1

The document summarizes file and directory management in Linux. It discusses commands to list, create, display, copy, move, rename, and delete files. It also covers creating, removing, renaming directories and changing between directories. File permissions and access modes are explained, including owner, group, and other permissions for read, write and execute access for files and directories. Changing permissions with the chmod command is also mentioned.

Uploaded by

Onkar Jadhav
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
You are on page 1/ 78

Linux Notes chapter 2 and 3

File Management in Linux


1. Files Listing

To perform Files listings or to list files and directories ls command is used


$ls
All your files and directories in the current directory would be listed and each
type of file would be displayed with a different color. Like in the output
directories are displayed with dark blue color.
$ls -l
It returns the detailed listing of the files and directories in the current
directory. The command gives os the owner of the file and even which file
could be managed by which user or group and which user/group has the
right to access or execute which file.

2. Creating Files

touch command can be used to create a new file. It will create and open a
new blank file if the file with a filename does not exist. And in case the file
already exists then the file will not be affected.
$touch filename

3. Displaying File Contents

cat command can be used to display the contents of a file. This command
will display the contents of the ‘filename’ file. And if the output is very large
then we could use more or less to fit the output on the terminal screen
otherwise the content of the whole file is displayed at once.
$cat filename

4. Copying a File

cp command could be used to create the copy of a file. It will create the new
file in destination with the same name and content as that of the file
‘filename’.
$cp source/filename destination/
5. Moving a File

mv command could be used to move a file from source to destination. It will


remove the file filename from the source folder and would be creating a file
with the same name and content in the destination folder.

$mv source/filename destination/

6. Renaming a File

mv command could be used to rename a file. It will rename the filename to


new_filename or in other words, it will remove the filename file and would be
creating a new file with the new_filename with the same content and name
as that of the filename file.
$mv filename new_filename

7. Deleting a File

rm command could be used to delete a file. It will remove the filename file
from the directory.
$rm filename

Unix / Linux - Directory Management

A directory is a file the solo job of which is to store the file names and the related
information. All the files, whether ordinary, special, or directory, are contained in
directories.
Unix uses a hierarchical structure for organizing files and directories. This structure
is often referred to as a directory tree. The tree has a single root node, the slash
character (/), and all other directories are contained below it.

Home Directory
The directory in which you find yourself when you first login is called your home
directory.
You will be doing much of your work in your home directory and subdirectories that
you'll be creating to organize your files.
You can go in your home directory anytime using the following command −
$cd ~
$
Here ~ indicates the home directory. Suppose you have to go in any other user's
home directory, use the following command −
$cd ~username
$
To go in your last directory, you can use the following command −
$cd -
$

Creating Directories
We will now understand how to create directories. Directories are created by the
following command −
$mkdir dirname
Here, directory is the absolute or relative pathname of the directory you want to
create. For example, the command −
$mkdir mydir
$
Creates the directory mydir in the current directory. Here is another example −
$mkdir /tmp/test-dir
$
This command creates the directory test-dir in the /tmp directory.
The mkdir command produces no output if it successfully creates the requested
directory.
If you give more than one directory on the command line, mkdir creates each of the
directories. For example, −
$mkdir docs pub
$
Creates the directories docs and pub under the current directory.

Removing Directories
Directories can be deleted using the rmdir command as follows −
$rmdir dirname
$
Note − To remove a directory, make sure it is empty which means there should not
be any file or sub-directory inside this directory.
You can remove multiple directories at a time as follows −
$rmdir dirname1 dirname2 dirname3
$
The above command removes the directories dirname1, dirname2, and dirname3, if
they are empty. The rmdir command produces no output if it is successful.
Changing Directories
You can use the cd command to do more than just change to a home directory. You
can use it to change to any directory by specifying a valid absolute or relative path.
The syntax is as given below −
$cd dirname
$
Here, dirname is the name of the directory that you want to change to. For example,
the command −
$cd /usr/local/bin
$
Changes to the directory /usr/local/bin. From this directory, you can cd to the
directory /usr/home/amrood using the following relative path −
$cd ../../home/amrood
$

Renaming Directories
The mv (move) command can also be used to rename a directory. The syntax is as
follows −
$mv olddir newdir
$
You can rename a directory mydir to yourdir as follows −
$mv mydir yourdir
$

The directories . (dot) and .. (dot dot)


The filename . (dot) represents the current working directory; and the filename
.. (dot dot) represents the directory one level above the current working directory,
often referred to as the parent directory.
If we enter the command to show a listing of the current working directories/files and
use the -a option to list all the files and the -l option to provide the long listing, we
will receive the following result.
File Management :
File management system calls handle file manipulation jobs like creating a
file, reading, and writing, etc. The Linux System calls under this are open(),
read(), write(), close().
 open():
 It is the system call to open a file.
 This system call just opens the file, to perform operations
such as read and write, we need to execute different
system call to perform the operations.
 read():
 This system call opens the file in reading mode
 We can not edit the files with this system call.
 Multiple processes can execute the read() system call on
the same file simultaneously.
 write():
 This system call opens the file in writing mode
 We can edit the files with this system call.
 Multiple processes can not execute the write() system call
on the same file simultaneously.
 close():
 This system call closes the opened file.

Unix / Linux - File Permission / Access


Modes
In this chapter, we will discuss in detail about file permission and access modes in
Unix. File ownership is an important component of Unix that provides a secure
method for storing files. Every file in Unix has the following attributes −
 Owner permissions − The owner's permissions determine what actions the
owner of the file can perform on the file.
 Group permissions − The group's permissions determine what actions a
user, who is a member of the group that a file belongs to, can perform on the
file.
 Other (world) permissions − The permissions for others indicate what action
all other users can perform on the file.

The Permission Indicators


While using ls -l command, it displays various information related to file permission
as follows −
$ls -l /home/amrood
-rwxr-xr-- 1 amrood users 1024 Nov 2 00:10 myfile
drwxr-xr--- 1 amrood users 1024 Nov 2 00:10 mydir
Here, the first column represents different access modes, i.e., the permission
associated with a file or a directory.
The permissions are broken into groups of threes, and each position in the group
denotes a specific permission, in this order: read (r), write (w), execute (x) −
 The first three characters (2-4) represent the permissions for the file's owner.
For example, -rwxr-xr-- represents that the owner has read (r), write (w) and
execute (x) permission.
 The second group of three characters (5-7) consists of the permissions for the
group to which the file belongs. For example, -rwxr-xr-- represents that the
group has read (r) and execute (x) permission, but no write permission.
 The last group of three characters (8-10) represents the permissions for
everyone else. For example, -rwxr-xr-- represents that there is read (r) only
permission.

File Access Modes


The permissions of a file are the first line of defense in the security of a Unix system.
The basic building blocks of Unix permissions are the read, write,
and execute permissions, which have been described below −

Read
Grants the capability to read, i.e., view the contents of the file.

Write
Grants the capability to modify, or remove the content of the file.
Execute
User with execute permissions can run a file as a program.

Directory Access Modes


Directory access modes are listed and organized in the same manner as any other
file. There are a few differences that need to be mentioned −
Read
Access to a directory means that the user can read the contents. The user can look
at the filenames inside the directory.

Write
Access means that the user can add or delete files from the directory.
Execute
Executing a directory doesn't really make sense, so think of this as a traverse
permission.
A user must have execute access to the bin directory in order to execute the ls or
the cd command.

Changing Permissions
To change the file or the directory permissions, you use the chmod (change mode)
command. There are two ways to use chmod — the symbolic mode and the absolute
mode.
Using chmod in Symbolic Mode
The easiest way for a beginner to modify file or directory permissions is to use the
symbolic mode. With symbolic permissions you can add, delete, or specify the
permission set you want by using the operators in the following table.
Sr.No. Chmod operator & Description

1
+
Adds the designated permission(s) to a file or directory.

2
-
Removes the designated permission(s) from a file or directory.

3
=
Sets the designated permission(s).

Here's an example using testfile. Running ls -1 on the testfile shows that the file's
permissions are as follows −
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on the testfile,
followed by ls –l, so you can see the permission changes −
$chmod o+wx testfile
$ls -l testfile
-rwxrwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod u-x testfile
$ls -l testfile
-rw-rwxrwx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod g = rx testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile
Here's how you can combine these commands on a single line −
$chmod o+wx,u-x,g = rx testfile
$ls -l testfile
-rw-r-xrwx 1 amrood users 1024 Nov 2 00:10 testfile

Using chmod with Absolute Permissions


The second way to modify permissions with the chmod command is to use a number
to specify each set of permissions for the file.
Each permission is assigned a value, as the following table shows, and the total of
each set of permissions provides a number for that set.

Number Octal Permission Representation Ref


0 No permission ---

1 Execute permission --x

2 Write permission -w-

3 Execute and write permission: 1 (execute) + 2 (write) = 3 -wx

4 Read permission r--

5 Read and execute permission: 4 (read) + 1 (execute) = 5 r-x

6 Read and write permission: 4 (read) + 2 (write) = 6 rw-

7 All permissions: 4 (read) + 2 (write) + 1 (execute) = 7 rwx

Here's an example using the testfile. Running ls -1 on the testfile shows that the file's
permissions are as follows −
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on the testfile,
followed by ls –l, so you can see the permission changes −
$ chmod 755 testfile
$ls -l testfile
-rwxr-xr-x 1 amrood users 1024 Nov 2 00:10 testfile
$chmod 743 testfile
$ls -l testfile
-rwxr---wx 1 amrood users 1024 Nov 2 00:10 testfile
$chmod 043 testfile
$ls -l testfile
----r---wx 1 amrood users 1024 Nov 2 00:10 testfile

Changing Owners and Groups


While creating an account on Unix, it assigns a owner ID and a group ID to each
user. All the permissions mentioned above are also assigned based on the Owner
and the Groups.
Two commands are available to change the owner and the group of files −
 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.

Changing Ownership
The chown command changes the ownership of a file. The basic syntax is as follows

$ chown user filelist
The value of the user can be either the name of a user on the system or the user id
(uid) of a user on the system.
The following example will help you understand the concept −
$ chown amrood testfile
$
Changes the owner of the given file to the user amrood.
NOTE − The super user, root, has the unrestricted capability to change the ownership
of any file but normal users can change the ownership of only those files that they
own.

Changing Group Ownership


The chgrp command changes the group ownership of a file. The basic syntax is as
follows −
$ chgrp group filelist
The value of group can be the name of a group on the system or the group ID
(GID) of a group on the system.
Following example helps you understand the concept −
$ chgrp special testfile
$
Changes the group of the given file to special group.

Process states and Transitions in a


UNIX Process
Process

A process is an instance of a program in execution. A set of processes


combined together make a complete program.
There are two categories of processes in Unix, namely
 User processes: They are operated in user mode.
 Kernel processes: They are operated in kernel mode.

Process States

The states that a Process enters in working from start till end are known as
Process states. These are listed below as:
 Created-Process is newly created by system call, is not ready to
run
 User running-Process is running in user mode which means it is a
user process.
 Kernel Running-Indicates process is a kernel process running in
kernel mode.
 Zombie- Process does not exist/ is terminated.
 Preempted- When process runs from kernel to user mode, it is said
to be preempted.
 Ready to run in memory- It indicated that process has reached a
state where it is ready to run in memory and is waiting for kernel to
schedule it.
 Ready to run, swapped– Process is ready to run but no empty
main memory is present
 Sleep, swapped- Process has been swapped to secondary storage
and is at a blocked state.
 Asleep in memory- Process is in memory(not swapped to
secondary storage) but is in blocked state.
The numbers indicate the steps that are followed.

Process Transitions

The working of Process is explained in following steps:


1. User-running: Process is in user-running.
2. Kernel-running: Process is allocated to kernel and hence, is in
kernel mode.
3. Ready to run in memory: Further, after processing in main
memory process is rescheduled to the Kernel.i.e.The process is not
executing but is ready to run as soon as the kernel schedules it.
4. Asleep in memory: Process is sleeping but resides in main
memory. It is waiting for the task to begin.
5. Ready to run, swapped: Process is ready to run and be swapped
by the processor into main memory, thereby allowing kernel to
schedule it for execution.
6. Sleep, Swapped: Process is in sleep state in secondary memory,
making space for execution of other processes in main memory. It
may resume once the task is fulfilled.
7. Pre-empted: Kernel preempts an on-going process for allocation of
another process, while the first process is moving from kernel to
user mode.
8. Created: Process is newly created but not running. This is the start
state for all processes.
9. Zombie: Process has been executed thoroughly and exit call has
been enabled.
The process, thereby, no longer exists. But, it stores a statistical
record for the process.
This is the final state of all processes.

Processes in Linux/Unix
A program/command when executed, a special instance is provided by the
system to the process. This instance consists of all the services/resources
that may be utilized by the process under execution.
 Whenever a command is issued in Unix/Linux, it creates/starts a
new process. For example, pwd when issued which is used to list
the current directory location the user is in, a process starts.
 Through a 5 digit ID number Unix/Linux keeps an account of the
processes, this number is call process ID or PID. Each process in
the system has a unique PID.
 Used up pid’s can be used in again for a newer process since all
the possible combinations are used.
 At any point of time, no two processes with the same pid exist in the
system because it is the pid that Unix uses to track each process.

Initializing a process
A process can be run in two ways:
Method 1: Foreground Process : Every process when started runs in
foreground by default, receives input from the keyboard, and sends output to
the screen. When issuing pwd command
$ ls pwd
Output:
$ /home/geeksforgeeks/root
When a command/process is running in the foreground and is taking a lot of
time, no other processes can be run or started because the prompt would not
be available until the program finishes processing and comes out.

Method 2: Background Process: It runs in the background without


keyboard input and waits till keyboard input is required. Thus, other
processes can be done in parallel with the process running in the
background since they do not have to wait for the previous process to be
completed.
Adding & along with the command starts it as a background process
$ pwd &
Since pwd does not want any input from the keyboard, it goes to the stop
state until moved to the foreground and given any data input. Thus, on
pressing Enter:
Output:
[1] + Done pwd
$
That first line contains information about the background process – the job
number and the process ID. It tells you that the ls command background
process finishes successfully. The second is a prompt for another
command.

Tracking ongoing processes


ps (Process status) can be used to see/list all the running processes.
$ ps

PID TTY TIME CMD


19 pts/1 00:00:00 sh
24 pts/1 00:00:00 ps
For more information -f (full) can be used along with ps
$ ps –f

UID PID PPID C STIME TTY TIME CMD


52471 19 1 0 07:20 pts/1 00:00:00f sh
52471 25 19 0 08:04 pts/1 00:00:00 ps -f
For single-process information, ps along with process id is used
$ ps 19

PID TTY TIME CMD


19 pts/1 00:00:00 sh
For a running program (named process) Pidof finds the process id’s (pids)
Fields described by ps are described as:
 UID: User ID that this process belongs to (the person running it)
 PID: Process ID
 PPID: Parent process ID (the ID of the process that started it)
 C: CPU utilization of process
 STIME: Process start time
 TTY: Terminal type associated with the process
 TIME: CPU time is taken by the process
 CMD: The command that started this process
There are other options which can be used along with ps command :
 -a: Shows information about all users
 -x: Shows information about processes without terminals
 -u: Shows additional information like -f option
 -e: Displays extended information
Stopping a process:
When running in foreground, hitting Ctrl + c (interrupt character) will exit the
command. For processes running in background kill command can be used if
it’s pid is known.
$ ps –f

UID PID PPID C STIME TTY TIME CMD


52471 19 1 0 07:20 pts/1 00:00:00 sh
52471 25 19 0 08:04 pts/1 00:00:00 ps –f

$ kill 19
Terminated
If a process ignores a regular kill command, you can use kill -9 followed by
the process ID.
$ kill -9 19
Terminated
Other process commands:
bg: A job control command that resumes suspended jobs while keeping
them running in the background
Syntax:
bg [ job ]
For example:
bg %19
fg: It continues a stopped job by running it in the foreground.
Syntax:
fg [ %job_id ]
For example
fg 19
top: This command is used to show all the running processes within the
working environment of Linux.
Syntax:
top
nice: It starts a new process (job) and assigns it a priority (nice) value at the
same time.
Syntax:
nice [-nice value]
nice value ranges from -20 to 19, where -20 is of the highest priority.
renice : To change the priority of an already running process renice is used.
Syntax:
renice [-nice value] [process id]
df: It shows the amount of available disk space being used by file systems
Syntax:
df
Output:
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/loop0 18761008 15246876 2554440 86% /
none 4 0 4 0% /sys/fs/cgroup
udev 493812 4 493808 1% /dev
tmpfs 100672 1364 99308 2% /run
none 5120 0 5120 0% /run/lock
none 503352 1764 501588 1% /run/shm
none 102400 20 102380 1% /run/user
/dev/sda3 174766076 164417964 10348112 95% /host
free: It shows the total amount of free and used physical and swap memory
in the system, as well as the buffers used by the kernel
Syntax:
free
Output:
total used free shared buffers
cached
Mem: 1006708 935872 70836 0 148244
346656
-/+ buffers/cache: 440972 565736
Swap: 262140 130084 132056

Types of Processes
1. Parent and Child process : The 2nd and 3rd column of the ps –f
command shows process id and parent’s process id number. For
each user process, there’s a parent process in the system, with
most of the commands having shell as their parent.
2. Zombie and Orphan process : After completing its execution a
child process is terminated or killed and SIGCHLD updates the
parent process about the termination and thus can continue the
task assigned to it. But at times when the parent process is killed
before the termination of the child process, the child processes
become orphan processes, with the parent of all processes “init”
process, becomes their new pid.
A process which is killed but still shows its entry in the process
status or the process table is called a zombie process, they are
dead and are not used.
3. Daemon process : They are system-related background processes
that often run with the permissions of root and services requests
from other processes, they most of the time run in the background
and wait for processes it can work along with for ex print daemon.
When ps –ef is executed, the process with ? in the tty field are
daemon processes.

Linux signals
On Unix-like operating systems such
as Linux, signals are software interrupts. They provide a
way for the user (or a process) to directly communicate with
a process.

Software may be programmed to respond intelligently to a wide


array of signals, and certain signals cause processes to behave in a
standardized, predefined way at the kernel level.

Description
Process signals were developed as part of UNIX in the 1970s. They
are used on all modern Unix-like operating systems,
including Linux, BSD, and macOS X.

When a signal is sent to a process, the operating system interrupts


the normal flow of the process execution and delivers the
notification. If the process has previously registered a way to handle
that particular signal, that routine is executed, otherwise the system
executes the default signal handler.

Signals can be sent with the kill command, which is named for its
default signal (SIGKILL) that instructs the OS to forcefully
terminate a process before doing anything else.

Signal names are commonly abbreviated without their SIG prefix,


e.g., "KILL", including in the command arguments of kill.
Finding system-specific signals
Signals are defined in the system library signal.h. To view the
signals used by your operating system, open a terminal and
run man signal or man 7 signal.

Signals in Linux
Signal Number Description

SIGHUP 1 The HUP signal is sent to a process when its controlling POSIX

terminal is closed. It was originally designed to notify

a serial line drop (HUP stands for "Hang Up"). In modern

systems, this signal usually indicates the controlling

pseudo or virtual terminal is closed.

SIGINT 2 The INT signal is sent to a process by its controlling ANSI

terminal when a user wants to interrupt the process. This

signal is often initiated by pressing Ctrl+C, but on some

systems, the "delete" character or "break" key can be

used.

SIGQUIT 3 The QUIT signal is sent to a process by its controlling POSIX

terminal when the user requests that the process perform

a core dump.

SIGILL 4 Illegal instruction. The ILL signal is sent to a process ANSI

when it attempts to execute a malformed, unknown, or

privileged instruction.

SIGTRAP 5 Trace trap. The TRAP signal is sent to a process when a POSIX

condition arises that a debugger is tracing — for example,


when a particular function is executed, or when a

particular variable changes value.

SIGABRT, 6 Abort process. ABRT is usually sent by the process itself, 4.2 BSD

SIGIOT when it calls the abort() system call to signal an

abnormal termination, but it can be sent from any process

like any other signal. SIGIOT is a synonym for SIGABRT.

(IOT stands for input/output trap, a signal which

originated on the PDP-11.)

SIGBUS 7 The BUS signal is sent to a process when it causes 4.2 BSD

a bus error, such as an incorrect memory access

alignment or non-existent physical address. In Linux, this

signal maps to SIGUNUSED, because memory access

errors of this kind are not possible.

SIGFPE 8 Floating point exception. The FPE signal is sent to a ANSI

process when it executes erroneous arithmetic operations,

such as division by zero.

SIGKILL 9 Forcefully terminate a process. With STOP, this is one of POSIX

two signals which cannot be intercepted, ignored, or

handled by the process itself.

SIGUSR1 10 User-defined signal 1. This is one of two signals POSIX

designated for custom user signal handling.

SIGSEGV 11 The SEGV signal is sent to a process when it makes an

invalid virtual memory reference, or segmentation fault,

i.e., when it performs a segmentation violation.


SIGUSR2 12 User-defined signal 2. This is one of two signals POSIX

designated for custom user signal handling.

SIGPIPE 13 The PIPE signal is sent to a process when it attempts to POSIX

write to a pipe without a process connected to the other

end.

SIGALRM 14 The ALRM signal notifies a process that the time interval POSIX

specified in a call to the alarm() system function has

expired.

SIGTERM 15 The TERM signal is sent to a process to request its ANSI

termination. Unlike the KILL signal, it can be caught and

interpreted or ignored by the process. This signal allows

the process to perform nice termination releasing

resources and saving state if appropriate. It should be

noted that SIGINT is nearly identical to SIGTERM.

SIGSTKFLT 16 Stack fault. Maps to SIGUNUSED in Linux.

SIGCHLD 17 The CHLD signal is sent to a process when a child POSIX

process terminates, is interrupted, or resumes after being

interrupted. One common usage of the signal is to instruct

the operating system to clean up the resources used by a

child process after its termination without an explicit call

to the wait system call.

SIGCONT 18 Continue executing after stopped, e.g., by STOP POSIX


SIGSTOP 19 The STOP signal instructs the operating system to stop a POSIX

process for later resumption. This is one of two signals,

along with KILL that cannot be intercepted, ignored, or

handled by the process itself.

SIGTSTP 20 The TSTP signal is sent to a process by its controlling POSIX

terminal to request it to stop temporarily. It is commonly

initiated by the user pressing Ctrl+Z. Unlike SIGSTOP,

this process can register a signal handler for or ignore the

signal.

SIGTTIN 21 The TTIN signal is sent to a process when it attempts to POSIX

read from the tty while in the background. This signal can

be received only by processes under job

control. Daemons do not have controlling terminals and

should never receive this signal.

SIGTTOU 22 TTOU signal is sent to a process when it attempts to write POSIX

from the tty while in the background. The compliment

to TTIN.

SIGURG 23 The URG signal is sent to a process when a socket has 4.2 BSD

urgent or out-of-band data available to read.

SIGXCPU 24 The XCPU signal is sent to a process when it has used up 4.2 BSD

the CPU for a duration that exceeds a certain

predetermined user-settable value. The arrival of

an XCPU signal provides the receiving process a chance

to quickly save any intermediate results and to exit

gracefully, before it is terminated by the operating system

using the SIGKILL signal.


SIGXFSZ 25 The XFSZ signal is sent to a process when it grows 4.2 BSD

a file larger than the maximum allowed size.

SIGVTALRM 26 Virtual alarm clock. May be sent by the alarm() system 4.2 BSD

call. By default, this signal kills the process, but it's

intended for use with process-specific signal handling.

SIGPROF 27 Profiling alarm clock. Indicates


4.2 BSD
expiration of a timer that

measures CPU time used by the current process ("user"

time), and CPU time expended on behalf of the process by

the system ("system" time). These times may be used to

implement code profiling facilities. By default, this signal

terminates the process, but it's intended for use with

process-specific signal handling.

SIGWINCH 28 Window change. The WINCH signal is sent to a process 4.3 BSD, Sun

when its controlling terminal changes size, for instance if

you resize it in your window manager.

SIGIO, 29 Input/output is now possible. SIGPOLL is a synonym for 4.2 BSD

SIGPOLL SIGIO, and in Linux its behavior is identical to SIGURG.

SIGPWR, 30 Power failure. The PWR signal is sent to a process when System V

SIGLOST the system detects a power failure. SIGLOST is a

synonym for SIGPWR.

SIGUNUSED, 31 Unused signal. This signal is provided for compatibility System V r4

SIGSYS reasons, for example when porting software from an

operating system with different or unsupported signals in

Linux. In Linux, SIGSYS is a synonym for SIGUNUSED.


Signals not supported by Linux

The following signals may be used by other systems, such as BSD,


but are interpreted as SIGUNUSED in Linux.

SIGE MT The EMT signal is sent to a process when an emulator trap occurs. Unused in Linux.

SIGINFO The INFO signal is sent to a process when a status request is received from the controlling terminal. Unused in L

SIGLOST The LOST signal is sent to a process when a file lock is lost. Unused in Linux.

SIGSYS The SYS signal is sent to a process when it passes a bad argument to a system call. Unused in Linux.

Sending signals from the keyboard


Signals may be sent from the keyboard. Several standard defaults
are listed below. Default key combinations for sending interrupt
signals can be defined with the stty command.

Ctrl-C Send SIGINT (Interrupt). By default, this causes a process

Ctrl-Z Send SIGTSTP (Suspend). By default, this causes a process

Ctrl-\ Send SIGQUIT (Quit). By default, this causes a process to


dump the core.

Ctrl-T Send SIGINFO (Info). By default, this causes the operating


about the command. Not supported on all systems.

Real-time signals
Real-time signals are a set of signals with no predefined purpose,
for programmers to use as they want in their software. Two signal
names, SIGRTMIN and SIGRTMAX, define the minimum and
maximum signal numbers of the real-time signals. For example, the
programmer may use the signal number as SIGRTMIN+3 to refer
to the fourth real-time signal number.

Examples: sending signals


The kill command sends signals to processes. Your shell may have
a built-in version of kill, which supersedes the version installed
at /bin/kill. The two versions have slightly different options, but
basic functions are the same. The following examples may run using
either version of kill.

The process to be signaled is referred to by PID (process ID). If


you're not sure of the process ID, you can find it with
the ps command, for example ps -aux.

kill 1234

Send the KILL signal to the process with PID 1234.

kill 123 456 789

Kill three processes: PIDs 123, 456, and 789.

kill -15 1234 5678

Send signal number 15 (TERM) to processes 1234 and 5678.

kill -TERM 1234 5678

Same as the previous command.

kill -l

List all available signals. Example output:


1) SIGHUP 2) SIGINT 3) SIGQUIT 4)
SIGILL 5) SIGTRAP

6) SIGABRT 7) SIGBUS 8) SIGFPE 9)


SIGKILL 10) SIGUSR1

11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14)


SIGALRM 15) SIGTERM

16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19)


SIGSTOP 20) SIGTSTP

21) SIGTTIN 22) SIGTTOU 23) SIGURG 24)


SIGXCPU 25) SIGXFSZ

26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29)


SIGIO 30) SIGPWR

31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36)


SIGRTMIN+2 37) SIGRTMIN+3

38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41)


SIGRTMIN+7 42) SIGRTMIN+8

43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46)


SIGRTMIN+12 47) SIGRTMIN+13

48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51)


SIGRTMAX-13 52) SIGRTMAX-12

53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56)


SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61)
SIGRTMAX-3 62) SIGRTMAX-2

63) SIGRTMAX-1 64) SIGRTMAX

kill -9 -1

The special process ID -1 refers to all processes other than kill and
the system root process. This command attempts to kill (-9) every
possible process (-1) on the system. For more information, see the
documentation of kill, linked below.

Process creation
A new process is created because an existing process makes an exact copy of itself.
This child process has the same environment as its parent, only the process ID
number is different. This procedure is called forking.

After the forking process, the address space of the child process is overwritten with
the new process data. This is done through an exec call to the system.

The fork-and-exec mechanism thus switches an old command with a new, while the
environment in which the new program is executed remains the same, including
configuration of input and output devices, environment variables and priority. This
mechanism is used to create all UNIX processes, so it also applies to the Linux
operating system. Even the first process, init, with process ID 1, is forked during
the boot procedure in the so-called bootstrapping procedure.

This scheme illustrates the fork-and-exec mechanism. The process ID changes after
the fork procedure:

Figure 4-1. Fork-and-exec mechanism


There are a couple of cases in which init becomes the parent of a process, while the
process was not started by init, as we already saw in the pstree example. Many
programs, for instance, daemonize their child processes, so they can keep on
running when the parent stops or is being stopped. A window manager is a typical
example; it starts an xterm process that generates a shell that accepts commands.
The window manager then denies any further responsibility and passes the child
process to init. Using this mechanism, it is possible to change window managers
without interrupting running applications.

Every now and then things go wrong, even in good families. In an exceptional case,
a process might finish while the parent does not wait for the completion of this
process. Such an unburied process is called a zombie process.

Linux Terminate Process

In the Linux ecosystem, when we are running any application or any job. Every application or job will
run with a specific process ID or daemon or service. The process ID is nothing but a digit number.
Sometimes the job or any service may not run due to some issues like deadlock, process stuck, etc.
Due to which remaining jobs will impact coming from the same service. If such a condition may
happen, we need to kill or terminate the stuck job or process.

Syntax of Terminate Process

ps [ OPTION ] kill [ OPTION ] [ PROCESS ID ]


 ps: We can use the “ps” keyword in the syntax. It will accept the arguments as an option. As
per the provided input arguments, the “ps” command will display the information of all the
running processes in the environment.

 kill: We can use the “kill” keyword in the syntax or command to terminate the process. It will
accept the two arguments like OPTION and PROCESS ID. As per the provided input
arguments, the “kill” command will terminate the process.

 OPTION: We can provide the different flags as options that are compatible with the “ps” and
“kill” command.

 PROCESS ID: We need to provide the relevant process ID to terminate the process.

How Linux Terminate Process Works?

As we have discussed earlier, every job or application is running with a specific process ID. In the
background, we are able to get all the list of the running process in the Linux environment. Due to
some technical issues like deadlock, process or services stuck the job or application will not able to
run. Hence we need to terminate the stuck process. So the next upcoming jobs will be executed
perfectly fine.

In the Linux environment, if we need to kill the process. First, we need to identify the process and
get the relevant process id. There are different ways to get the process id from the Linux
environment like “ps” and “top”.

“ps” command.
ps -ax
“top” command.

To terminate the process, we need to use the below different killing signals in the kill command.

1. SIGHUP

 To use SIGHUP signal, we need to use the digit “1”

 It is known as the hang up signal

2. SIGINT

 To use SIGINT signal, we need to use the digit “2”

 It is known as the interrupt signal

3. SIGSTOP

 To use SIGINT signal, we need to use the digit “17, 19, 23”

 It is known as the stop signal

4. SIGTERM

 To use SIGTERM signal, we need to use the digit “15”

 It is known as the termination signal

5. SIGKILL

 To use SIGTERM signal, we need to use the digit “9”


 It is known as the kill signal

Examples to Implement Linux Terminate Process?

Following are the examples are given below:

1. Identify the Linux Process

While terminating the Linux process, it is very important to identify the running process. There are
different ways to identify the running process.

Command:

ps -aux

ps -aux | grep -i "httpd"

Output:
Explanation: As per the above command, we are able to get all the running

process information on the Linux server. From the first “ps” command, we are the

entire list down all the process (refer to screenshot 1 (a)). But it is very difficult to

identify the specific process. To overcome this condition, we need to use the “pipe

(|)” functionality and grep the data from it (refer to screenshot 1 (b)).

2. Terminate Process– With Kill Command


In termination of the Linux process, we can use the kill command. The kill

command sends an exact signal to the process. In different ways, we can trigger the

command like a direct command or via shell.

Command:

kill -9 1941

Output:
Explanation: As discussed earlier, we are having different signals in the kill

command. As per the requirement, we can use those signals. In the above “kill”

command. We are using the kill signal i.e. “9”. The process id “1941” is running in

the environment. We are terminating the “1941” process with the help of kill signal

(9).

3. Terminate Process– With pkill Command


In the Linux environment, we are having the functionality to kill the process with

the help of the process name.

Note: There is no need for a process id here.

Command:

pkill httpd

Output:
Explanation: Sometimes we don’t have time to check all process ids and

terminate the process accordingly. Hence we need functionality to kill the process

via service, process or application name. To terminate the process, we can use the

process name with pkill command. As per the below screenshot, we have used the

“https” as the process name. It will terminate all the processes running with the

same name.

4. Terminate Process– With kill all Command


We can terminate all the processes as well as the running child processes. Here, we

just need to specify the process name only.

Command:

killall httpd

Output:
Explanation: If we need to terminate all the processes like a parent as well as

child process both then we need to use the “killall” command. As per the below

screenshot, we are using the “httpd” process name in the “killall” command. It will

terminate all the parent and child processes. Once, the “killall” command will

terminate the process. The status of the service or application is in a failed state.
One Time Task Scheduling using
at Command in Linux
While working with Linux systems we preferred crontab for scheduling jobs
generally. There are another utility at command is very useful for scheduling one time
tasks. It reads commands from standard input or script/file which can be executed later
once. But we can’t use at command for any recurring tasks. For recurring tasks use
Linux crontab.

 Read This => Schedule recurring tasks with crontab on Linux

At command can be useful for shutdown system at the specified time, Taking a one-
time backup, sending email as a reminder at the specified time etc. This article will
help you to understand the working of at command with useful examples.

Commands used with at:


 at : execute commands at specified time.
 atq : lists the pending jobs of users.
 atrm : delete jobs by their job number.

1. Schedule first job using at command


Below example will schedule “sh backup.sh” command to be executed on next 9:00 A
M once.t 9:00 at 9:00 AM

at

03-23 09:00

job 3 at 2013-03-23 09:00


A backup.sh

at> ^d

job 3 at 2013-03-23 09:00


job 3 at 2013-03-23 09:00
Use ^d to exit from at prompt.
You can also use the following option to schedule a job. The below command will run
“sh backup.sh” at 9:00 in the morning.

e cho "sh backup.sh" | at


9:00 AM

2. List the scheduled jobs using atq


When we list jobs by root account using atq, it shows all users jobs in the result. But if
we execute it from a non-root account, it will show only that users jobs.

1 2013-03-23 12:00 a ro
ot
Fields description:
First filed: job id
Second filed: Job execution date
third filed: Job execution time
Last field: User name, under which job is scheduled.

3. Remove scheduled job using atrm


You can remove any at job using atrm with their job id.
4. Check the content of scheduled at job
atq command only shows the list of jobs but if you want to check what
script/commands are scheduled with that task, below example will help you.

at -c 5
In the above example, 5 is the job id.
Examples of at Command:
at midnight

The above job will execute on next 12:00 AM

nohup Command in Linux with Examples


Every command in Linux starts a process at the time of its execution, which
automatically gets terminated upon exiting the terminal. Suppose, you are
executing programs over SSH and if the connection drops, the session will be
terminated, all the executed processes will stop, and you may face a huge
accidental crisis. In such cases, running commands in the background can be very
helpful to the user and this is where nohup command comes into the
picture. nohup (No Hang Up) is a command in Linux systems that runs the
process even after logging out from the shell/terminal.
Usually, every process in Linux systems is sent a SIGHUP (Signal Hang
UP) which is responsible for terminating the process after closing/exiting the
terminal. Nohup command prevents the process from receiving this signal upon
closing or exiting the terminal/shell. Once a job is started or executed using the
nohup command, stdin will not be available to the user and nohup.out file is
used as the default file for stdout and stderr. If the output of the nohup
command is redirected to some other file, nohup.out file is not generated.
Syntax:
nohup command [command-argument ...]
Working with nohup command

1. Checking the version of Nohup:


The version of nohup command can be checked by using the following command.
$ nohup --version
Output:

2. To run a command in the foreground:


Runs the command in the foreground and redirects the command output to
the nohup.out file if any redirecting filename is not mentioned.
$ nohup bash geekfile.sh
Output:

To redirect the output to the output.txt file:


$ nohup bash geekfile.sh > output.txt
Output:

3. To run a command in the background (with ‘&’):


To run the command in the background, the ‘&’ symbol is appended at the end of
the command. After executing, it doesn’t return to the shell command prompt after
running the command in the background. It can be brought back to the foreground
with the fg command.
$ nohup bash geekfile.sh &
fg
Output:
Note: The number within square brackets represents the job id and the number
next to it is the process id.
4. To run multiple commands in the background:
nohup command can be used to run multiple commands in the background.
$ nohup bash -c 'commands'
Example:
$ nohup bash -c 'cal && ls'
Output:

Here, the output will be by default stored in nohup.out. To redirect it, type:
$ nohup bash -c 'commands' > filename.txt
Example:
$ nohup bash -c 'cal && ls' > output.txt
Output:
Chapter 3
Linux Text Editors
Linux text editors can be used for editing text files, writing codes, updating user
instruction files, and more. A Linux system supports multiple text editors. There are
two types of text editors in Linux, which are given below:

o Command-line text editors such as Vi, nano, pico, and more.


o GUI text editors such as gedit (for Gnome), Kwrite, and more.

A text editor plays an important role while coding. So, it is important to select the best
text editor. A text editor should not only be simple but also functional and should be
good to work with.

A text editor with IDE features is considered as a good text editor.

In this section, we are going to discuss the top 20 text editors for Linux

. Further, we will talk about the latest text editors and will compare them with the traditional text
editors such as Vi and nano. This will help you with selecting the editor of your choice.

1.Vi/VIM editor
Vim editor is one of the most used and powerful command-line based editor of the
Linux system. By default, it is supported by most Linux distros. It has enhanced
functionalities of the old Unix Vi editor

. It is a user-friendly editor and provides the same environment for all the Linux distros. It is also
termed as programmer's editor because most programmers prefer Vi editor.

Vi editor has some special features such as Vi modes and syntax highlighting that
makes it powerful than other text editors. Generally, it has two modes:

Command Mode: The command mode allows us to perform actions on files. By


default, it starts in command mode. In this mode, all types of words are considered as
commands. We can execute commands in this mode.

Insert Mode: The insert mode allows to insert text on files. To switch from command
mode to insert mode, press the Esc key to exit from active mode and 'i' key.

To learn more about Vi editor, visit the Vi editor with commands

.
To invoke the vi editor, execute the vi command with the file name as follows:

1. vi <file name>

It will look like below image:

2. Nano editor
Nano is a straight forward editor. It is designed for both beginners and advanced users.
It has many customization features.

Some advanced features of a nano text editor are as following:

o It has highly customizable key bindings


o It supports syntax highlighting
o It has undo and redo options
o It provides full line display on the standard output
o It has pager support to read from standard input

To open file with nano editor, execute the command as follows:

1. nano <file name>

The nano editor looks like:

In the nano editor, the useful options are given at the bottom, use the CTRL+
option to perform an operation. For example, to exit from the editor, use CTRL
+X keys. To learn more about nano editor, Visit Linux Nano Editor

.
3. Gedit editor
Gedit editor is the default editor for the GNOME desktop environment. When we open
a file, it will open with the Gedit editor. It provides straightforward functionalities like
any basic text editor. It is a lightweight editor with a straight forward user interface. It
was publicly released in the year 2000 with a GNOME desktop environment. It is
developed using the C programming language

and supports all font family.

Some key features of the gedit text editor are as following:

o It provides syntax highlighting.


o It supports internationalized text.
o It supports several programming languages.

To invoke the gedit editor from the terminal, execute the below command:

1. gedit <file name>

It looks like:
Vi Editor with Commands
What is vi
The vi editor is elaborated as visual editor. It is installed in every Unix system. In other
words, it is available in all Linux distros. It is user-friendly and works same on different
distros and platforms. It is a very powerful application. An improved version of vi editor
is vim.

The vi editor has two modes:

o Command Mode: In command mode, actions are taken on the file. The vi editor starts
in command mode. Here, the typed words will act as commands in vi editor. To pass a
command, you need to be in command mode.
o Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key will
take you to the command mode from insert mode.

By default, the vi editor starts in command mode. To enter text, you have to be in insert
mode, just type 'i' and you'll be in insert mode. Although, after typing i nothing will
appear on the screen but you'll be in insert mode. Now you can type anything.

To exit from insert mode press Esc key, you'll be directed to command mode.

If you are not sure which mode you are in, press Esc key twice and you'll be in
command mode.

Using vi
The vi editor tool is an interactive tool as it displays changes made in the file on the
screen while you edit the file.

In vi editor you can insert, edit or remove a word as cursor moves throughout the file.

Commands are specified for each function like to delete it's x or dd.

The vi editor is case-sensitive. For example, p allows you to paste after the current line
while P allows you to paste before the current line.

vi syntax:
1. vi <fileName>

In the terminal when you'll type vi command with a file name, the terminal will get
clear and content of the file will be displayed. If there is no such file, then a new file
will be created and once completed file will be saved with the mentioned file name.

Linux vi example
To start vi open your terminal and type vi command followed by file name. If your file is in
some other directory, you can specify the file path. And if in case, your file doesn't exist, it will
create a new file with the specified name at the given location.

Example:

1. vi /home/sssit/Downloads/file.txt

Look at the above snapshot, we are creating a new file file.txt (as this file doesn't exist) and
have entered the full path for the directory Downloads.

Command mode
This is what you'll see when you'll press enter after the above command. If you'll start
typing, nothing will appear as you are in command mode. By default vi opens in
command mode.
Look at the above snapshot, it is blank as it is a new file. To start typing, you have to
move to the insert mode. At the end of the terminal window, directory name and file
name are displayed.

Insert mode
To move to the insert mode press i. Although, there are other commands also to move to
insert mode which we'll study in next page.

Look at the above snapshot, after pressing i we have entered into insert mode. Now we can
write anything. To move to the next line press enter.

Once you have done with your typing, press esc key to return to the command
mode.
To save and quit
You can save and quit vi editor from command mode. Before writing save or quit command
you have to press colon (:). Colon allows you to give instructions to vi.

exit vi table:

Commands Action

:wq Save and quit

:w Save

:q Quit

:w fname Save as fname

ZZ Save and quit

:q! Quit discarding changes made

:w! Save (and write to non-writable file)

To exit from vi, first ensure that you are in command mode. Now, type :wq and press enter. It
will save and quit vi.

Type :wq to save and exit the file.


Look at the above snapshot, command :wq will save and quit the vi editor. When you'll type
it in command mode, it will automatically come at bottom left corner.

If you want to quit without saving the file, use :q. This command will only work when you
have not made any changes in the file.

Look at the above snapshot, this file is modified and hence on typing :q it displays this
message at bottom left corner.

The above file can be saved with the command :!q. It discards the changes made in the file
and save it.
Look at the above snapshot, we have typed :!q, it will save our file by discarding the
changes made.

To switch from command to insert mode:


Command Action

I Start typing before the current character

I Start typing at the start of current line

A Start typing after the current character

A Start typing at the end of current line

O Start typing on a new line after the current line

O Start typing on a new line before the current line

To move around a file:


Commands Action

J To move down

K To move up
H To move left

L To move right

To jump lines:
Commands Action

G Will direct you at the last line of the file

`` Will direct you to your last position in the file

To delete:
Commands Action

X Delete the current character

X Delete the character before the cursor

r Replace the current character

xp Switch two characters

dd Delete the current line

D Delete the current line from current character to the end of the line

dG delete from the current line to the end of the file

To repeat and undo:


Commands Action

u Undo the last command


. Repeat the last command

Command to cut, copy and paste:


Commands Action

dd Delete a line

yy (yank yank) copy a line

p Paste after the current line

P Paste before the current line

Command to cut, copy and paste in blocks:


Commands Action

<n>dd Delete the specified n number of lines

<n>yy Copy the specified n number of lines

Start and end of line:


Commands Action

θ Bring at the start of the current line

^ Bring at the start of the current line

$ Bring at the end of the current line

dθ Delete till start of a line

d$ Delete till end of a line


Joining lines:
Commands Action

J Join two lines

yyp Repeat the current line

ddp Swap two lines

Move forward or backward:


Commands Action

w Move one word forward

b Move one word backward

<n>w Move specified number of words forward

dw Delete one word

yw Copy one word

<n>dw Delete specified number of words

Search a string:
Commands Action

/string Forward search for given string

?string Backward search for given string

/^string Forward search string at beginning of a line


/string$ Forward search string at end of a line

n Go to next occurrence of searched string

/\<he\> Search for the word he (and not for there, here, etc.)

/pl[abc]ce Search for place, plbce, and plcce

Replace all
Syntax:

1. :<startLine,endLine> s/<oldString>/<newString>/g

Example:

Commands Action

:1,$ s/readable/changed/ Replace forward with backward from first line to the last line

:3,6 s/letters/neww/g Replace forward with backward from third line to the ninth line

Different Shells in Linux


SHELL is a program which provides the interface between the user and an
operating system. When the user logs in OS starts a shell for
user. Kernel controls all essential computer operations, and provides the
restriction to hardware access, coordinates all executing utilities, and manages
Resources between process. Using kernel only user can access utilities provided
by operating system.
Types of Shell:
 The C Shell –
Denoted as csh
Bill Joy created it at the University of California at Berkeley. It
incorporated features such as aliases and command history. It includes
helpful programming features like built-in arithmetic and C-like
expression syntax.
In C shell:
Command full-path name is /bin/csh,
Non-root user default prompt is hostname %,
Root user default prompt is hostname #.
 The Bourne Shell –
Denoted as sh
It was written by Steve Bourne at AT&T Bell Labs. It is the original
UNIX shell. It is faster and more preferred. It lacks features for
interactive use like the ability to recall previous commands. It also lacks
built-in arithmetic and logical expression handling. It is default shell for
Solaris OS.
For the Bourne shell the:
Command full-path name is /bin/sh and /sbin/sh,
Non-root user default prompt is $,
Root user default prompt is #.
 The Korn Shell
It is denoted as ksh
It Was written by David Korn at AT&T Bell LabsIt is a superset of the
Bourne shell.So it supports everything in the Bourne shell.It has
interactive features. It includes features like built-in arithmetic and C-
like arrays, functions, and string-manipulation facilities.It is faster than
C shell. It is compatible with script written for C shell.
For the Korn shell the:
Command full-path name is /bin/ksh,
Non-root user default prompt is $,
Root user default prompt is #.
 GNU Bourne-Again Shell –
Denoted as bash
It is compatible to the Bourne shell. It includes features from Korn and
Bourne shell.
For the GNU Bourne-Again shell the:
Command full-path name is /bin/bash,
Default prompt for a non-root user is bash-g.gg$
(g.ggindicates the shell version number like bash-3.50$),
Root user default prompt is bash-g.gg#.
Introduction to Linux Shell and Shell Scripting
If you are using any major operating system you are indirectly interacting to shell. If
you are running Ubuntu, Linux Mint or any other Linux distribution, you are
interacting to shell every time you use terminal. In this article I will discuss about
linux shells and shell scripting so before understanding shell scripting we have to get
familiar with following terminologies –
 Kernel
 Shell
 Terminal
What is Kernel
The kernel is a computer program that is the core of a computer’s operating
system, with complete control over everything in the system. It manages following
resources of the Linux system –
 File management
 Process management
 I/O management
 Memory management
 Device management etc.
It is often mistaken that Linus Torvalds has developed Linux OS, but
actually he is only responsible for development of Linux kernel.
Complete Linux system = Kernel + GNU system utilities and libraries + other
management scripts + installation scripts .
What is Shell
A shell is special user program which provide an interface to user to use
operating system services. Shell accept human readable commands from user
and convert them into something which kernel can understand. It is a command
language interpreter that execute commands read from input devices such as
keyboards or from files. The shell gets started when the user logs in or start the
terminal.
linux shell

Shell is broadly classified into two categories –



Command Line Shell

Graphical shell
Command Line Shell
Shell can be accessed by user using a command line interface. A special
program called Terminal in linux/macOS or Command Prompt in Windows
OS is provided to type in the human readable commands such as “cat”, “ls”
etc. and then it is being execute. The result is then displayed on the
terminal to the user. A terminal in Ubuntu 16.4 system looks like this –

Linux command line

In above screenshot “ls” command with “-l” option is executed.It will list all the
files in current working directory in long listing format.
Working with command line shell is bit difficult for the beginners because it’s hard
to memorize so many commands. It is very powerful, it allows user to store
commands in a file and execute them together. This way any repetitive task can
be easily automated. These files are usually called batch files in Windows
and Shell Scripts in Linux/macOS systems.
Graphical Shells
Graphical shells provide means for manipulating programs based on graphical
user interface (GUI), by allowing for operations such as opening, closing, moving
and resizing windows, as well as switching focus between windows. Window OS
or Ubuntu OS can be considered as good example which provide GUI to user for
interacting with program. User do not need to type in command for every
actions.A typical GUI in Ubuntu system –

GUI shell

There are several shells are available for Linux systems like –
 BASH (Bourne Again SHell) – It is most widely used shell in Linux systems.
It is used as default login shell in Linux systems and in macOS. It can also
be installed on Windows OS.
 CSH (C SHell) – The C shell’s syntax and usage are very similar to the C
programming language.
 KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell
standard specifications etc.
Each shell does the same job but understand different commands and
provide different built in functions.
Shell Scripting
Usually shells are interactive that mean, they accept command as input from
users and execute them. However some time we want to execute a bunch of
commands routinely, so we have type in all commands each time in terminal.
As shell can also take commands as input from file we can write these
commands in a file and can execute them in shell to avoid this repetitive
work. These files are called Shell Scripts or Shell Programs. Shell scripts
are similar to the batch file in MS-DOS. Each shell script is saved
with .sh file extension eg. myscript.sh
A shell script have syntax just like any other programming language. If you
have any prior experience with any programming language like Python,
C/C++ etc. it would be very easy to get started with it.
A shell script comprises following elements –
Shell Keywords – if, else, break etc.
Shell commands – cd, ls, echo, pwd, touch etc.
Functions
Control flow – if..then..else, case and shell loops etc.
Why do we need shell scripts
There are many reasons to write shell scripts –
 To avoid repetitive work and automation
 System admins use shell scripting for routine backups
 System monitoring
 Adding new functionality to the shell etc.
Advantages of shell scripts
 The command and syntax are exactly the same as those directly entered in
command line, so programmer do not need to switch to entirely different
syntax
 Writing shell scripts are much quicker
 Quick start
 Interactive debugging etc.
Disadvantages of shell scripts
 Prone to costly errors, a single mistake can change the command which
might be harmful
 Slow execution speed
 Design flaws within the language syntax or implementation
 Not well suited for large and complex task
 Provide minimal data structure unlike other scripting languages. etc

How to determine Shell


You can get the name of your shell prompt, with following command :

Syntax:

1. echo $SHELL
Look at the above snapshot, with the help of above command we got the name of our
shell which is 'bash'.

The $ sign stands for a shell variable; echo will return the text whatever you typed in.

Shell Scripting She-bang


The sign #! is called she-bang and is written at top of the script. It passes instruction
to program /bin/sh.

To run your script in a certain shell (shell should be supported by your system), start
your script with #! followed by the shell name.

Example:

1. #!/bin/bash
2. echo Hello World
3. #!/bin/ksh
4. echo Hello World

Shell Scripting Comments


Any line starting with a hash (#) becomes comment. Comment means, that line will not
take part in script execution. It will not show up in the output.

Look at the above snapshot, lines after the # are commented.

Look at the above snapshot, commented lines are not displayed in the output.
Shell Scripting Variables
Scripts can contain variables inside the script.

Look at the above snapshot, two variables are assigned to the script $var1 and $var2.

As scripts run in their own shell, hence variables do not survive the end of the script.

Look at the above snapshot, var1 and var2 do not run outside the script.

Steps to write and execute a script


o Open the terminal. Go to the directory where you want to create your script.
o Create a file with .sh extension.
o Write the script in the file using an editor.
o Make the script executable with command chmod +x <fileName>.
o Run the script using ./<fileName>.

Note: In the last step you have to mention the path of the script if your script is in other
directory.

Hello World script


Here we'll write a simple programme for Hello World.
First of all, create a simple script in any editor or with echo. Then we'll make it executable
with chmod +x command. To find the script you have to type the script path for the shell.

Look at the above snapshot, script echo Hello World is created with echo command
as hello_world. Now command chmod +x hello_world is passed to make it executable.
We have given the command ./hello_world to mention the hello_world path. And output is
displayed.

Shell Scripting if then else


The if then else condition loop states that if condition meets, output goes to if part otherwise
it goes to else part.

The word fi represents if loop termination .

Syntax:

Syntax of if then else is shown in the snapshot below,

Example if then else:

We have shown the example of voting. If user's age will be greater than 18 then he or she will
be eligible to vote, otherwise not.

1. if condition:
2. if [ "$age" -ge 18 ];
Look at the above snapshot, we have shown the script of file voter.

Look at the above snapshot, with age 17 it displays the message "you are younger !!" and
with age 30 it displays the message "you are eligible to vote".

Shell Scripting if then elif


A new if can be nested inside an elif.

Syntax:

Syntax of if then elif is shown in the snapshot below,


Example if then elif:
We have shown the example of choosing color.

Condition:

1. if [ $color == Red ]
2. elif [ $color == Blue ]

Look at the above snapshot, we have shown the script.


Look at the above snapshot, on Red color it goes to if part, on Blue color it goes to elif part
and on other colors it goes to else part.

Condition:

1. if [ $color == Red ]
2. elif [ $color == Blue ]

Look at the above snapshot, we have shown the script.


Look at the above snapshot, on Red color it goes to if part, on Blue color it goes to elif part
and on other colors it goes to else part.

o Keywords are for, in, do, done


o List is a list of variables which are separated by spaces. If list is not mentioned in the
for statement, then it takes the positional parameter value that were passed into the
shell.
o Varname is any variable assumed by the user.

Shell Scripting case


A case construct helps us to simplify nested if statement. You can match several
variables against one variable. Each case is an expression matching a certain pattern.

Syntax:
Look at the above snapshot, you can write one pattern or more than one pattern
together according to the situation. Let's see an example to understand it more clearly.

Example:P

Look at the above snapshot, we have shown a script to show the capital of different
states. States Punjab and Haryana are written together as they share same capital.
Output:

Look at the above snapshot, user can enter a state name and script will display its
capital respectively.

Example for:
We have shown an example to count 2's table within for loop.

Look at the above snapshot, our varname is table, list is specified under curly braces. Within
the curly braces, first two will initialize the table from 2, 20 represents maximum value of
$table and last 2 shows the increment by value 2.
Look at the above snapshot, it displays the 2's table as the output.

2) Syntax:

Syntax of for like C programming language.

Look at the above snapshot, condition1 indicates initialization, cond2


indicates condition and cond3 indicates updation.

Example for:
We have shown an example to count the number in reverse direction.

Look at the above snapshot, this is the loop script. $i will initialize with 10 and will go
till 1, decrementing with 1 value.
Look at the above snapshot, this is the output of the script.

Shell Scripting while loop


Linux scripting while loop is similar to C language while loop. There is a condition in
while. And commands are executed till the condition is valid. Once condition becomes
false, loop terminates.

Syntax:

Syntax of while loop is shown in the snapshot below,

Example:
We have shown the example of printing number in reverse order.

Output is displayed in the below snapshot,


while infinite loop:
Infinite loop is also called endless loop. It is made with while true (it means condition
will always be true) or while : (it means an empty expression), where colon (:) is
equivalent to no operation.

Look at the above snapshot, this script includes while truesyntax.

Look at the above snapshot, this script includes while: syntax.

Both of them display the same output.

Shell Scripting until loop


It is similar to while loop. The only difference is that until statement executes its code
block while its conditional expression is false, and while statement executes its code
block while its conditional expression is true.

Difference between while and until


Until loop always executes at least once. Loop while executes till it returns a zero value
and until loop executes till it returns non-zero value.

Syntax:
Syntax of until loop is shown in the snapshot below:

Example:
We have shown an example to display number from 5 to 15.

Look at the above snapshot, it shows the script.

Look at the above snapshot, it displays the output until the condition is false.

What are Linux Regular Expressions?


Linux Regular Expressions are special characters which help search data and
matching complex patterns. Regular expressions are shortened as ‘regexp’ or
‘regex’. They are used in many Linux programs like grep, bash, rename, sed,
etc.
Types of Regular expressions
For ease of understanding let us learn the different types of Regex one by one.

 Basic Regular expressions


 Interval Regular expressions
 Extended regular expressions

Basic Regular expressions


Some of the commonly used commands with Regular expressions are tr, sed,
vi and grep. Listed below are some of the basic Regex.

Symbol Descriptions

. replaces any character

^ matches start of string

$ matches end of string

* matches up zero or more times the preceding character

\ Represent special characters

() Groups regular expressions

? Matches up exactly one character


Let’s see an example.

Execute cat sample to see contents of an existing file

Search for content containing letter ‘a’.


‘^‘ matches the start of a string. Let’s search for content that STARTS with a

Only lines that start with character are filtered. Lines which do not contain the
character ‘a’ at the start are ignored.

Let’s look into another example –

Select only those lines that end with t using $

Interval Regular expressions


These expressions tell us about the number of occurrences of a character in a
string. They are

Expression Description
{n} Matches the preceding character appearing ‘n’ times exactly

{n,m} Matches the preceding character appearing ‘n’ times but not more than m

{n, } Matches the preceding character only when it appears ‘n’ times or more
Example:

Filter out all lines that contain character ‘p’

We want to check that the character ‘p’ appears exactly 2 times in a string one
after the other. For this the syntax would be:
cat sample | grep -E p\{2}

Note: You need to add -E with these regular expressions.

Extended regular expressions


These regular expressions contain combinations of more than one expression.
Some of them are:

Expression Description

\+ Matches one or more occurrence of the previous character

\? Matches zero or one occurrence of the previous character


Example:

Searching for all characters ‘t’


Suppose we want to filter out lines where character ‘a’ precedes character ‘t’

We can use command like


cat sample|grep "a\+t"

Brace expansion
The syntax for brace expansion is either a sequence or a comma separated list
of items inside curly braces “{}”. The starting and ending items in a sequence
are separated by two periods “..”.

ome examples:

In the above examples, the echo command creates strings using the brace
expansion.

Wild card characters in Linux


10 Practical Examples Using Wildcards to Match Filenames in Linux (tecmint.com)

Shell Scripting Tutorial in Linux

You might also like