0% found this document useful (0 votes)
27 views108 pages

Introduction to Linux Programming Basics

The document provides an extensive overview of Linux programming, covering its history, architecture, features, and various distributions. It discusses the advantages and disadvantages of using Linux, its applications, and the components of the Linux operating system, including the kernel and system libraries. Additionally, it highlights the installation process and the importance of Linux in various computing environments, from personal systems to enterprise solutions.

Uploaded by

revathiaiml30
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)
27 views108 pages

Introduction to Linux Programming Basics

The document provides an extensive overview of Linux programming, covering its history, architecture, features, and various distributions. It discusses the advantages and disadvantages of using Linux, its applications, and the components of the Linux operating system, including the kernel and system libraries. Additionally, it highlights the installation process and the importance of Linux in various computing environments, from personal systems to enterprise solutions.

Uploaded by

revathiaiml30
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

CSOE005 LINUX PROGRAMMING

UNIT I

INTRODUCTION TO LINUX AND LINUX UTILITIES: A brief history of LINUX, Architecture of LINUX, Features of LINUX,
Introduction to vi editor. Linux commands - PATH, Man, Echo, Printf, Script, Passwd, Uname, Who, Date, Stty, Pwd, cd, mkdir, rmdir,
ls, cp, mv, rm, cat, more, wc, lp, od, tar, gzip, File handling utilities, Security by file permissions, Process utilities, Disk utilities,
Networking commands, unlink, du, df, mount, umount, find, unmask, ulimit, ps, w, finger, arp, ftp, telnet, [Link] Processing utilities
and backup utilities , Tail, head , sort, nl, uniq, grep, egrep, fgrep, cut, paste, join, tee, pg, comm, cmp, diff, tr, awk, cpio

HISTORY OF LINUX:
A popular open-source operating system is Linux. It was initially created by Linus Torvalds in 1991. At the time, Torvalds was a
computer science student at the University of Helsinki, Finland and began working on the Linux project as a personal endeavour. The
name Linux is a combination of his first name, Linus, and Unix, the operating system that inspired his projects
Linux as free software under the GNU General Public License. This meant that anyone could use, modify, and redistribute his source
code.
Early versions of Linux were primarily used by technology enthusiasts and software developers, but over time it has grown in
popularity and is used in various types of devices such as servers, smartphones, and embedded systems.
Linux is considered one of the most stable, secure and reliable operating systems and is widely used in servers, supercomputers and
enterprise environments. Nowadays Linux has many distributions (versions) namely:
1. Ubuntu
2. Fedora
3. Arch
4. Plasma
5. KDE
6. Mint
7. Manjaro
How does Linux Work?
Think of the operating system as the engine of your car. The engine can move on its own, but when connected to the gearbox, axles
and wheels it becomes a functioning car. If the engine is not working properly, the rest of the car will not work. Linux was designed
to be similar to UNIX but evolved to run on hardware ranging from phones to supercomputers. All Linux-based operating systems

1
include a Linux kernel that manages hardware resources and a set of software packages that make up the rest of the operating system.
Organizations can also run Linux operating systems on Linux servers.
• Kernel: This is actually a component of the “Linux” system as a whole. The kernel, which controls the CPU, memory,
and peripherals, serves as the brain of the system. The operating system’s kernel is at the most fundamental level.
• Desktop Environment: The user actually engages in interaction at this point. There are numerous desktop environments
available (GNOME, Cinnamon, Mate, Pantheon, Enlightenment, KDE, Xfce, etc.). Every desktop environment has pre-
installed programmes (file managers, configuration tools, web browsers, games, etc.).
Why Use Linux?
There are several reasons why one might choose to use Linux:
• Open-source: Linux is open-source software, meaning that the source code is freely available for anyone to use, modify,
and distribute. This allows for a large and active community of developers to contribute to the development and
maintenance of the operating system.
• Customizability: Linux is highly customizable, and users can easily install and configure different software packages to
suit their needs.
• Stability and security: Linux is known for its stability and security, as it is less prone to crashes and viruses than other
operating systems.
• Cost-effective: Linux is free to download and use, making it a cost-effective option for individuals and businesses.
Events Leading to the Creation of Linux
The emergence of Linux, one of the world’s most widely used open-source operating systems, can be traced to several important
events and the work of a few people. Below is a summary of the major events that led to the emergence of Linux.
1. Unix development: Linux was heavily influenced by the Unix operating system developed by Bell Labs in the late
1960s and early 1970s. Unix was developed as a multi-user, multi-tasking operating system and has been widely used in
science and research.
2. Minix is born: In the early 1980s, computer science professor Andrew S. Tanenbaum created a small Unix-like
operating system called Minix. Minix was developed as an educational tool and the source code was made available to
students.
3. Linux is born: In 1991, a 21-year-old student named Linus Torvalds began working on a new operating system he
named Linux. Linus was inspired by his Minix and used its source his code as a starting point for his own projects. He
also drew heavily on Unix design principles.
4. Release of Linux 0.01: In September 1991, Linus released the first version of his Linux called Linux 0.01. It was a
command-line operating system and was freely distributed on the Internet.

2
5. Linux community development: In the years that followed, Linux quickly gained popularity among programmers and
enthusiasts. A community of developers began to form around Linux, contributing to the development of the operating
system by writing code, filing bug reports, and providing feedback.
6. Enterprise Adoption: In the late 1990s and early 2000s, the open-source nature of Linux made it more flexible, cost-
effective, and more secure than proprietary operating systems such as Windows, making it a popular choice for
enterprises and businesses. started being hired by companies. This increased acceptance led to the development of
commercial support and services for Linux.
7. Linux Distribution Growth: As Linux became more popular, various groups of developers began creating their own
versions of the operating system, called distributions. Some of the most popular distributions are Red Hat, Debian, and
Ubuntu. These distros contain the Linux kernel and a number of his packages of easy-to-use tools and software that
make using his Linux easy for both developers and end users.
8. Linux in the Enterprise: With the growth of cloud computing and the Internet of Things, Linux continues to gain
traction in the enterprise. Linux is now widely used as an operating system for servers, mainframes, and supercomputers.
It’s also used in embedded systems, mobile devices, and the Internet of Things.
9. Linux in the Consumer Market: Linux has also entered the consumer market with the advent of Linux-based mobile
devices, smart TVs, and other consumer electronics.
Development of Linux
The Linux ecosystem is a constantly evolving and expanding platform, so there is a lot of development going on. Notable recent
developments include:
• Linux 5.11 kernel release. It includes new features such as AMD Zen 3 processor support, memory management
system improvements, and new hardware support.
• Continued development of various Linux distributions. Ubuntu 21.04 released in April 2021. It features an updated
Gnome desktop environment, improved ZFS file system support, and new security features.
• Development of new open-source software and tools for Linux. For example, the release of version 6.0 of Ansible
automation tools brings new features such as support for Windows Subsystem for Linux 2 (WSL2) and improved
support for Kubernetes.
• The rise of containerization and orchestration technologies such as Docker and Kubernetes. They are becoming more
and more common in deploying and managing Linux-based applications.
• Linux is growing in popularity in the cloud computing space, with many major cloud providers offering Linux-based
virtual machines and managed services.
Installing Linux
Installing an operating system can seem like a daunting task to many. Believe it or not, Linux is the easiest operating system to install.
In fact, most versions of Linux offer what’s called a live distribution. This means running your operating system from a CD/DVD or

3
USB flash drive without making any changes to your hard drive. All features are available without committing to an installation.
Once you’ve tried it out and decided to use it, double-click the Install icon to run the simple installation wizard.

Pros and Cons of Linux OS or Advantages and Disadvantages of Linux

o Open source: The Linux kernel is published under the open-source software license of GNU GPL. Most distributions contain
several applications with various options in almost all categories. Also, several distributions contain proprietary software, like
device drivers offered by manufacturers, to support hardware.
o Reliability: Linux is treated as a reliable operating system, and it is well-supported with several security patches. Also, Linux is
treated as a stable OS, which means it can execute in almost every circumstance. Linux can also handle errors when running
unexpected input and software.
o Licensing costs: Linux has no accurate licensing fees, unlike Apple macOS or Microsoft Windows. While system support is
present for a fee from several Linux vendors, the operating system itself is free to use and copy. A few IT organizations have
enhanced their savings by moving their server software to Linux from a commercial operating system.

o Backward compatibility: Linux and many open-source software tend to be frequently updated for functional and security
patches while having core functionality. Shell scripts and configurations are likely to operate unchanged even if software updates

4
are used. Generally, Linux and other open-source applications do not alter their operation modes with new versions, unlike
economic software vendors that mount new releases of their operating systems with new forms of work.
o Several choices: Between almost all infinite options, several available distros, and many application options to configure,
compile, and run Linux on almost all hardware platforms, it's possible to develop Linux for almost all applications.

Security

The Linux security feature is the main reason that it is the most favorable option for developers. It is not completely safe, but it is less
vulnerable than others. Each application needs to authorize by the admin user. The virus is not executed until the administrator provides
the access password. Linux systems do not require any antivirus program.

Stability

Linux is more stable than other operating systems. Linux does not require to reboot the system to maintain performance levels. It
rarely hangs up or slow down. It has big up-times.

Performance

Linux system provides high performance over different networks. It is capable of handling a large number of users simultaneously.

Flexibility

Linux operating system is very flexible. It can be used for desktop applications, embedded systems, and server applications too. It also
provides various restriction options for specific computers. We can install only necessary components for a system.

Graphical User Interface

Linux is a command-line based OS but, it provides an interactive user interface like Windows.

5
Privacy

Linux always takes care of user privacy as it never takes much private data from the user. Comparatively, other operating systems ask
for the user's private data.

Software Updates

In Linux, the software updates are in user control. We can select the required updates. There a large number of system updates are
available. These updates are much faster than other operating systems. So, the system updates can be installed easily without facing any
issue.

Multitasking

It is a multitasking operating system as it can run multiple tasks simultaneously without affecting the system speed.

Multiple Desktop Support

Linux system provides multiple desktop environment support for its enhanced use. The desktop environment option can be selected
during installation. We can select any desktop environment such as GNOME (GNU Network Object Model Environment) or KDE
(K Desktop Environment) as both have their specific environment.

6
o Lack of standard: No standard version is available for Linux, which may be nice to optimize Linux for specific applications,
but less so to deploy desktop images and standardized servers. The huge variety of options can convolute support as an outcome.
o Support costs: Support isn't free, while an organization can freely acquire Linux without licensing fees. Almost all enterprise
Linux distributors, such as Red Hat and SUSE, provide support contracts. These license fees can significantly decrease savings
depending on the situation.
o Proprietary software: PC productivity software, such as Microsoft Office, can't be utilized on Linux desktops, and many
proprietary software may not be available for Linux platforms.
o Steep learning curve: Several users battle to learn to use Linux-based applications and Linux desktops.
o Unsupported hardware: Several hardware manufacturers enable the device drivers of Linux accessible for their products, but
several don't.

Types of Linux OS
Ubuntu: Ubuntu is one of the most popular Linux distributions designed for desktop and server use. Ubuntu offers a simple and user-
friendly interface and supports many applications.
Fedora: Fedora is a Linux distribution developed by the Fedora Project, a community supported by Red Hat. Fedora is often used for
development and security testing purposes.

7
Debian: Debian is a Linux distribution known for its excellent package management capabilities. Debian is also often used as the basis
for other Linux distributions, including Ubuntu and Knoppix.
Arch Linux: Arch Linux is a Linux distribution designed for more experienced users. Arch Linux offers greater control over the system
and allows users to install only the components they need.
CentOS: CentOS is a Linux distribution based on the source code of Red Hat Enterprise Linux (RHEL). CentOS is often used as a
cheaper alternative to RHEL because CentOS is free and open-source.
Kali Linux: Kali Linux is a Linux distribution designed for penetration testing and network security. Kali Linux comes with many tools
for testing network and system security.
Mint: Mint is a Linux distribution designed for desktop use. Mint offers a simple and user-friendly interface, and supports many
applications.
OpenSUSE: OpenSUSE is a Linux distribution designed for desktop and server use. OpenSUSE offers many security features and strong
package management.
Red Hat Enterprise Linux (RHEL): RHEL is a Linux distribution designed for business use. RHEL offers many security features and
long-term support for updates.

Applications of LINUX OS

1. Stacer– The PC Optimizer


2. VLC Media Player– The Media Player
3. Steam– A Gaming Emulator
4. Rambox– The Multi-Social Media Application
5. Kodi– A media Repo
6. Calibre– A Book Reader
7. TimeShift– A Powerful PC Restore
8. KeePass: Password Safe
9. aTunes: Alternative Program For iTunes

8
ARCHITECTURE OF LINUX:
Linux is an open-source UNIX-based operating system. The main component of the Linux operating system is Linux kernel. It is
developed to provide low-cost or free operating system service to personal system users, which includes an X-window system, Emacs
editor, IP/TCP GUI, etc.
Linux distribution:
Linux distribution is developed using a set of software based on compatibility with the Linux core kernel, using which Linux-based
operations in different systems, such as personal systems, embedded systems, etc. There are around 600 distributions available.
Some Linux distributions are: MX Linux, Manjaro, Linux Mint, elementary, Ubuntu, Debian, Solus, Fedora, openSUSE, Deepin
Components of Linux:
Like any operating system, Linux consists of software, computer programs, documentation, and hardware.
The main components of Linux operating system are: Application, Shell, Kernel, Hardware, Utilities

Linux operating system architecture

9
1. Kernel:
Kernel is the main core component if Linux, it controls the activity of other hardware components. It visualizes the common hardware
resources and provide each process with necessary virtual resources. It makes the process to wait in the ready queue and execute in
consequently to avoid any kind of conflict.
Different of types of kernel:
1.1. Monolithic Kernel:
Monolithic kernel is a type of operating system kernel, where all the concurrent processes are executed simultaneously in the kernel
itself. All the processes share same memory recourses.
1.2. Micro kernel:
In micro kernel user services and kernel services are executed in separate address spaces. User services are kept in user address space
and kernel services are kept in kernel address space.
1.3. Exokernel:
Exo-kernel is designed to manage hardware resources at application level. High level abstraction is used in this operating system to
offer hardware resources access to kernel.
1.4. Hybrid kernel:
It is the combination of both monolithic kernel and microkernel. It has speed and design of monolithic kernel and modularity and
stability of microkernel.
Main Subsystems of kernel:
• Process scheduler: Responsible for fairly distributing the the processing time among all the concurrently running process.
• Memory management unit: This kernel sub unit is responsible for proper distribution of memory resources among the
concurrently running process.
• Virtual file system: This subsystem provides interface to access stored data across different file system and different
physical media.

10
Kernel subsystems

2. System Library:
System libraries are some predefined functions by using which any application programs or system utilities can access kernel’s
features. These libraries are the foundation upon which any software can be built.
Some of the most common system libraries are:
1. GNU C library: This is the C library that provides the most fundamental system for the interface and execution of C
programs. This provides may in-built functions for the execution.
2. libpthread (POSIX Threads): This library plays important role for multithreading in Linux, it allows users for creating
and managing multiple threads.
3. libdl (Dynamic Linker): This library is responsible for the loading and linking file at the runtime.
4. libm (Math Library): This library provides user with all kind of mathematical function and their execution.
Some other system libraries are: librt (Realtime Library), libcrypt (Cryptographic Library), libnss (Name Service Switch Library),
libstdc++ (C++ Standard Library)
3. Shell:
Shell can be determined as the interface to the kernel, which hides the internal execution of functions of kernel from the user. Users
can just enter the commend and using the kernel’s function that specific task is performed accordingly.
Different types of shell:

11
3.1. Command Line shell:
Executes the command provided by user given in the form command. A special program called terminal in executed and the result is
displayed in the terminal itself.
3.2. Graphical User Interface:
Executes the process provided by user in graphical way and output is displayed in the graphical window.

Linux shell

4. Hardware Layer:
Hardware layer of Linux is the lowest level of operating system track. It is plays a vital role in managing all the hardware components.
It includes device drivers, kernel functions, memory management, CPU control, and I/O operations. This layer generalizes hard
complexity, by providing an interface for software by assuring proper functionality of all the components.
5. System utility:
System utilities are the commend line tools that preforms various tasks provided by user to make system management and
administration better. These utilities enables user to perform different tasks, such as file management, system monitoring, network
configuration, user management etc.

12
FEATURES OF LINUX

Here is the list of top features of the Linux Operating system:


1. Free and Open Source

2. Multiuser Capacity

3. Multitasking

4. Security

5. Graphical User Interface (GUI)

6. File System

7. Application Support

13
8. Frequent New Updates

9. Portability

10. Performance

11. Lightweight Infrastructure

12. Live CD/USB

13. Support's customized keyboard

14. Compatible with cloud computing

15. Interoperability

16. Shell
1. Free and Open Source
This Linux code is freely available to all, and it's a community-based development project which helps the user to modify the code or
analyze the codes and redistribution of codes.
2. Multiuser Capacity
In Multiuser Capacity, Linux allows its users to share the system resources such as RAM, hard drive, and application program at same
time. But they have to use it in different terminals.
3. Multitasking
Multitasking allows multiple applications to run simultaneously by effectively dividing the CPU time. Examples of multitasking are
UNIX, IBM’s OS/390, Windows Vista, Windows XP, and Windows 7, 8, 9, and 10.
4. Security
It secures data in three ways:
Authentication: By using a password and login ID
Authorization: By using read, write and execute permissions
Encryption: It converts the files into an unreadable format.

14
5. Graphical User Interface (GUI)
It is a command line that can be converted into a Graphical User Interface by installing some packages. The most popular method for
getting a GUI in a Linux system is logging into a Ubuntu server and installing its desktop environment.
6. File System
It provides a hierarchical system to arrange files and directories. The folders are classified into binary directories, configuration
directories, data directories, and memory directories based on the type of files they contain.
7. Application Support
It consists of a software repository for users to download and install several applications, which gives the user a vast field of
applications to download the application of their choice.
8. Frequent New Updates
Linux operating systems receive frequent updates, including security patches, bug fixes, and new features, ensuring ongoing
improvements and staying up-to-date with evolving technology.
9. Portability
Here the term portability doesn't mean the smaller size. Here, it means that Linux supports different kinds of hardware, which means
that the software can perform similarly on different types of hardware.
10. Performance
Linux operating systems are known for their performance, offering high stability, efficiency, and scalability, making them widely used
in various applications.
11. Lightweight Infrastructure
Linux can be configured into a lightweight infrastructure by using minimal resources, streamlined services, and optimized kernel
settings, ideal for resource-constrained environments or embedded systems.
12. Live CD/USB
Live CD/USB of a Linux operating system allows booting and running the OS from external media without installation, useful for
testing, recovery, or portable computing.
13. Support's customized keyboard
Linux offers support for customized keyboard layouts, allowing users to define and use specific key mappings for various languages
and preferences.
14. Compatible with cloud computing
Linux is highly compatible with cloud computing platforms, offering a wide range of distributions and tools for cloud deployment,
scaling, and management. It's a popular choice for cloud servers and containers.

15
15. Interoperability
Linux demonstrates strong interoperability, allowing it to work seamlessly with various software, file formats, and systems, promoting
open standards and collaboration across diverse environments.
16. Shell
The Shell command-line interpreter on Linux acts as a line between the user and the kernel, which runs the program known
as commands. It is efficient and takes less time and space while executing the tasks.

INTRODUCTION TO VI EDITOR
The default editor that comes with the Linux/UNIX operating system is called vi (visual editor). Using vi editor, we can edit an
existing file or create a new file from scratch. we can also use this editor to just read a text file. The advanced version of the vi
editor is the vim editor.

To Open VI Editor
To open vi editors, we just need to type the command mentioned below.
vi [file_name]

Here, [file_name] = this is the file name we want to create or to open the pre-existing file.
Example 1: Creating a new file with `file_name` = geeksforgeeks
vi geeksforgeeks

Modes of Operation in the vi editor


There are three modes of operation in vi:

16
Here are three modes of operations on the vi editor

Vi Command Mode :
When vi starts up, it is in Command Mode. This mode is where vi interprets any characters we type as commands and thus does not
display them in the window. This mode allows us to move through a file, and delete, copy, or paste a piece of text. Enter into
Command Mode from any other mode, requires pressing the [Esc] key. If we press [Esc] when we are already in Command Mode,
then vi will beep or flash the screen.
Vi Insert mode:
This mode enables you to insert text into the file. Everything that’s typed in this mode is interpreted as input and finally, it is put in
the file. The vi always starts in command mode. To enter text, you must be in insert mode. To come in insert mode, you simply type
i. To get out of insert mode, press the Esc key, which will put you back into command mode.
Vi Last Line Mode (Escape Mode):
Line Mode is invoked by typing a colon [:], while vi is in Command Mode. The cursor will jump to the last line of the screen and vi
will wait for a command. This mode enables you to perform tasks such as saving files and executing commands.

Linux vi Commands and Examples

17
to insert in vi editor in Linux :
To enter in insert mode in vi editor in Linux we just need to press `i` on our keyboard and we will be in insert mode. we can just
start entering our content. (Refer to screenshot mentioned below).

Moving within a File (Navigation) in Vi Editor :


To move around within a file without affecting text must be in command mode (press Esc twice). Here are some of the commands
that can be used to move around one character at a time.
Commands Description

`k` Moves the cursor up one line.

`j` Moves the cursor down one line.

`h` Moves the cursor to the left one-character position.

`l` Moves the cursor to the right one-character position.

18
Commands Description

`0` Positions cursor at beginning of line.

Control Command (Scrolling) in vi Editor :


There are the following useful commands which can be used along with the Control Key. These commands are helpful in saving
time by navigating quickly in a file without manually scrolling.
Command Description

CTRL+d moves the screen down by half a page.

CTRL+f moves the screen down by a full page.

CTRL+u moves the screen up by half a page.

CTRL+b moves the screen up by a full page.

Inserting and Replacing text in Vi Editor :


To edit the file, we need to be in the insert mode. There are many ways to enter insert mode from the command mode.
Command Description

i Inserts text before current cursor location

a Insert text after current cursor location

19
Command Description

A Insert text at the end of current line

Deleting Characters and Lines in Vi Editor :


Here is the list of important commands which can be used to delete characters and lines in an opened file.
Command Description

`X` (Uppercase) Deletes the character before the cursor location.

`x` (Lowercase) Deletes the character at the cursor location.

`Dw` Deletes from the current cursor location to the next word

`d^` Deletes from current cursor position to the beginning of the line.

Copy and Paste in Vi editor in Linux:


Copy lines or words from one place and paste them in another place by using the following commands.
Commands Description

Yy Copies the current line.

9yy Yank current line and 9 lines below.

20
Commands Description

p Puts the copied text after the cursor.

Save and Exit in Vi Editor in Linux:


Need to press [Esc] key followed by the colon (:) before typing the following commands:
Commands Description

q Quit

q! Quit without saving changes i.e. discard changes.

r [file_name] Read data from file called [file_name]

wq Write and quit (save and exit).

SECURITY BY FILE PERMISSION

Setting file permissions in Linux is a fundamental task for managing access to files and directories. Proper file permissions ensure
that only authorized users can read, write, or execute files, enhancing the security and functionality of your system.

To Check the Permission of Files in Linux

ls –l

21
-rw-r—r— 1 root root 46 Apr 14 16:37 example

There’s a lot of information in those lines.


1. The first character = ‘-‘, which means it’s a file ‘d’, which means it’s a directory.
2. The next nine characters = (rw-r–r–) show the security
3. The next column shows the owner of the file. (Here it is `root`)
4. The next column shows the group owner of the file. (Here it is `root` which has special access to these files)
5. The next column shows the size of the file in bytes.
6. The next column shows the date and time the file was last modified.
7. Last Column = File_name or Directory_name. (For example, here are: prac, snap, test, example)

Each of the three “rwx” characters refers to a different operation you can perform on the file.

1. owners: These permissions apply exclusively to the individuals who own the files or directories.
2. Groups: Permissions can be assigned to a specific group of users, impacting only those within that particular group.
3. All Users: These permissions apply universally to all users on the system, presenting the highest security risk. Assigning
permissions to all users should be done cautiously to prevent potential security vulnerabilities.
--- --- ---
rwxrwxrwx
user group other
There are three kinds of file permissions in Linux Read, write, and execute.
Letters Definition

‘r’ “read” the file’s contents.

‘w’ “write”, or modify, the file’s contents.

22
Letters Definition

“execute” the file. This permission is given only if


‘x’ the file is a program.

Symbols: `+`, `-` and `=`Option in Linux File Permission


Operators Definition

`+` Add permissions

`-` Remove permissions

`=` Set the permissions to the specified values

User, group, and others Option in Linux File Permission


Reference Class Description

The user permissions apply only


to the owner of the file or
directory, they will not impact
`u` user the actions of other users.

23
Reference Class Description

The group permissions apply


only to the group that has been
assigned to the file or directory,
they will not affect the actions
`g` group of other users.

The other permissions apply to


all other users on the system,
this is the permission group you
`o` others want to watch the most.

All three (owner, groups,


`a` All three others)

Reading the Security Permissions in Linux


For example: “rw- r-x r–“
• “rw-“: the first three characters `rw-`. This means that the owner of the file can “read” it (look at its contents) and “write” it
(modify its contents). we cannot execute it because it is not a program but a text file.
• “r-x”: the second set of three characters “r-x”. This means that the members of the group can only read and execute the files.
• “r–“: The final three characters “r–” show the permissions allowed to other users who have a UserID on this Linux system. This
means anyone in our Linux world can read but cannot modify or execute the files’ contents.

24
To Change Permissions in Linux
The command you use to change the security permissions on files is called “chmod“, which stands for “change mode” because the
nine security characters are collectively called the security “mode” of the file.
An example will make this clearer.
For example, if you want to give “execute” permission to the world (“other”) for file “[Link]”, you will start by typing.
chmod o
Now you would type a ‘+’ to say that you are “adding” permission.
chmod o+
Then you would type an ‘x’ to say that you are adding “execute” permission.
chmodo+x
Finally, specify which file you are changing.
chmodo+x [Link]

Multiple permission
To change multiple permissions at once. For example, if you want to take all permissions away from everyone, you would type.
chmodugo-rwx [Link]

The code above revokes all the read(r), write(w), and execute(x) permission from all user(u), group(g), and others(o) for the file
[Link]

PROCESS UTILITIES:
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 called 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.

25
• 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

26
PID TTY TIME CMD
19 pts/1 [Link] sh
24 pts/1 [Link] ps
For more information -f (full) can be used along with ps
$ ps –f

UID PID PPID C STIME TTY TIME CMD


52471 25 19 0 08:04 pts/1 [Link]ps -f
For single-process information, ps along with process id is used
$ ps 19

PID TTY TIME CMD


19 pts/1 [Link] 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 pscommand :
• -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

27
UID PID PPID C STIME TTY TIME CMD
52471 19 1 0 07:20 pts/1 [Link]sh

$ 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:
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

28
udev 493812 4 493808 1% /dev
tmpfs 100672 1364 99308 2% /run
none 5120 0 5120 0% /run/lock
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
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.

29
DISK UTILITIES IN LINUX
Disk Utilities make it easy for system administrators to easily monitor and manage disk partitions in Linux. In this article, we will look
at the most popular disk utilities in Linux. Most of them are available in almost every Linux distribution, by default.

Here are the top disk utilities in Linux.

[Link] command

du command that estimates and displays the disk space used by files.
du command-line utility helps you to find out the disk usage of set of files or a directory.
syntax of du command :
//syntax of du command

du [OPTION]... [FILE]...
where OPTION refers to the options compatible with du command and FILE refers to the filename of know the disk space
occupied.

here are two files say [Link] and [Link] and you want to know the disk usage of these files,
//using du command

$du [Link] [Link]


8 [Link]
4 [Link]

/* the first column


displayed the file's
disk usage */
above du displayed the disk space used by the corresponding files.

30
• Using – -time option : This option is used to display the last modification time in the output of du.
$du --time [Link]
4 2017-11-18 16:00 [Link]

• Using -h option : As mentioned above, -h option is used to produce the output in human readable format.

$du -h [Link] [Link]


8.0K [Link]
4.0K [Link]

• Using -c option : This option displays the grand total as shown.

$du -c -h [Link] [Link]


8.0K [Link]
4.0K [Link]
12.0K total

2. fdisk
fdisk (for fixed disk) is a popular disk utility to create and manage disk partitions in Linux. It supports GPT, MBR, Sun, SGI, and
BSD partition tables. You can use it to create, resize, modify, delete and move disk partitions. The following command will display all
partition tables on your disk.

$ sudofdisk -l

3. sfdisk
sfdisk (for scriptable fdisk) is another disk utility that is similar to fdisk but offers more features. It also supports GPT, MBR, Sun,
SGI, BSD partition tables. Here is the command to display all partition tables on your system.
31
$ sudosfdisk -l

4. cfdisk
cfdisk (curses fdisk) is a simple disk partitioning utility that allows you to manage disk partitions on your system. Like fdisk and
sfdisk, it allows you to create, modify, resize and delete disk partitions. You can navigate through its output using right & left arrow
keys.

$ sudocfdisk

5. parted
parted is another popular command for managing disk partitions. It is used to create new partitions and re-organize existing partitions.
You can also use it to copy data across disk partitions as well as hard disks. Like other tools mentioned above, it also supports GPT
and MBR partition table formats.

$ sudo parted -l

6. lsblk
lsblk command (list block) displays all available information about available and mounted block devices, such as name, type,
mountpoint.

$ lsblk

7. blkid
blkid (block id) is a utility that displays block device attributes such as deice or partition name, label, and filesystem.

32
$ blkid

8. hwinfo
If you need to get hardware info about your system, you can use hwinfo command. You can also use — <HARDWARE_TYPE>
option to list all hardware of specified type. You can also use –short option to get summarized information.

$ hwinfo --short --block

9. df command
If you want to monitor the disk usage, then df is the most popular command for this purpose. Here is a command to display total disk
size, used space, available space and usage percent in human readable formats.

$ sudodf -hT

10. pydf
pydf is an alternative to df command to monitor disk usage. It is a python script that displays disk usage and free disk using system
colors. It is a great alternative to df command.

$ pydf

In this article, we have learnt about the different disk utilities that system administrators can use to monitor and manage their disk
partitions.

33
LINUX COMMANDS
Path

PATH specifies program directories and instructs the system where to search for a program to run.
To print all the configured directories in the system's PATH variable, run the echo command:

echo $PATH

The output shows directories configured in PATH by default.

Man

The "man" is a short term for manual page. In linux, man is an interface to view the system's reference manual. man command
in Linux is used to display the manual pages for other commands and utilities. It provides detailed documentation about the usage,
options, and functionality of commands, Each manual page includes sections such as NAME, SYNOPSIS, DESCRIPTION,
OPTIONS, and EXAMPLES, which help users understand and effectively use the command.
Sections in Manual Pages
Manual pages are organized into different sections, each serving a specific purpose. The primary sections include:
• NAME: Provides the name and a brief description of the command.
• SYNOPSIS: Describes the syntax of the command.
• DESCRIPTION: Offers a detailed explanation of the command’s functionality.
• OPTIONS: Lists the available command-line options and their descriptions.
• EXAMPLES: Provides practical examples demonstrating command usage.

34
Syntax of man:
man [option(s)] keyword(s)
For example,
man ls
This command will display all the information about 'ls' command as shown in the screen shot.
-w option in man Command in Linux
• The -w option in the man command returns the location of the manual page for a given command. This is useful for finding
where the manual pages are stored on the system.
Syntax
man -w [COMMAND NAME]
Example
man -w ls
Output
In this example, the command man -w ls outputs the path to the manual page for the ls command, indicating where the documentation
file is located on the system.

Echo

In Linux, the echo command can be used for displaying a line of string/text that is passed as the arguments.

35
Syntax of the echo command

echo [string]

Printf

“printf” command in Linux is used to display the given string, number or any other format specifier on the terminal window. It works
the same way as “printf” works in programming languages like C.

Syntax:
$printf [-v var] format [arguments]
$printf "%s\n" "Hello, World!"
Output:

Script
36
script command in Linux is used to make typescript or record all the terminal activities. After executing the script command it starts
recording everything printed on the screen including the inputs and outputs until exit. By default, all the terminal information is saved
in the file typescript , if no argument is given.

Syntax:

script [options] [file]


Example:

Input:

In order to stop the typescript, we just need to execute exit command and script will stop the capturing process. Since there’s no
filename given as argument, the script will automatically create a file namely typescript in the home directory to save the recorded
information.
Output:

Passwd

The passwd command is used to create and change the password for a user. If the passwd command is executed by non-root user then
it will prompt for the current password and then allows to set new password of a user who has invoked the command.

Syntax:

37
1. passwd <username>

Output:

Uname

The uname command is used to check the complete OS information of the system. Check out the command and the output below
Command:

Output:

Description

The uname is a command line tool most commonly used to determine the processor architecture, the system hostname and the version
of the kernel running on the system.

Examples

1. When we run uname command without any options, it just prints the core operating system name. We can also use -s option to get
the same output, it prints the kernel name of the system.

$ uname
Linux
$ uname -s

38
Linux

Options

-a, --all
print all information, in the following order, except omit -p and -i if unknown:

-
-m, --machine
print the machine hardware name

-p, --processor
print the processor type (non-portable)

-i, --hardware-platform
print the hardware platform (non-portable)

-o, --operating-system
print the operating system

--help
display this help and exit

--version
output version information and exit

Who

The Linux "who" command lets you display the users currently logged in to your UNIX or Linux operating system.

The output of the "who" command usually depends on the users and how they use it. If a user normally types the "Who" command in
the terminal and runs it, the output will be the same. It will display the list of the users that are currently logged in to the current operating

39
system. However, if the user runs or uses the "who" command with different arguments, then the output will also be slightly changed or
may completely different.

Syntax of the command:

who
to run the "who" command in Linux?

The following steps will help you to run the above command even if someone is not familiar enough with Linux operating systems (or
new to the Linux Operating system):

Step 1. Open the terminal by pressing the Ctrl + Alt + T on the keyboard, as shown in the given image:

Step 2. Now, type the following given command in the terminal and press enter:

Command:

Who

Step 3. Once you press the enter button, it will take a little bit time and display the information like logged-in users' names, last reboot
time,, etc. The output of this command may look like as given in the following image:

Output

40
"Who" command with the different arguments:

1. To display all details of currently logged in users-

With this command's help, one sees all the details of every user logged in to the current system. The syntax of this command is the same
except the additional option "-a", as we can see in the given syntax:

Syntax

who -a

Output

41
2. To display information about all active processes that are spawned by the NIT process-

This command will help you to display essential information as well as each and every active process.

Syntax

who -p -h

Output

3. To display the status of the user's message as -, + or?

This command will help us to display the status of the user's message. Syntax of this command given below:

42
Syntax

who -T -H

Output

4. To display the whole list of logged-in users-

This command will help us to display the whole list of the logged-in users. Syntax of this command given below:

Syntax

who -u

Output

43
5. To display system login process details-

One can use this command to see the login process. The syntax of the command is given below:

Syntax:

who -l -H

Output

6. To display the system's username-

This command is generally used to know about the actual system's username. The syntax of the command is given below:

Syntax

whoami

Output

44
7. To display the list of users and their activities-

With the help of this command, you can see the complete list of users and their activities as well, which are logged-in the current system.
The command is given below:

Syntax

Output

Date Command

The date command is used to display date, time, time zone, and more.

Syntax:

45
date

Output:

-u, --utc, --universal: It is used to display or set the UTC.

--help: It is used to display the help manual.

--version: It displays the version information.

Formatting options

%a: It is used to display the abbreviated weekday name (e.g., Sun)

%A: It is used to display the full weekday name (e.g., Sunday)

%b: it is used to display the abbreviated month name (e.g., Jan)

%B: It is used to display the full month name (e.g., January)

%c: It is used to display the date and time (e.g., Thu Mar 3 [Link] 2005)

Stty

stty command in Linux with Examples


stty command in Linux is used to change and print terminal line settings. Basically, this command shows or changes terminal
characteristics.
Syntax:

46
stty [-F DEVICE | --file=DEVICE] [SETTING]...
stty [-F DEVICE | --file=DEVICE] [-a|--all]
stty [-F DEVICE | --file=DEVICE] [-g|--save]
Example: It will display the characteristics of the terminal.

Options:
• stty –all: This option print all current settings in human-readable form.
stty --all

• stty -g: This option will print all current settings in a stty-readable form.
stty -g

• stty -F : This option will open and use the specified DEVICE instead of stdin.
Example:
stty -F D/
• stty –version: This option will show the version information and exit.
stty --version

47
pwd Command

The pwd command is used to display the location of the current working directory.

Syntax:

pwd

Output:

Cd

cd Command in Linux/Unix | Linux Change Directory

Linux cd command is used to change the current working directory ( i.e., in which the current user is working). The "cd" stands
for 'change directory.' It is one of the most frequently used commands in the Linux terminal.

Syntax:

48
cd <dirname>

It is one of the most important and common commands in the Linux system and will be used repeatedly. With the help of this command,
we can move all over our directories in our system. We can go to our previous directory or previous to the next directory, or anywhere.

rmkdir Command

The mkdir command is used to create a new directory under any directory.

Syntax:

mkdir <directory name>

Output:

rmdir Command

The rmdir command is used to delete a directory.

Syntax:

rmdir <directory name>

Output:

Ls

49
ls Command

The ls command is used to display a list of content of a directory.

Syntax:

ls

Output:

Cp

cp Command

The cp command is used to copy a file or directory.

Syntax:

To copy in the same directory:

cp <existing file name> <new file name>

To copy in a different directory:

50
Output:

Mv

mv Command

The mv command is used to move a file or a directory form one location to another location.

Syntax:

mv <file name> <directory path>

Output:

rm

rm Command

The rm command is used to remove a file.

Syntax:

rm <file name>

Output:

51
Cat

cat Command

The cat command is a multi-purpose utility in the Linux system. It can be used to create a file, display content of the file, copy the
content of one file to another file, and more.

Syntax:

cat [OPTION]... [FILE]..

To create a file, execute it as follows:

cat > <file name>


// Enter file content

Press "CTRL+ D" keys to save the file. To display the content of the file, execute it as follows:

cat <file name>

Output:

more command

52
The more command is quite similar to the cat command, as it is used to display the file content in the same way that the cat command
does. The only difference between both commands is that, in case of larger files, the more command displays screenful output at a time.

In more command, the following keys are used to scroll the page:

ENTER key: To scroll down page by line.

Space bar: To move to the next page.

b key: To move to the previous page.

/ key: To search the string.

Syntax:

more <file name>

more [Link]

output:

wc Command

53
The wc command is used to count the lines, words, and characters in a file.

Syntax:

wc <file name>

Output:

Lp

lp: submits files for printing or alters a pending job..

DESCRIPTION

lp command arranges for the files specified by the Files parameter and their associated information (called a request) to be printed by a
line printer. If you do not specify a value for the Files parameter, the lp command accepts standard input. The file name - (dash) represents
standard input and can be specified on the command line in addition to files. The lp command sends the requests in the order specified.
If the job is submitted to a local print queue, the lp command displays the following to standard output: Job number is: nnn where nnn
is the assigned job number. To suppress the job number use the -s flag.

od Command

The od command is used to display the content of a file in different s, such as hexadecimal, octal, and ASCII characters.

Syntax:

od -b <fileName> // Octal format


od -t x1 <fileName> // Hexa decimal format
od -c <fileName> // ASCII character format

54
Output:

Tar

The GNU tar (short for Tape ARchiver) command is the most widely used archiving utility in Linux systems. Available directly in the
terminal, the tar command helps create, extract, and list archive contents.

Tar Command Syntax

The tar command general syntax is:

tar <operation mode> <option(s)> <archive> <file(s) or location(s)>

• Operation mode indicates which operation executes on the files (creation, extraction, etc.). The command allows and requires
only one operation.
• Options modify the operation mode and are not necessary. There is no limit on the number of options.
• The archive is the file name and extension.
• The file name(s) is a space-separated list for extraction or compression or wildcard matched name.

55
There are three possible syntax styles to use the operations and options:

1. Traditional style, clustered together without any dashes.

For example:

tar cfv <archive> <file(s) or location(s)>

2. UNIX short option style, using a single dash and clustered options:

tar -cfv <archive> <file(s) or location(s)>

Alternatively, a dash before each option:

tar -c -f -v <archive> <file(s) or location(s)>

3. GNU long-option style with a double-dash and a descriptive option name:

tar --create --file <archive> --verbose <file(s) or location(s)>

All three styles can be used in a single tar command.

Examples of tar command

56
Some of the important examples which are widely used in tar command are as follows:

1. Making an uncompressed tar archive with -cvf option

This option makes a tar file known as [Link]. It is the archive of every .txt file inside mydir directory.

The command is as follows:

$ tar cvf [Link] *.txt

2. Extracting files through the archive with -xvf option

This option can extract files through archives.

The command is as follows:

$ tar xvf [Link]

57
3. Extracting the gzip tar archive with -xvzf option

This option can extract the files through [Link] tar archived files.

The command is as follows:

$ tar xvzf [Link]

Gzip

58
gzip command compresses files. Each single file is compressed into a single file. The compressed file consists of a GNU zip header and
deflated data. If given a file as an argument, gzip compresses the file, adds a “.gz” suffix, and deletes the original file. With no arguments,
gzip compresses the standard input and writes the compressed file to the standard output.
Syntax of the gzip Command
The basic syntax of the gzip command is straightforward:
gzip [Options] [filenames]
This syntax allows users to compress a specified file.
Options Available in gzip Command
Options Description

Forcefully compress a file even if a


compressed version with the same name
-f already exists.

Compress a file and keep the original file,


resulting in both the compressed and
-k original files.

-L Display the gzip license for the software.

To decompress a file you can use gunzip command and your original file will be back.

Syntax:

gzip <file1> <file2> <file3>. . .


example:
gzip [Link] [Link]

59
Compressing Multi Files Together

If you want to compress more than one file together, you can use 'cat' and gzip command with pipe command.

Syntax:

cat <file1> <file2>. . | gzip > <[Link]>

Example:

cat [Link] [Link] | gzip > [Link]

NETWORK commands:

unlink

60
The unlink command is a fundamental utility in Linux, designed to remove a specified file. It operates similarly to the rm command
but offers a more straightforward approach for deleting individual files. It allows users to efficiently delete files or symbolic links.

unlink is specifically designed for removing individual files without prompting.

Syntax of “unlink” Command

The basic syntax of the unlink command is:

unlink [file_name]

1. Delete a File from Current DirectoryIf you are working inside the Desktop directory and the directory contains a file named

“[Link]” which you want to delete using the unlink command. Run the following command inside the current directory to delete that

file:

unlink [Link]

OUTPUT:

61
2. Delete a Symbolic Link Using “unlink” Command

The process of deleting a symbolic link is identical to the process of deleting a file. According to the image below, there is a symbolic
link named “[Link]” inside my current directory

To delete a symlink run the following command:

unlink [Link]

OUTPUT:

Du command

There are many ways by which we can check the Linux system disk space. We can use a third-party app which displays the available
disk space. Another way is the command-line by the Linux Terminal, some of which are df and du, where du means disk space used
and df means disk space free.

62
du Command

We can check the disk space with the help of the du command. The full-form of du is "Disk Usage." The du command shows the usage
of disk. The du command will show you the disk usage for specific directories in Linux.

Syntax:

$ du

du -h: - This will show you the disk usage in a human-readable format for each directory and subdirectory.

Output:

du -a: - This will show you the disk usage for all the files.

Syntax:

$ du -a
Output:

63
du -s: - This will show you the total disk space used by a specific directory or file.

Syntax:

1. $ du -s

df command

The full-form of df command is "disk-free,". Using this command, we can check the used and available disk space in the Linux
system.

Syntax:

$ df [optios].........FILESYSTEM.........

When we use this command with no parameter, then this command will show you the information related to all the mounted file
systems:

$df

Output:

64
Display Information of /home File System

If we want to see the information of only the device /home file system in the human-readable format, then we can use the following
command:

$ df -hT /home

Display Information of File System in Bytes

If want to see the information and usage of file system in 1024-byte blocks, then we can use the '-k' option.

Syntax:

$ df -k

65
Linux mount

The mount command attaches the filesystem of an external device to the filesystem of a system.

It instructs the operating system that filesystem is ready to use and associate it with a particular point in the system's hierarchy. Mounting
will make files, directories and devices available to the users.

It mounts the external storage devices like hard disks, pen drives, USBs etc.

To mount a device generally, following syntax is used

Syntax:

mount -t type <device> <directory>

Here, this command instructs kernel to attach filesystem of device at the specified directory.

If destination directory is not mentioned, by default, it mounts the device in the /etc/fstab file.

List currently mounted file systems

This command display all currently mounted file system on a system.

Syntax:

mount
output:

66
umount

The umount command detaches the file system(s) mentioned from the file hierarchy. A file system is specified by giving the directory
where it has been mounted

Syntax of the ‘umount’ command in Linux


umount [OPTIONS] [TARGET]
• OPTIONS: Optional flags or parameters that modify the behavior of the umount command.
• TARGET: The directory or device path indicating the location to be unmounted.

• For example, if we want to unmount the previously mounted USB stick and ISO image:
• root# umount /dev/sdd1
• root# umount /mnt/archIso

Find command:

The find command is used to find a particular file within a directory. It also supports various options to find a file such as byname, by
type, by date, and more.

The following symbols are used after the find command:

(.) : For current directory name

67
(/) : For root

Syntax:

1. find . -name "*.pdf"

Unmask command

unmask is a command used to remove the mask from a systemd unit, usually a service. It reverses the masking of a service,
making it operational and accessible for system administrators.

we need to unmask a service when we require activation or to regain control over a particular service. When a service needs to be
operational or configured according to specific requirements, unmasking becomes necessary.

To unmask the service, we need to find the path where the masked service file is located. We can search for the service file using
the find command:
$ sudo find /etc /usr/lib -name "[Link]*"

Ulimit:

ulimit is admin access required Linux shell command which is used to see, set, or limit the resource usage of the current user. It is
used to return the number of open file descriptors for each process. It is also used to set restrictions on the resources used by a
process.
Syntax:

68
To check the ulimit value use the following command:
ulimit -a

output:

Working with ulimit commands:


1. To display maximum users process or for showing maximum user process limit for the logged-in user.
ulimit -u
output:

2. For showing the maximum file size a user can have.


ulimit -f

3 For showing maximum memory size for the current user.


ulimit -m

69
output:

PS command

ps command is used to view currently running processes on the system. It helps us to determine which process is doing what in our
system, how much memory it is using, how much CPU space it occupies, user ID, command name, etc . ps command shows details of
a selection of the running processes. If we wish repetitive selection updates and displayed information

Syntax:

ps

4 columns are displayed as the output.

o PID is the process ID of running command


o TTY is the type of terminal where current command is running

70
o TIME tells how much time is used by CPU to run the process
o CMD is current command

ps command supports 3 types of usage syntax style

o Unix, may be grouped and preceded by hyphen


o BSD, may be grouped but not preceded by hyphen
o GNU, long options and preceded by double hyphens

Linux ps -ef and ps -aux

To display all currently running processes in full format on a system two types of commands are used.

Syntax:

ps -ef
ps -aux

e displays all the processes

f displays full format listing

Syntax:
ps -ef

71
Syntax:

ps -aux

w command

w command is used to check the current system activity. This can be a user activity or any process related to the system. You can list
the current users on your Linux machine with w command.
syntax
$w
Output:
[Link] up 1:12, 5 users, load average: 0.54, 0.46, 0.12
USER TTY LOGIN@ IDLE JCPU PCPU WHAT

72
İpcisco :0 10:12 ?xdm? 4:07 0.11s gdm-session-worker [pam/gdm-password]

FTP
FTP is file transfer protocol. It’s the most preferred protocol for data transfer amongst computers.

You can use FTP to –

• Logging in and establishing a connection with a remote host


• Upload and download files

Navigating through directories

• Browsing contents of the directories

Syntax:
ftp hostname=""
Once you enter this command, it will ask you for authentication via username and password.

Once a connection is established, and you are logged in, you may use the following commands to perform different actions.
Command Function
dir Display files in the current directory of a remote computer
cd “dirname” change directory to “dirname” on a remote computer
put file upload ‘file’ from local to remote computer
get file Download ‘file’ from remote to local computer
quit Logout

73
Output:

Telnet
Telnet helps to –

74
• connect to a remote Linux computer
• run programs remotely and conduct administration

This utility is similar to the Remote Desktop feature found in Windows Machine.

The syntax for this utility is:

telnet hostname=""
output:

Arp Command
The ARP (Address Resolution Protocol) command is used to display and modify ARP cache, which contains the mapping of IP
address to MAC address. The system’s TCP/IP stack uses ARP in order to determine the MAC address associated with an IP
address.

75
Syntax:
Arp
OUTPUT:

Finger:

The finger command displays information about users on a given host. The The host can be either local or remote.

Finger may be disabled on other systems for security reasons.

Check all the logged-in users on the local machine –

Syntax:

$ finger
Output:
Login Name Tty Idle Login Time Office
amrood pts/0 Jun 25 08:03 ([Link])

76
Get information about a specific user available on the local machine −

$ finger amrood
Login: amrood Name: (null)
Directory: /home/amrood Shell: /bin/bash
rlogin

On Unix-like operating systems, the rlogin command remotely logs in to a system.

Syntax

rlogin [-8EKLdx] [-e char] [-l username] host

Options

-8 Allows an eight-bit input data path at all times; otherwise, parity bits are stripped except when the remote side's stop and start characters are othe

-E Stops any character from being recognized as an escape character. When used with the -8 option, this provides a completely transparent connecti

-L The -L option allows the rlogin session to run in "litout" mode, a special BSD terminal mode.

-d Turns on socket debugging on the TCP sockets used for communication with the remote host.

Examples

rlogin -l hope [Link]

77
Login as user hope to the remote system [Link].

TEXT PROCESSING AND BACKUP UTILITIES


Grep command:

The grep command in Unix/Linux is a powerful tool used for searching and manipulating text patterns within files. Its name is
derived from the ed (editor) command g/re/p (globally search for a regular expression and print matching lines), which reflects its
core functionality. grep is widely used by programmers, system administrators, and users alike for its efficiency and versatility in
handling text data.

Syntax of grep Command in Unix/Linux


The basic syntax of the `grep` command is as follows:
grep [options] pattern [files]

[options]: These are command-line flags that modify the behavior of grep.
[pattern]: This is the regular expression you want to search for.
[file]: This is the name of the file(s) you want to search within. You can specify multiple files for simultaneous searching.
Options Available in grep Command
Options Description

This prints only a count of the lines that


-c match a pattern

78
Options Description

Display the matched lines, but do not display


-h the filenames.

Print only the matched parts of a matching


line, with each such part on a separate output
-o line.

Consider the below file as an input.

cat > [Link]

unix is great os. unix was developed in Bell labs.

learn operating system.

Unix linux which one you choose.

uNix is easy to [Link] is a multiuser [Link] unix .unix is a powerful.

Displaying the Count of Number of Matches Using grep


We can find the number of lines that matches the given string/pattern
grep -c "unix" [Link]

Output:

79
Displaying only the matched pattern Using grep
By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by
using the -o option.
grep -o "unix" [Link]

Output:

Case insensitive search


The -i option enables to search for a string case insensitively in the given file. It matches the words like “UNIX”, “Unix”, “unix”.
grep -i "UNix" [Link]

Output:

80
Egrep:

egrep is a pattern searching command which belongs to the family of grep functions. It works the same way as grep -E does. It
treats the pattern as an extended regular expression and prints out the lines that match the pattern. If there are several files with the
matching pattern, it also displays the file names for each line

egrep [ options ] 'PATTERN' files

Example:

c: Used to counts and prints the number of lines that matched the pattern and not the lines.

-i: Ignore the case of the pattern while matching.

81
-l: Prints only the names of the files that matched. It does not mention the matching line numbers or any other information.

Fgrep:

The fgrep filter is used to search for the fixed-character strings in a file. There can be multiple files also to be searched. This
command is useful when you need to search for strings which contain lots of regular expression metacharacters, such as “^”, “$”,
etc.

Syntax:
fgrep [options] [ -e pattern_list] [pattern] [file]
Options with Description:
• -c : It is used to print only a count of the lines which contain the pattern.
• -h : Used to display the matched lines.
• -v : Print all lines except those contain the pattern.

Example:
fgrep -i "geeks*forgeeks" para
Output:
Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.
Geeks*forgeeks is best for learni\ng.

82
-c option: Displaying the count of number of matches. We can find the number of lines that match the given string.
Example:
$fgrep -c "usin.g" para
Output:
1

-h option: To display the matched lines.


Example:
fgrep -h "usin.g" para
Output:
Hi, @re you usin.g geeks*forgeeks for learni\ng computer science con/cepts.

AWK:

Awk is a scripting language used for manipulating data and generating reports. The awk command programming language requires
no compiling and allows the user to use variables, numeric functions, string functions, and logical operators.
Awk is a utility that enables a programmer to write tiny but effective programs in the form of statements that define text patterns
that are to be searched for in each line of a document and the action that is to be taken when a match is found within a line. Awk is
mostly used for pattern scanning and processing. It searches one or more files to see if they contain lines that matches with the
specified patterns and then perform the associated actions.
Awk is abbreviated from the names of the developers – Aho, Weinberger, and Kernighan.

83
1. AWK Operations:
(a) Scans a file line by line
(b) Splits each input line into fields
(c) Compares input line/fields to pattern
(d) Performs action(s) on matched lines
2. Useful For:
(a) Transform data files
(b) Produce formatted reports
3. Programming Constructs:
(a) Format output lines
(b) Arithmetic and string operations
(c) Conditionals and loops

Example:
Consider the following text file as the input file for all cases below:
$cat > [Link]
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000
1. Default behavior of Awk: By default Awk prints every line of data from the specified file.
$ awk '{print}' [Link]
Output:
ajay manager account 45000
sunil clerk account 25000
varun manager sales 50000
amit manager account 47000

84
tarun peon sales 15000
deepak clerk sales 23000
sunil peon sales 13000
satvik director purchase 80000

2. Print the lines which match the given pattern.


$ awk '/manager/ {print}' [Link]
Output:
ajay manager account 45000
varun manager sales 50000
amit manager account 47000

head:

The head command, as the name implies, print the top N number of data of the given input. By default, it prints the first 10 lines of
the specified files. If more than one file name is provided then data from each file is preceded by its file name.

Syntax:

head [OPTION]... [FILE]...


$ cat [Link]
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Jharkhand

85
Karnataka
Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal
$ cat [Link]
Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar

Example:

86
$ head [Link]
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir

. -n num: Prints the first ‘num’ lines instead of first 10 lines. num is mandatory to be specified in command otherwise it displays
an error.

$ head -n 5 [Link]
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh

2. -c num: Prints the first ‘num’ bytes from the file specified. Newline count as a single character, so if head prints out a newline, it
will count it as a byte. num is mandatory to be specified in command otherwise displays an error.

$ head -c 6 [Link]
Andhra

3. -q: It is used if more than 1 file is given. Because of this command, data from each file is not precedes by its file name.

87
Without using -q option
$ head [Link] [Link]
==> [Link] <==
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir

==> [Link] <==


Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar

With using -q option


$ head -q [Link] [Link]
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar

88
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar

Tail command

The tail command, as the name implies, prints the last N number of data of the given input. By default, it prints the last 10 lines of
the specified files. If more than one file name is provided then data from each file is preceded by its file name.

Syntax of Tail Command in Linux


tail [OPTION]... [FILE]...
cat [Link]
Andhra Pradesh
Arunachal Pradesh
Assam

89
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Jharkhand
Karnataka
Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal

Example:

90
tail [Link]

Here we will only get names of last 10 states after using tail command.

1. `-n` num Option in Tail Command in Linux


Prints the last ‘num’ lines instead of last 10 lines. num is mandatory to be specified in command otherwise it displays an error. This
command can also be written as without symbolizing ‘n’ character but ‘-‘ sign is mandatory.
tail -n 3 [Link]

91
-c` num Option in Tail Command in Linux
Prints the last ‘num’ bytes from the file specified. Newline count as a single character, so if tail prints out a newline, it will count it
as a byte. In this option it is mandatory to write -c followed by positive or negative num depends upon the requirement. By +num,
it display all the data after skipping num bytes from starting of the specified file and by -num, it display the last num bytes from
the file specified.

tail -c 7 [Link]

`-q` Option in Tail Command in Linux


It is used if more than 1 file is given. Because of this command, data from each file is not precedes by its file name.

92
93
94
tr command:

The tr command is a UNIX command-line utility for translating or deleting characters. It supports a range of transformations
including uppercase to lowercase, squeezing repeating characters, deleting specific characters, and basic find and replace. It can be
used with UNIX pipes to support more complex translation. tr stands for translate.
Syntax :
$ tr [OPTION] SET1 [SET2]
$ cat greekfile
Output:
WELCOME TO
GeeksforGeeks
$ cat greekfile | tr [a-z] [A-Z]
Output:
WELCOME TO
GEEKSFORGEEKS

Tee command

tee command
reads the standard input and writes it to both the standard output and one or more files. The command is named after the T-splitter
used in plumbing. It basically breaks the output of a program so that it can be both displayed and saved in a file. It does both the
tasks simultaneously, copies the result into the specified files or variables and also display the result.

95
SYNTAX:
tee [OPTION]... [FILE]...
Options :

96
97
–version Option :
It gives the version information and exit.
SYNTAX :
geek@HP:~$ tee --version

SORT command is used to sort a file, arranging the records in a particular order. By default, the sort command sorts file assuming
the contents are ASCII. Using options in the sort command can also be used to sort numerically.
• SORT command sorts the contents of a text file, line by line.
• sort is a standard command-line program that prints the lines of its input or concatenation of all files listed in its argument list in
sorted order.
• The sort command is a command-line utility for sorting lines of text files. It supports sorting alphabetically, in reverse order, by
number, by month, and can also remove duplicates.
• The sort command can also sort by items not at the beginning of the line, ignore case sensitivity, and return whether a file is
sorted or not. Sorting is done based on one or more sort keys extracted from each line of input.

The sort command follows these features as stated below:


1. Lines starting with a number will appear before lines starting with a letter.

98
2. Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in
the alphabet.
3. Lines starting with a uppercase letter will appear before lines starting with the same letter in lowercase.

Syntax:

Sort filename

Example:

nl command:

Linux offers a wide range of commands for text formatting and editing. While editing a text file, you might want to display the
lines with line numbers appended before them, and here comes the role-play of the nl command in Linux. nl command is a
Unix/Linux utility that is used for numbering lines, accepting input either from a file or from STDIN. It copies each specified file
to STDOUT, with line numbers appended before the lines.
Syntax:

99
nl [OPTION]... [FILE]...

Uniq command:

The uniq command in Linux is a command-line utility that reports or filters out the repeated lines in a file. In simple words, uniq is
the tool that helps to detect the adjacent duplicate lines and also deletes the duplicate lines. uniq filters out the adjacent matching
lines from the input file(that is required as an argument) and writes the filtered data to the output file.

Syntax of uniq Command


The basic syntax of the `uniq` command is:
uniq [OPTIONS] [INPUT_FILE [OUTPUT_FILE]]
To remove duplicate lines from `[Link]`, we can use the `uniq` command:
100
uniq [Link]

to Display Repeated Lines Using `uniq` Command in Linux


The `-d` option only prints duplicate lines:
uniq -d [Link]

to Display Unique Lines Using `uniq` Command in Linux


The `-u` option prints only unique lines:
uniq -u [Link]

Cut command

The cut command in linux is a command for cutting out the sections from each line of files and writing the result to standard output.
It can be used to cut parts of a line by byte position, character, and field. The cut command slices a line and extracts the text. It is
necessary to specify an option with a command otherwise it gives an error. If more than one file name is provided then data from
each file is not preceded by its file name.

Syntax of cut Command


The basic syntax of the cut command is:
cut OPTION... [FILE]...

101
Where
`OPTION` specifies the desired behavior
`FILE` represents the input file.

$ cat [Link]
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh

cut -b 1,2,3 [Link]

Paste:

When no file is specified, or put dash (“-“) instead of file name, paste reads from standard input and gives output as it is until a
interrupt command [Ctrl-c] is given. Syntax:
paste [OPTION]... [FILES]...
$ cat state
Arunachal Pradesh
Assam
Andhra Pradesh
Bihar
Chhattisgrah

$ cat capital
Itanagar
Dispur

102
Hyderabad
Patna
Raipur

$ paste number state capital


1 Arunachal Pradesh Itanagar
2 Assam Dispur
3 Andhra Pradesh Hyderabad
4 Bihar Patna
5 Chhattisgrah Raipur

Join

The join command in UNIX is a command line utility for joining lines of two files on a common field.
Suppose you have two files and there is a need to combine these two files in a way that the output makes even more [Link]
example, there could be a file containing names and the other containing ID’s and the requirement is to combine both files in such a
way that the names and corresponding ID’s appear in the same line. join command is the tool for it. join command is used to join
the two files based on a key field present in both the files. The input file can be separated by white space or any delimiter
Syntax:
$join [OPTION] FILE1 FILE2
// displaying the contents of first file //
$cat [Link]
1 AAYUSH
2 APAAR
3 HEMANT
4 KARTIK

// displaying contents of second file //


$cat [Link]
1 101
2 102

103
3 103
4 104
$join [Link] [Link]
1 AAYUSH 101
2 APAAR 102
3 HEMANT 103
4 KARTIK 104

Comm command

comm compare two sorted files line by line and write to standard output; the lines that are common and the lines that are unique.

Syntax :
$comm [OPTION]... FILE1 FILE2
$cat [Link]
Apaar
Ayush Rajput
Deepak
Hemant

// displaying contents of file2 //


$cat [Link]
Apaar
Hemant
Lucky
Pranjal Thakral

Output:

$comm [Link] [Link]

104
Apaar
Ayush Rajput

Deepak
Hemant
Lucky
Pranjal Thakral
Diff

managing and comparing files is a common task for system administrators and developers alike. The ability to compare files line by
line is crucial for identifying differences, debugging code, and ensuring the integrity of data. One powerful tool that facilitates this
process is the diff command. In this article, we will explore how to use the diff command to compare files line by line in Linux.

Syntax of diff Command


The basic syntax of the diff command is as follows:
diff [OPTION]... FILE1 FILE2
Here, `FILE1` and `FILE2` are the two files you want to compare.

cat [Link]
cat [Link]

105
cmp

cmp command in Linux/UNIX is used to compare the two files byte by byte and helps you to find out whether the two files are
identical or not.
• When cmp is used for comparison between two files, it reports the location of the first mismatch to the screen if difference is
found and if no difference is found i.e the files compared are identical.
• cmp displays no message and simply returns the prompt if the files compared are identical.

Syntax:
cmp [OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]]

SKIP1 ,SKIP2 & OPTION are optional


and FILE1 & FILE2 refer to the filenames .

1. If the files are identical : you will see something like this on your screen:
$cmp [Link] [Link]
$_
/*indicating that the files are identical*/

106
cpio stands for “copy in, copy out“. It is used for processing the archive files like *.cpio or *.tar. This command can copy files to
and from archives.
Synopsis:
• Copy-out Mode: Copy files named in name-list to the archive
Syntax:
cpio -o < name-list > archive
• Copy-in Mode: Extract files from the archive
Syntax:
cpio -i < archive
• Copy-pass Mode: Copy files named in name-list to destination-directory
Syntax:
cpio -p destination-directory < name-list

107
Paste command is one of the useful commands in Unix IMPORTANT QUESTIONS - UNIT I

1. Draw the architecture of Linux and explain.

2. Explain the following Linux commands with syntax and example.


a. PATH, Man, Echo, Printf, Script, Passwd, Uname, Who, Date, Stty, Pwd, cd, mkdir, rmdir, ls, cp, mv, rm, cat, more, wc, lp, od, tar,
gzip,

3. Explain the following networking commands with syntax and example.


a. unlink, du, df, mount, umount, find, unmask, ulimit, ps, w, finger, arp, ftp, telnet, rlogin.

4. Explain the following Text Processing Utility commands with syntax and example.
a. Tail, head , sort, nl, uniq, grep, egrep, fgrep, cut, paste, join, tee, pg, comm, cmp, diff, tr, awk, cpio

108

You might also like