0% found this document useful (0 votes)
11 views51 pages

OS Unit - IV

Linux is an open-source operating system based on the Linux kernel, initially released in 1991, and is widely used in various devices including personal computers and embedded systems. It comprises several components such as the kernel, system libraries, and shell, and offers advantages like security, flexibility, and community support, while also having disadvantages like a steeper learning curve for beginners. The document also details the Linux directory structure, file types, and the process of logging in and out of the system.
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)
11 views51 pages

OS Unit - IV

Linux is an open-source operating system based on the Linux kernel, initially released in 1991, and is widely used in various devices including personal computers and embedded systems. It comprises several components such as the kernel, system libraries, and shell, and offers advantages like security, flexibility, and community support, while also having disadvantages like a steeper learning curve for beginners. The document also details the Linux directory structure, file types, and the process of logging in and out of the system.
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/ 51

Operating System

UNIT – IV

BASIC CONCEPT OF LINUX

INTRODUCTION
Linux is a community of open-source Unix-like operating systems that are
based on the Linux Kernel. It was initially released by Linus Torvalds on September
17, 1991. It is a free and open-source operating system and the source code can be
modified and distributed to anyone commercially or noncommercially under the
GNU General Public License.
Initially, Linux was created for personal computers and gradually it was
used in other machines like servers, mainframe computers, supercomputers, etc.
Nowadays, Linux is also used in embedded systems like routers, automation
controls, televisions, digital video recorders, video game consoles, smartwatches,
etc. The biggest success of Linux is Android (operating system) it is based on the
Linux kernel that is running on smartphones and tablets. Android Linux has the
largest installed base of all general-purpose operating systems. Linux is generally
packaged in a Linux distribution.

Linux Distribution- Linux distribution is an operating system that is made


up of a collection of software based on the Linux kernel or you can say distribution
contains the Linux kernel and supporting libraries and software. You can get Linux
based operating system by downloading one of the Linux distributions and these
distributions are available for different types of devices like embedded devices,
personal computers, etc. Around 600 + Linux Distributions are available and some
of the popular Linux distributions are:
MX Linux
Manjaro
Linux Mint
elementary
Ubuntu
Debian
Solus
Fedora
openSUSE
Deepin

Components of Linux System- Linux architecture has the following


components:

Kernel: Kernel is the core of the Linux-based operating system. It virtualizes the
common hardware resources of the computer to provide each process with its
virtual resources. This makes the process seem as if it is the sole process running

Page 109 of 159


Operating System

on the machine. The kernel is also responsible for preventing and mitigating
conflicts between different processes. Different types of the kernel are:
Monolithic Kernel
Hybrid kernels
Exo kernels
Microkernels

System Library: These are the special types of functions that are used to
implement the functionality of the operating system.

Shell: It is an interface to the kernel which hides the complexity of the kernel’s
functions from the users. It takes commands from the user and executes the
kernel’s functions.

Hardware Layer: This layer consists of all peripheral devices like RAM/ HDD/
CPU, etc.

System Utility: It provides the functionalities of an operating system to the


user.

Advantages of Linux
➢ The main advantage of Linux is that it is an open-source operating system.
This means the source code is easily available for everyone and you are allowed
to contribute, modify, and distribute the code to anyone without any
permissions.
➢ In terms of security, Linux is more secure than any other operating system. It
does not mean that Linux is 100 percent secure, it has some malware, but is
less vulnerable than any other operating system. So, it does not require any
anti-virus software.
➢ The software updates in Linux are easy and frequent.
➢ Various Linux distributions are available so that you can use them according to
your requirements or according to your taste.
➢ Linux is freely available to use on the internet.

Page 110 of 159


Operating System

➢ It has large community support.


➢ It provides high stability. It rarely slows down or freezes and there is no need to
reboot it after a short time.
➢ It maintains the privacy of the user.
➢ The performance of the Linux system is much higher than other operating
systems. It allows a large number of people to work at the same time and it
handles them efficiently.
➢ It is network-friendly.
➢ The flexibility of Linux is high. There is no need to install a complete Linux
suite; you can only install the required components.
➢ Linux is compatible with a large number of file formats.
➢ It is fast and easy to install from the web. It can also install on any hardware,
even on your old computer system.
➢ It performs all tasks properly even if it has limited space on the hard disk.

Disadvantages of Linux
➢ It is not very user-friendly. So, it may be confusing for beginners.
➢ It has small peripheral hardware drivers as compared to Windows.

LOGGING IN AND LOGGING OUT


Once the booting procedure is completed, the Linux operating system is
loaded into memory. To enter the system, we need to identify ourselves by a
system, which is known as logging in the Linux operating system.
A login, logging in, or logging on is the entering of identifier information into
a system by a user to access the system, i.e., a computer or a website. A login
requires the user to enter two pieces of information:

1. User Name- A user name or account name is a string (i.e., sequence of


characters) that uniquely identifies the user. User names can be the same as or
related to the real name of the user or different.
2. Password- A password is also a string, but it differs from a username, which
is to be kept secret and is known only to its user or to a system administrator.
This information is entered into a login window on a GUI or the command
line in a console (i.e., all text mode) depending on the system and situation.
If the password is correct, the system may display the following message, at
the end it displays a Linux prompt (displays $ for normal user or it displays % for
superuser), indicating that the system is ready to accept commands from the user.
Welcome to LINUX System
Last login Mon Aug 11 8:45 tty02
$

Page 111 of 159


Operating System

LOGOUT- To shut down the normal user terminal of system commands may
vary from different versions of the operating system. One may try following
commands to shutdown
➢ <ctrl> + d
➢ <ctrl> + z
➢ Logout
➢ logoff
On executing the above command, it disconnects our terminal from the
server. When a user logs out, the following message may appear on the screen.
Safe to power off
Or
Press any key to reboot
There are two ways of logging out
1. Logging Out of the system from a (text) terminal- To log out (exit) of a
text terminal, type logout.
2. Logging Out of the System from an X-Windows session- Use the mouse
to exit an X-Windows session; click the right button and choose the “Logout” or
“Exit” option.

ANATOMY OF LINUX OS
The Linux operating system's architecture mainly contains some of the
components: the Kernel, System Library, Hardware layer, System, and Shell utility.

Kernel: The kernel is one of the core sections of an operating system. It is


responsible for each of the major actions of the Linux OS. This operating system
contains distinct types of modules and cooperates with underlying hardware
directly. The kernel facilitates the required abstraction for hiding details of low-level
hardware or application programs in the system. There are some of the important
kernel types mentioned below:
Monolithic Kernel

Page 112 of 159


Operating System

Microkernels
Exo kernels
Hybrid kernels

System Libraries: These libraries can be specified as having some special


functions. These are applied for implementing the operating system's functionality
and don't need code access rights for the modules of the kernel.

System Utility Programs: It is responsible for doing specialized level and


individual activities.

Hardware layer: Linux operating system contains a hardware layer that


consists of several peripheral devices like CPU, HDD, and RAM.

Shell- It is an interface between the kernel and the user. It can afford the services
of kernel. It can take commands through the user and runs the functions of the
kernel. The shell is available in distinct types of OSes. These operating systems are
categorized into two different types, which are graphical shells and command-line
shells.
The graphical line shells facilitate the graphical user interface, while the
command line shells facilitate the command line interface. Thus, both of these
shells implement operations. However, the graphical user interface shells work
slower as compared to the command-line interface shells.
There are a few types of these shells which are categorized as follows:
Korn shell
Bourne shell
C shell
POSIX shell

DIRECTORY STRUCTURE
In Linux/Unix operating system, everything is a file, even directories are
files, files are files, and devices like mice, keyboards, printers, etc, are also files.
Here we are going to see the Directory Structure in Linux.

Types of files in the Linux system


General Files- It is also called ordinary files. It may be an image, video,
program, or simple text file. These types of files can be in ASCII or Binary format. It
is the most commonly used file in the Linux system.

Directory Files- These types of files are a warehouse for other file types. It may
be a directory file within a directory (subdirectory).

Device Files- In a Windows-like operating system, devices like CD-ROM, and


hard drives are represented as drive letters like F: G: H, whereas in the Linux
system devices are represented as files. As, /dev/sda1, /dev/sda2, and so on.

Page 113 of 159


Operating System

We know that in a Windows-like operating system, files are stored in


different folders on different data drives like C: D: E: whereas in the Linux/Unix
operating system files are stored in a tree-like structure starting with the root
directory as shown in the below diagram.

The base of the Linux/Unix file system hierarchy begins at the root and
everything starts with the root directory.
These are the common top-level directories associated with the root
directory:
/Directory- The root directory, denoted by a single forward slash (/), is the
uppermost directory in the Linux directory structure. It contains all directories,
sub-directories, and files on your Linux system. It’s from the root directory where
the Linux directory hierarchy starts.

/root Directory- The /root directory is the home directory for the root user,
which is also referred to as the root user’s home directory (and not as the root (/)
directory).
The root account, also referred to as the superuser, administrative user,
system administrator or just the root user, has all the access to commands and
system files in Linux.

/boot Directory- This is one of the most vital directories in a Linux system. As
the name implies, the boot directory contains Linux boot files such as the
bootloader, the kernel, and its associated files. Files such as ‘vmlinuz’ represent the
compressed image of the Linux kernel.

/bin Directory - The /bin directory contains user binaries, executable


programs, and common system commands that are used by all users in the
system. These include ls, pwd, cat, mkdir, cd, mv, cp, du, df, tar, rpm, wc, history,
etc.

/etc Directory - The /etc directory contains system configuration files for all
the services, scripts, and third-party applications that are installed. This directory
is considered the nerve center of the Linux system.

/home Directory - The /home directory is a directory that contains a user’s


folders and files. On a graphical Linux system, the home directory, by default,

Page 114 of 159


Operating System

contains folders such as Desktop, Documents, Downloads, Pictures, Videos, and


Public.
In addition, the /home directory contains personal configuration files which
are prefixed with a dot (.). These are hidden files that contain user-specific settings
for the login shell session.

/opt Directory - The /opt directory is a directory that is reserved for add-on
packages and third-party software applications that are not included by default in
the system’s official repositories.
For example, when you install applications such as Skype, Discord, Spotify,
and Java, to mention a few, they get stored in the /opt directory.

/tmp Directory - The /tmp directory is a directory that stores temporary files
and many programs use this directory to create lock files and keep the temporary
storage of data.
Do not delete files under the/tmp directory unless you know exactly what
you are doing! Many of these files are critical for presently running programs and
removing them may affect a system crash.

/usr Directory - The /usr directory ranks as one of the most important
directories due to the enormous amount of data it holds. The directory contains
system-wide read-only files. These include libraries, user binaries and their
documentation, programs, and system utilities.

/var Directory - The /var directory stores system-generated variable files,


which include log files, caches, and spool files

/dev Directory- The /dev directory contains device files or special files for
devices that are attached to the system such as the hard drive, keyboard, and
mouse. As mentioned, these are not regular that a user can read and write to.
These are abstractions of standard devices that applications on your system
interact with through input and output system calls.

Some other directories in the Linux system:

/proc Directory- The /proc directory is somewhat of a strange directory. It is a


virtual or pseudo filesystem that contains vital information about running
processes. It is considered the control and information center for the Linux kernel.
The filesystem is created on the fly upon system startup and is destroyed
once the system is powered off.

/mnt Directory- The /mnt directory along with its subdirectories is a directory
intended to be used as a temporary mount point for mounting storage devices such
as Hard disk drives, USB drives, and CDROMs.

/sys Directory- The /sys is a virtual file system that contains a set of virtual
files that provide an interface to the Linux kernel.

/media Directory- The /media directory is a directory where the system


mounts removable media such as USB drives.

Page 115 of 159


Operating System

/run Directory- The /run directory is a temporary filesystem that contains


volatile runtime data that shows the system has since it was booted. Files under
the /run directory must be deleted (removed or truncated as convenient) at the
start of the boot process.

/lib Directory- The /lib directory stores all the essential standard libraries
required by user binaries in the /bin directory.

/lost+found Directory- The lost+found directory is installed during the


installation of Linux, useful for recovering files that may be broken due to an
unexpected shut-down.

/srv Directory- The /srv directory is the service directory and is abbreviated as
‘srv‘. This directory contains server-specific and service-related files.
Exploring directories and their usability: We know that Linux is a
very complex system that requires an efficient way to start, stop, maintain, and
reboot a system, unlike the Windows operating system. In the Linux system, some
well-defined configuration files, binaries, and man pages information files are
available for every process.

/usr DIRECTORY
The /usr directory consists of several subdirectories that contain additional
UNIX commands and data files. It is also the default location of the user’s home
directories.
Although /usr is pronounced like the user, remember that it stands for Unix
System Resources. The /usr hierarchy should contain shareable, read-only data.
Some people choose to mount /usr as read-only.
The /usr/bin directory contains more UNIX commands. These commands
are used less frequently or are considered nonessential to UNIX system operation.
/usr/bin is a standard directory on Unix-like operating systems that contains most
of the executable files (i.e., ready-to-run programs) that are not needed for booting
(i.e., starting) or repairing the system.
The /usr/include directory contains header files for compiling C programs.
The /usr/lib directory contains more libraries and data files used by various
UNIX commands.
The /usr/spool directory contains various directories for storing files to be
printed, mailed, or passed through networks.
The /usr/tmp directory contains more temporary files.
The /usr/adm directory contains data files associated with system
administration and accounting. In particular, the /usr/adm/messages and
/usr/adm/Syslog files contain a record of system error messages, including those
sent to the system console. These files are especially useful for locating system
problems, including hardware problems. For example, an unusual number of disk
errors on a drive indicates a defective or misaligned drive. Because messages in the
file can accumulate rapidly, these files must be deleted periodically.

Page 116 of 159


Operating System

FILE TYPES
A file type helps us in identifying the type of content that is saved in the file.
Linux supports seven different types of files. These file types are the Regular file,
Directory file, Link file, Character special file, Block special file, Socket file, and
Named pipe file.

User data files (Regular or Ordinary Files)- Regular or ordinary files


store data of various content types such as text, audio, video, images, scripts, and
programs. There are hundreds of content types. In Linux, regular files can be
created with or without an extension.
An extension is a group of characters that is used with the file name to give
it a special identity or to group it with files of a similar content type. For easy
recognition and processing, files of different content types often use well-known file
extensions.
Although the Linux file system does not need file extensions, you still use
them. They help us in identifying the types of content that are stored in files. For
example, if a file has a .mp4 extension, you may know that it is a video file.

Directory files- To organize files in a hierarchy, file systems use directories.


Directories are also files, but instead of storing data, they store the location of other
files. To store the location of files placed in the directory, the directory uses
directory entries. Each directory entry stores the name and location of a single file.
Linux file system starts with a directory called / or root directory. All files
and directory files are created under this directory. Except for the root directory,
each directory has a parent directory.

System data files or Special files- Linux treats all hardware devices
(such as hard drives, printers, monitors, terminal emulators, and CD/DVD drives)
as special files. This means that an application program can access and use files
and devices in the same way. This feature makes developing programs in Linux
easier and more flexible.
Linux places all special files or device files under the /dev directory. There
are two types of special files: a character special file and a block special file. A
character special file represents a device that transfers data in bytes such as a
monitor or a printer. A block special file represents a device that transfers data in
blocks, such as a hard drive.

Link files- Link files allow us to use a file with a different filename and from a
different location. For this, we use link files. A link file is a pointer to another file.
There are two types of links: a hard link and a symbolic or soft link.
A hard link creates a mirror copy of the original file. A hard link cannot be
created to a directory or a file on another filesystem. A soft or symbolic link creates
a pointer to the original file. A soft link can be created to a directory or a file on
another filesystem.

Page 117 of 159


Operating System

Socket files- A socket is a communication endpoint that applications use to


exchange data. For example, if an application wants to communicate with another
application, it connects with the socket of that application.
Each application that provides services to other applications or remote
clients uses a socket to accept connections. Each socket has an associated IP
address and port number that allow it to accept connections from clients.
For example, if an application of the local system wants to communicate
with another application of a remote system, it connects to the socket of that
application by using the associated IP address and port number of that socket.

Named pipe files- Linux allows us to send the output of any process or
command to another process or command as the input. This feature is known as
the pipe. Pipes work only when both processes are started by the same user and
exist in the same parent process space.
If processes are executed under different user names and permissions, then
standard pipes do not work. In such circumstances, named pipes are used. Named
pipes are similar to the standard pipes except that they can be accessed as part of
the filesystem.
Named pipe files are empty pipe files. The kernel processes named pipe files
without writing them to the file system. Named pipe files can exist anywhere in the
file system. Named pipe files are also known as the FIFO (First In First Out) files.
Executable files- An executable file is a file that is used to perform various
functions or operations on a computer. Unlike a data file, an executable file cannot
be read because it's compiled. On an IBM-compatible computer, common
executable files are .BAT, .COM, .EXE, and .BIN.

NAMING FILES AND DIRECTORIES


Linux adheres to the following rules for file and directory names:
➢ A file or directory name can have from 1 to 256 characters in length.
➢ Linux is case-sensitive, uppercase characters are different from lowercase
characters.
➢ File or directory names can include letters, numbers, and the following special
characters: period (.), underscore (_), and dash (-).
➢ The special characters comma (,), quotes (‘,’ “ “, or ` ), slash ( / ), backslash ( \ ),
and space can be used in file or directory names, but are highly advised
against.
Linux provides two wildcard characters to represent ambiguous characters
or strings in file or directory names:
➢ The question mark (?) represents any single character. (e.g.: ls file?.txt would
list file1.txt file2.txt, but not file50.txt)
➢ The asterisk (*) represents any string of zero or more characters. (e.g.: ls
file*.txt would list file.txt file1.txt file2.txt file50.txt, but not file01.data)

Page 118 of 159


Operating System

General File naming conventions- Unlike Windows, Linux is not strict


with the naming convention. We can use any number or letter in a file name. We
can also use an underscore, space, period, and comma. Some special characters
such as a question mark, asterisk, and slash are not allowed in a file name. These
characters are reserved for shell functions. Just like Windows, we can use a dot to
create a file extension. Although file extensions are not compulsory in Linux, they
should still be used wherever possible as they provide a good way to manage files.
➢ A file name can contain any character or number.
➢ The maximum length for a file name is 256 characters.
➢ A file name can use a space, underscore, minus, period, and comma.
➢ A file name cannot use a question mark, asterisk, or slash.
➢ A file extension is not compulsory. A file can be created with or without an
extension.
➢ A file whose name starts with a period (.) is treated as a hidden file.
➢ If a file name contains a white space, it needs to be quoted before it can be
accessed at the command prompt.

SHELL
The shell can be defined as a command interpreter within an operating
system like Linux/GNU or Unix. It is a program that runs other programs. The
shell facilitates every user of the computer as an interface to the Unix/GNU Linux
system. Hence, the user can execute different tools/utilities or commands with a
few input data.
The shell sends the result to the user over the screen when it has completed
running a program, which is the common output device. That's why it is known as
a "command interpreter".
The shell is not just a command interpreter. Also, the shell is a programming
language with complete constructs of a programming language such as functions,
variables, loops, conditional execution, and many others.

Category of Shell- Broadly, the shell is categorized into two main categories
which are explained below:

1) Graphical Shells- These shells specify the manipulation of programs that


are based on the graphical user interface (GUI) by permitting operations like
moving, closing, resizing, and opening windows and switching focus among
windows as well. Ubuntu OS or Windows OS could be examined as a good
example that offers a graphical user interface for the user to interact with the
program. Various users don't need to type in any command for all the actions.

2) Command-line Shell- Various shells could be accessed with the help of a


command-line interface by users. A unique program known as Command
prompt in Windows or Terminal in macOS/Linux is offered for typing in
human-understandable commands like "ls", "cat", etc, and after that, it is run.
The result is further shown to the user on the terminal.

Page 119 of 159


Operating System

Working on a command-line shell is complicated for many beginners


because it is hard to remember several commands. Command-line shell is very
dominant and it permits users to store commands in a file and run them
together. In this way, a repetitive action could be automated easily. Usually,
these files are known as Shell scripts in macOS/Linux systems and batch files
in Windows.

Types of Shell- There are various types of shells which are discussed as
follows:

a) Bash Shell- In the bash shell, bash means Bourne Again Shell. It is a default
shell over several distributions of Linux today. It is a sh-compatible shell. It
could be installed over Windows OS. It facilitates practical improvements on
the sh for interactive and programming use, which contains:
Job Control
Command-line editing
Shell Aliases and Functions
Unlimited size command history
Integer arithmetic in a base from 2-64

b) Csh/Tcsh Shell- Tcsh is an upgraded C shell. This shell can be used as a


shell script command processor and interactive login shell. Tcsh shell includes
the following characteristics:
C like syntax
Filename completion and programmable word
Command-line editor
Job control
Spelling correction

c) Ksh Shell- Ksh means Korn shell. It was developed and designed by David G.
Korn. Ksh shell is a high-level, powerful, and complete programming language,
and it is a reciprocal command language as well, just like various other
GNU/Unix Linux shells. The usage and syntax of the C shell are very similar to
that of the C programming language.

d) Zsh Shell- Zsh shell is developed to be reciprocal and it combines various


aspects of other GNU/Unix Linux shells like ksh, tcsh, and bash. Also, the
POSIX shell standard specifications were based on the Korn shell. Also, it is a
strong scripting language like other available shells. Some of its unique
features are listed as follows:
Startup files
Filename generation
Login/Logout watching
Concept index
Closing comments
Variable index

Page 120 of 159


Operating System

Key index
Function index and various others that we could find out within the
man pages.
All these shells do a similar job but take different commands and
facilitate distinct built-in functions.

e) Fish- Fish stands for "friendly interactive shell". It was produced in 2005. Fish
shell was developed to be fully user-friendly and interactive just like other
shells. It contains some good features which are mentioned below:
Web-based configuration
Man page completions
Auto-suggestions
Support for term256 terminal automation
Completely scripted with clean scripts

CREATING USER ACCOUNT


The Linux server allows us to create more than one user after installation.
Linux is a multi-user system, which means more than one user can work in the
same system at the same time. We are allowed to do so through the Setup agent.
We must create an account to work with Linux as we cannot keep working
with the root account. We have one administrative account; a system administrator
account is responsible for managing the user accounts and groups of the system.
Adding or removing a user is one of the most basic tasks of a new Linux server.
We are given only a root user account on a new Linux server. Adding a user
account provides lots of power and accessibility to a particular user. It is a useful
but insecure utility of the Linux server. It is good to add an unprivileged user to do
common tasks. However, we can access the administrative privilege through the
Sudo command-line utility.

Create a User in Linux (Ubuntu)- There are two most common ways to
add a user to a Linux server.
Graphically through the user manager
By the useradd command (Terminal)

Graphically through the user manager- Linux GUI allows us to create a


user from its functions. It is a straightforward process. To create a user for your
Linux server, follow the below steps:
Step 1: Goto system search and search for the setting and navigate to Detail->
About.
Step 2: Click on the Users after the Unlock option given on the header. It will ask
for the system security password to enter the password and click ok to continue.
Consider the below image:

Page 121 of 159


Operating System

Step 3: Click on the Add User option to add a new user.

Step 4: Enter the user details like username and password and account type. We
can create two types of accounts, which are Standard and Administrator. The
standard account does not contain the sudo privilege. However, we can provide it
later.

Page 122 of 159


Operating System

Step 5: Now, we have successfully created a new user called JTP2. Consider the
below image.

By the Linux useradd command, in Linux, the useradd command is a


command-line utility that is used to add or remove a user on a Linux server and
Unix-based operating system. In a different type of Linux distribution, the useradd
command may be slightly different. The useradd command performs the below
tasks:
➢ It edits the files for newly created users like /etc/passwd, /etc/shadow,
/etc/group, and /etc/gshadow.
➢ It creates and opens a new home directory.
➢ It allows us to set ownerships and permissions to the home directory.
Syntax: useradd [options] username
To use the useradd command, we have to log in with root or sudo access.
Before using the Linux useradd command, understand some common terms that
are used in the Linux command line.
Username: A username is a name that is used to log in to the Linux system. It is
displayed when we turn on our machine. The username length should be between
1 to 32 characters.
Password: A password is a secret code that is used to protect your system from
unauthorized access. It is stored in an etc/shadow file in an encrypted format.
User ID (UID): Linux provides a unique ID to every user; it is called a user
identification number or User ID or UID. By default, the UID for the root user is
reserved as zero, and the remaining UID from 1 to 99 is reserved for other
predefined accounts. Further, UIDs from 100-999 are reserved for groups and
system accounts.
Group ID (GID): The GID or Group ID is a group identification number provided
by the Linux system. It is stored in the/etc/group file.
User Info: It allows us to define some additional information about the user, such
as the user’s full name. It is optional.

Page 123 of 159


Operating System

Home Directory: It is an absolute location for a user.


Shell: It is an absolute location of a user's shell, i.e. /bin/bash.
To create a new user by the useradd command, execute the useradd
command followed by the username as follows:
sudo useradd JTP3
The above command will ask for the system administration password, enter
the password. It will create a user named JTP3. This username is used by the user
to log in to the system. The username must be unique. Consider the below output:
To set the password for the newly created user, execute the below command:
sudo passwd JTP3
The above command will ask for the new password, enter the password and
retype the new password. It will update the password for the specified user.
Consider the below output:

Create a user with a home directory- Sometimes the newly created user
may or may not assign a home directory. To create a user and forcefully assign a
home directory to it, execute the below command:
Sudo useradd -m Demo
The above command will ask for the system administration password and
create a directory home/Demo for the user Demo.

Create a user with a different home directory- Linux allows us to create


a home directory in a different place instead of the default folder. Use the -d option
with the useradd command to create a different home directory. Execute the below
command:
sudo useradd -m -d /Demo1 Demo1
The above command will create a Demo1 folder under the root directory for the
user Demo1.
SHELL CONCEPT
A shell is a special user program that provides an interface for the user to
use operating system services. Shell accepts human-readable commands from a
user and converts them into something which the kernel can understand. It is a
command language interpreter that executes commands read from input devices
such as keyboards or files. The shell gets started when the user logs in or starts the
terminal.
Shell is broadly classified into two categories-
Command Line Shell
Graphical shell

Page 124 of 159


Operating System

Command Line Shell- Shell can be accessed by the 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 human-readable commands such as
“cat”, “ls” etc. and then it is executed. The result is then displayed on the terminal
to the user. A terminal in the Ubuntu 16.4 system looks like this –

In the above screenshot, the “ls” command with the “-l” option is executed. It
will list all the files in the current working directory in a long listing format.
Working with a command line shell is a bit difficult for beginners because it’s hard
to memorize so many commands. It is very powerful; it allows users 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 the 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 examples which
provide a GUI to the user for interacting with the program. Users do not need to
type in a command for every action. A typical GUI in the Ubuntu system-

Page 125 of 159


Operating System

There are several shells available for Linux systems -


➢ BASH (Bourne Again SHell)- It is the most widely used shell in Linux
systems. It is used as the default login shell in Linux systems and macOS. It
can also be installed on Windows OS.
➢ CSH (C SHell)- The C shell’s syntax and usage is 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 understands different commands and
provides different built-in functions.

SHELL PROGRAM
Usually, shells are interactive that mean, they accept the command as input
from users and execute them. However, sometimes we want to execute a bunch of
commands routinely, so we have to type in all commands each time in the
terminal.
As a shell can also take commands as input from the file, we can write these
commands in a file and execute them in the 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 a .sh file extension, eg,
myscript.sh.
A shell script has 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 the 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.

Page 126 of 159


Operating System

Need for 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 the same as those directly entered in the
command line, so programmers do not need to switch to entirely different
syntax
➢ Writing shell scripts is 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 the large and complex tasks
➢ Provide minimal data structure, unlike other scripting languages. etc.

BASH SHELL
BASH is an acronym for Bourne Again Shell, a punning name, which is a
tribute to Bourne Shell (i.e., invented by Steven Bourne).
Bash is a shell program written by Brian Fox as an upgraded version of the
Bourne Shell program 'sh'. It is an open-source GNU project. It was released in
1989 as one of the most popular shell distributions of GNU/Linux operating
systems. It provides functional improvements over Bourne Shell for both
programming and interactive uses. It includes command line editing, key bindings,
command history with unlimited size, etc.
In basic terms, Bash is a command line interpreter that typically runs in a
text window where the user can interpret commands to carry out various actions.
The combination of these commands as a series within a file is known as a Shell
Script. Bash can read and execute the commands from a Shell Script.
Bash is the default login shell for most Linux distributions and Apple's mac
OS. It is also accessible for Windows 10 with a version and default user shell in
Solaris 11.
When you first launch the shell, it uses a startup script located in the
.bashrc or .bash_profile file which allows you to customize the behavior of the shell.
When a shell is used interactively, it displays a $ when it is waiting for a command
from the user. This is called the shell prompt.

Page 127 of 159


Operating System

[username@host ~] $
If the shell is running as root, the prompt is changed to #. The superuser
shell prompt looks like this:
[root@host ~] #
Bash is very powerful as it can simplify certain operations that are hard to
accomplish efficiently with a GUI. Remember that most servers do not have a GUI,
and it is best to learn to use the powers of a command line interface (CLI).

CHANGING SHELL PROMPT


The shell prompt can be changed to display information such as the
username for a user, the directory in which the user is working, the current date
and time, or some special message. To change the shell prompt for your current
login session, follow the steps given below:
1. Display the shell variables. At the shell prompt, type ‘printenv’ and press Enter.
If you cannot read the entire screen, send the printenv command to the less
pager.
(Type printenv |less)
2. Look for the PS1 variable. It may look as follows:
PS1=[\u@\r\w] \$
This variable tells the system to display the username for whoever is
using the host computer and that user’s current working directory inside
brackets followed by the $ prompt (or # prompt for the root account).
3. Write down the information from the PS1 variable.
4. Decide how you want the prompt to look. The following table shows the
characters to customize the shell prompt.

Character code Description


\! Display the number used in the history list to access the
command that would be executed at the shell prompt.
\$ Display a $ in the prompt for the regular user and a # for
the superuser.
\\ Display the backslash character.
\d Display the current date
\h Display the hostname of the computer at which you are
working
\t Display the current time
\u Display the username of the user who is logged in to the
system
\w Display the current working directory

Page 128 of 159


Operating System

\xxx Display any special comment.

Example: If you want to change the prompt so that it will display the time, the
date, the current working directory, and the $ prompt, then type PS1= [\t \d \w]\$‘
and press Enter. The shell prompt will change to display the following: [12:18:40
Sat Jan 21 aditi] $
Once you log out of your account, the shell prompt will return to the default
shell prompt.

COMMANDS
The Linux command is a utility of the Linux operating system. All basic and
advanced tasks can be done by executing commands. The commands are executed
on the Linux terminal. The terminal is a command-line interface to interact with
the system, which is similar to the command prompt in Windows OS. Commands
in Linux are case-sensitive.
Linux provides a powerful command-line interface compared to other
operating systems such as Windows and macOS. We can do basic work and
advanced work through its terminal. We can do some basic tasks such as creating
a file, deleting a file, moving a file, and more. In addition, we can also perform
advanced tasks such as administrative tasks (including package installation, and
user management), networking tasks (ssh connection), security tasks, and many
more.
Linux terminal is a user-friendly terminal as it provides various support
options. To open the Linux terminal, press the "CTRL + ALT + T" keys together, and
execute a command by pressing the 'ENTER' key.

Basic Syntax for A Command- Linux commands can be executed by


typing their name on the command line, followed by the options list, and then
parameters. A typical command line is as follows:
$ commandname –option [parameter]
The single-line command is referred to as the command line and it is typed
after the shell prompt. The command name always appears first, it tells the shell
WHAT to do. To execute the command press Enter. The minimum usage for most
commands is the command and one or more command options.
Command options are typed after the command and are used to modify the
result of the command. There must be a space between the command and the
command option. Then, the dash (-) character must precede the command option.
The dash tells Linux to treat each letter that follows the dash as a command
option. There is no space between the dash and the command option. There can be
more than one command option, but do not put any space between the dash and
the option.
For example, $ls –l /usr/doc
The ls command displays a file list for the contents of the current working
directory. The command option ls –l, modifies the information displayed about each

Page 129 of 159


Operating System

file in the listing. The parameter tells the command to list the contents of the
/usr/doc directory instead of the current working directory.
A command parameter can be a file, a directory, or a period. Parameters are
not preceded by a dash. Parameters specify which file or directory command is to
be acted upon, or they can set a time limit in which the command is to be
executed.

Creating an alias for a long command: A command alias is a unique


short name that is assigned to a command. It is possible to assign a short name for
a long command using an alias. To create an alias for the following command
cd /user/doc/file1
Suppose ’move’ is a sample alias name, to create this alias, type at the shell
prompt:
$alias move= “cd/user/doc/file1”
The alias command is followed by the alias name. The equal sign (=)
precedes the command that will be executed when the alias name is typed at the
shell prompt. Do not give space to either side of the equal sign. Now to change to
the ‘file1’ directory just type ‘move’ and press Enter.

EXPLORING THE HOME DIRECTORY


The Linux home directory is a directory for a particular user of the system
and consists of individual files. It is also referred to as the login directory. This is
the first place that occurs after logging into a Linux system. It is automatically
created as "/home" for each user in the directory. It is a standard subdirectory of
the root directory. The root directory contains all other directories, subdirectories,
and files on the system. It is denoted by a forward slash (/).
The home directory can be said as a personal working space for all the users
except root. There is a separate directory for every user. For example, two users
'jtp1' and 'jtp2' will have directories like "/home/jtp1" and "/home/jtp2". These
users will have all the rights under their directory files.
The root (administrative) user is the only user who has its home directory in
a different location by default. The path of the root user is '/root/', where it has
control under all the directories and files.

How to find the Home Directory? There are multiple ways to access
and return to the home directory. Some commands are very helpful for the
directories such as cd, pwd, mkdir, pwd, ls, and rmdir. To access the home
directory graphically, open the Files application, and click on the Home option from
the left side menu. Consider the below image:

Page 130 of 159


Operating System

Here, we can explore our home directory.


Generally, our terminal opens with the user's particular directory. To change
the directory to the home directory, execute the cd command as follows:
cd /home
The above command will change the directory to home. To list the home
directory, execute the ls command as follows:
ls
Consider the below output:

We can get back to our home directory by executing the cd command


without any argument. It will go back to our home directory from any directory we
are working on. Execute it as follows:
cd
Consider the below output:

From the above output, we were in /Directory/files, by executing only the cd


command, we reached our home directory. We can use the "cd ~ or cd $HOME"
commands as well, to do the same. Consider the below commands:
cd ~
cd $Home
To display the current working directory, execute the pwd command as follows:
pwd
Consider the below output:

Page 131 of 159


Operating System

ls COMMAND
ls is a Linux shell command that lists directory contents of files and
directories. Some practical examples of the ls command are shown below.

Open Last Edited File Using ls -t


ls -t: It sorts the file by modification time, showing the last edited file first.
head -1 picks up this first file. To open the last edited file in the current directory
use the combination of ls and head commands as shown below.

This will open the last file you edited (i.e., second.txt)

Display One File Per Line Using ls -1

Display All Information About Files/Directories Using ls -l


$ ls -l: To show long listing information about the file/directory.

-rw-rw-r– 1 maverick maverick 1176 Feb 16 00:19 1.c

Page 132 of 159


Operating System

1st Character – File Type: The first character specifies the type of the file. In
the example above, the hyphen (-) in the 1st character indicates that this is a
normal file. Following are the possible file type options in the 1st character of the ls
-l output.
Field Explanation
– normal file
d: directory
s: socket file
l: link file
Field 1- File Permissions: Next 9 characters specify the permission of the file.
Every 3 characters specify read, write, and execute permissions for the user(root),
group, and others respectively in order. Taking the above example, -rw-rw-r–
indicates read-write permission for the user(root), read permission for the group,
and no permission for others respectively. If all three permissions are given to the
user(root), group, and others, the format looks like this -rwxrwxrwx
Field 2- Number of links: Second field specifies the number of links for that file.
In this example, 1 indicates only one link to this file.
Field 3- Owner: The third field specifies the owner of the file. In this example,
this file is owned by the username ‘maverick’.
Field 4- Group: Fourth field specifies the group of the file. In this example, this
file belongs to the ”maverick” group.
Field 5- Size: Fifth field specifies the size of the file in bytes. In this example,
‘1176’ indicates the file size in bytes.
Field 6- Last modified date and time: The sixth field specifies the date and
time of the last modification of the file. In this example, ‘Feb 16 00:19’ specifies the
last modification time of the file.
Field 7- File name: The last field is the name of the file. In this example, the file
name is 1.c.

Display File Size in Human Readable Format Using ls -lh


ls -lh (h stands for human readable form): To display file size in an easy-to-read
format. i.e., M for MB, K for KB, G for GB.

Display Directory Information Using ls -ld

Page 133 of 159


Operating System

When you use “ls -l” you will get the details of the directory's content. But if
you want the details of the directory then you can use the -d option as., For
example, if you use ls -l /etc, it will display all the files under the etc directory. But,
if you want to display the information about the /etc/ directory, use the -ld option
as shown below.
$ ls -l /etc

$ ls -ld /etc

Order Files Based on Last Modified Time Using ls -lt


ls -lt: To sort the file names displayed in the order of the last modification
time. You will find it handy to use it in combination with the -l option.

Order Files Based on Last Modified Time (In Reverse Order)


Using ls -ltr
$ ls -ltr: To sort the file names in the last modification time in reverse order.
This will be showing the last edited file in the last line, which will be handy when
the listing goes beyond a page.

Page 134 of 159


Operating System

Display Hidden Files Using ls -a (or) ls -A


$ ls -a: To show all the hidden files in the directory, use the ‘-a option’. Hidden
files in Unix start with ‘.’ in their file name. It will show all the files including the ‘.’
(current directory) and ‘..’ (parent directory).

$ ls -A: To show the hidden files, but not the ‘.’ (current directory) and ‘..’ (parent
directory).

Display Files Recursively Using ls -R


$ ls /etc/apt

Page 135 of 159


Operating System

$ ls -R /etc/apt: To show all the files recursively. When you do this from /, it
shows all the unhidden files in the whole file system recursively.

Display File Inode Number Using ls -i


Sometimes you may want to know the inode number of a file for internal
maintenance. Use the -i option as shown below to display the inode number. Using
the inode number, you can remove files that have special characters in their name.
$ ls -i

$ ls -i /etc/apt

Page 136 of 159


Operating System

Hide Control Characters Using ls -q


ls -q: To print question marks instead of the non-graphics control characters.

Display File UID and GID Using ls -n


$ ls -n ~/kv: Lists the output like -l, but shows the uid and gid in numeric format
instead of names.

Visual Classification of Files with Special Characters Using ls


-F
$ ls -F: Instead of doing the ‘ls -l’ and then checking for the first character to
determine the type of file. You can use -F which classifies the file with different
special characters for different kinds of files.
/ – directory.
Nothing – normal file.
@ – link file.
* – Executable file

Page 137 of 159


Operating System

Visual Classification of Files with Colors Using ls -F


$ ls –color=auto: Recognizing the file type by the color in which it gets
displayed is another kind of classification of a file. In the below output, directories
get displayed in blue, soft links get displayed in green, and ordinary files get
displayed in the default color.

mkdir COMMAND
In Linux, if you want to create a new directory, you can do so by using the
mkdir command. The mkdir command is used to make a directory in Linux.
Before jumping into how we can create a directory (or in Windows
terminology - a folder), first, let's see how the mkdir command works.

Using the mkdir Command- Here is the syntax for the mkdir command:
mkdir [OPTION] [DIRECTORY]
We can provide some options and the path of one or more directories while
using the mkdir command. To see the available options, you can run the following
command in your terminal: mkdir --help.
Now let's see how we can create a directory using the mkdir command in Linux.

Creating a Directory- We will start by creating a single directory using the


mkdir command:
mkdir studytonight

Page 138 of 159


Operating System

The above command will create a new directory with the name studytonight
in the present working directory. You can use the ls command to list down the files
and directories in the current directory.
ls -l
Output- drwxrwxr-x 2 nobody nobody 6 Jul 2 17:29 studytonight
By default, the directory is created inside the current directory. If we want to
create the directory in some other location, then we can provide the complete path
while creating the directory.
Consider that we have a directory structure:
home: - someuser: - learn-linux - test-linux
And we are currently inside the directory someuser and want to create a new
directory with a name sample inside the directory test-linux, we can do so using
the following command:
mkdir text-linux/sample
Consider that you are currently inside the directory test-linux and you want
to create a directory inside the directory learn-linux with a name sample, we can do
this using the following command:
mkdir ../learn-linux/sample
The two dots, in the beginning, represents that we want to move out of the
test-Linux directory, then go inside the learn-linux directory and create a directory
named sample there.

Creating a directory along with Parent Directories- If we want to


create a directory structure for example in the above-given directory structure if
you are currently inside the someuser directory and you want to create a directory
sample inside the directory practice-Linux, how will you do so? Notice, we do not
have the practice-Linux directory inside someuser directory. We can use the mkdir
command to create the parent directory too while creating a directory using the -p
option.
mkdir -p practice-Linux/sample
When we run the above command, a new directory practice-Linux will be
created and inside it, a sample directory will also get created. This is the magic of
the -p option of the mkdir command. Similarly, you can use the -p option to create
multiple levels of parent directories.

Creating Multiple Directories- If we want to create multiple directories in


one go, we can easily do so using the mkdir command.
mkdir dir1 dir2 dir3
The above command will create 3 directories in the current directory.
Output-
drwxrwxr-x 2 nobody nobody 6 Jul 2 17:50 dir1
drwxrwxr-x 2 nobody nobody 6 Jul 2 17:50 dir2

Page 139 of 159


Operating System

drwxrwxr-x 2 nobody nobody 6 Jul 2 17:50 dir3


Similarly, you can provide different paths to create multiple directories all at
different locations by running a single command.

Creating Directory with custom Permissions- When we use the


mkdir command to create a directory in Linux, the default mode/permissions
assigned to it is 755, which means read and execute permission for all, but not
everyone can write to this directory. If you want to provide custom permissions like
700, 644, or even more restrictive 444, we can do so using the -m option (which
stands for mode) with the mkdir command. Here's an example,
mkdir -m 444 dir1
output- dr--r--r-- 2 nobody nobody 6 Jul 3 10:31 dir1
This will create a new directory with 444 mode/permission, which you can see at
the beginning of the output dr--r--r-- which represents the permissions. We can
change the permission for any directory or file, using the chmod command in Linux
rmdir COMMAND
rmdir command is used to remove empty directories from the filesystem in
Linux. The rmdir command removes every directory specified in the command line
only if these directories are empty. So if the specified directory has some directories
or files in it then this cannot be removed by the rmdir command.
Syntax: rmdir [-p] [-v | –verbose] [–ignore-fail-on-non-empty] directories …
Options:
➢ –help: It will print the general syntax of the command along with the various
options that can be used with the rmdir command as well as give a brief
description bout each option.
➢ rmdir -p: In this option each of the directory arguments is treated as a
pathname of which all components will be removed, if they are already empty,
starting from the last component.
➢ rmdir -v, –verbose: This option displays verbose information for every directory
being processed.
➢ rmdir –ignore-fail-on-non-empty: This option does not report a failure that
occurs solely because a directory is non-empty. Normally, when rmdir is being
instructed to remove a non-empty directory, it simply reports an error. This
option consists of all those error messages.
➢ rmdir –version: This option is used to display the version information and exit.
Example 1: This will first remove the child directory and then remove the parent
directory.
rmdir -p mydir/mydir1

Page 140 of 159


Operating System

Example 2: Remove the directories mydir1, mydir2, and mydir3, if they are
empty. If any of these directories are not empty, then an error message will be
printed for that directory, and the other directories will be removed.
rmdir mydir1 mydir2 mydir3

Example 3: Remove the directory mydir/mydir1 if it is empty. Then, remove


directory mydir, if it is empty after mydir/mydir1 was removed.
rmdir mydir/mydir1 mydir

stat COMMAND
The stat is a command which gives information about the file and filesystem.
Stat command gives information such as the size of the file, access permissions
and the user ID and group ID, and birth time access time of the file. Stat command
has another feature, by which it can also provide the file system information. This
is the best tool to use when we want the information on any file.
The basic syntax of using the stat command is as follows:
stat --options filenames
Stat can accept one or more filenames as input to the stat command. For
example
stat /etc/resolv.conf
Output:

Page 141 of 159


Operating System

The information we get from stat- The following is the information we get
about the file when we run the stat command.
➢ File: The name of the provided file. If the provided file is a symlink, then the
name will be different.
➢ Size: The size of a given file in Bytes.
➢ Blocks: Total number of allocated blocks to the file to store on the hard disk.
➢ IO Block: The size of every allocated block in bytes.
➢ File type: The file may be of the following types: Regular files, special files,
directories, or symbolic links.
➢ Device: Device number in hexadecimal format.
➢ Inode: Inode number of the file.
➢ Links: Number of hard links of the file.
➢ Access: Access permissions in the numeric and symbolic methods.
➢ Context: The field stores the SELinux security context.
➢ Access: The last time at which the file was accessed.
➢ Modify: The last time at which the file was modified.
➢ Change: The last time the at which file’s attribute or content was changed.
➢ Birth: The time at which the file was created.

Displaying the File System Information- stat command can provide


the file system information when we provide the file name with the -f (–file-system)
options. Syntax of using the -f option with the stat command:
stat -f filename

We can also provide the directory or file system as input to the stat
command as follows:
stat -f /
The information we get for the filesystem from the stat

Page 142 of 159


Operating System

➢ File: The name of provided file.


➢ ID: File system ID in hexadecimal format.
➢ Namelen: The maximum length (number of characters) of a file name.
➢ Fundamental block size: Total size of each block on the file system.
➢ Blocks:
• Total: Total number of blocks in the file system
• Free: Total number of free blocks in the file system
• Available: Total number of free blocks available for non-root users
➢ Inodes:
• Total: Total number of inodes in the file system.
• Free: Total number of free inodes in the file system.

Using Stat with Multiple Files- To get the information about multiple
files using the stat command, just mention the filenames separated by space:
stat locale.conf login.defs
This will show the information about the mentioned files.

cat COMMAND
cat(concatenate) command is very frequently used in Linux. It reads data
from the file and gives its content as output. It helps us to create, view, and
concatenate files. So let us see some frequently used cat commands.

To view a single file


Command: $cat filename
Output- It will show the content of the given filename

To view multiple files


Command: $cat file1 file2
Output- This will show the content of file1 and file2.

Page 143 of 159


Operating System

To view the contents of a file preceding with line numbers.


Command: $cat -n filename
Output- It will show content with line number
Example: $cat-n geeks.txt
Output- 1) This is geeks
2) A unique array

Create a file
Command: $ cat > newfile
Output- Will create a file named newfile

Copy the contents of one file to another file.


Command:
$cat [filename-whose-contents-is-to-be-copied] > [destination-
filename]
Output- The content will be copied into the destination file

Cat command can suppress repeated empty lines in the output


Command: $cat -s geeks.txt
Output- Will suppress repeated empty lines in the output

Cat command can append the contents of one file to the end of another
file.
Command: $cat file1 >> file2
Output- Will append the contents of one file to the end of another file

Cat command can display content in reverse order using tac command.
Command: $tac filename
Output- Will display content in reverse order

Cat command can highlight the end of the line.


Command: $cat -E "filename"
Output- Will highlight the end of the line

If you want to use the -v, -E, and -T options together, then instead of writing
-vET in the command, you can just use the -A command line option.
Command $cat -A "filename"

Cat command if the file has a lot of content and can’t fit in the
terminal.
Command: $cat "filename" | more
Output- Will show that much content, that could fit in the terminal, and will
ask to show more.

Cat command to merge the contents of multiple files.


Command: $cat "filename1" "filename2" "filename3" > "merged_filename"

Page 144 of 159


Operating System

Output- Will merge the contents of the file in respective order and will insert
that content in "merged_filename".

Cat command to display the content of all text files in the folder.
Command: $cat *.txt
Output- This will show the content of all text files present in the folder.

Cat command to write in an already existing file.


Command: $cat >> geeks.txt
The newly added text.
Output- Will append the text "The newly added text." to the end of the file.

rm COMMAND
rm stands for remove here. The rm command is used to remove objects such
as files, directories, symbolic links, and so on from the file system like UNIX. To be
more precise, rm removes references to objects from the filesystem, where those
objects might have had multiple references (for example, a file with two different
names). By default, it does not remove directories. This command normally works
silently and you should be very careful while running the rm command because
once you delete the files then you are not able to recover the contents of files and
directories.
Syntax: rm [OPTION]... FILE...

Example- Let us consider 5 files having names a.txt, b.txt, and so on till e.txt.
$ ls
Output- a.txt b.txt c.txt d.txt e.txt

Removing one file at a time


$ rm a.txt
$ ls
b.txt c.txt d.txt e.txt

Removing more than one file at a time


$ rm b.txt c.txt
$ ls
d.txt e.txt
No output is produced by rm since it typically only generates messages in the case
of an error.

Options:
1. -i (Interactive Deletion): Like in cp, the -i option makes the command ask
the user for confirmation before removing each file, you have to press y to
confirm the deletion, any other key leaves the file un-deleted.
$ rm -i d.txt

Page 145 of 159


Operating System

rm: remove regular empty file 'd.txt'? y


$ ls
e.txt

2. -f (Force Deletion): rm prompts for confirmation removal if a file is write-


protected. The -f option overrides this minor protection and removes the file
forcefully.
$ ls -l
total 0
-r--r--r--+ 1 User User 0 Jan 2 22:56 e.txt
$ rm e.txt
rm: remove write-protected regular empty file 'e.txt'? n
$ ls
e.txt
$ rm -f e.txt
$ ls
-f option of the rm command will not work for write-protect directories.

3. -r (Recursive Deletion): With the -r (or -R) option rm command performs a


tree walk and will delete all the files and sub-directories recursively of the
parent directory. At each stage, it deletes everything it finds. Normally, rm
wouldn’t delete the directories but when used with this option, it will delete.
Below is the tree of directories and files:
$ ls
A
$ cd A
$ ls
BC
$ ls B
a.txt b.txt
$ ls C
c.txt d.txt
Now, deletion from A directory (as parent directory) will be done as:
$ rm *
rm: cannot remove 'B': Is a directory
rm: cannot remove 'C': Is a directory
$ rm -r *
$ ls
Every directory and file inside A directory is deleted.

mv COMMAND

Page 146 of 159


Operating System

mv stands for the move. mv is used to move one or more files or directories
from one place to another in a file system like UNIX. It has two distinct functions:
(i) It renames a file or folder.
(ii) It moves a group of files to a different directory.
No additional space is consumed on a disk during renaming. This command
normally works silently means no prompt for confirmation.
Syntax: mv [Option] source destination

Examples- Let us consider 4 files having names a.txt, b.txt, and so on till d.txt. To
rename the file a.txt to geek.txt (does not exist):
$ ls
a.txt b.txt c.txt d.txt
$ mv a.txt geek.txt
$ ls
b.txt c.txt d.txt geek.txt
If the destination file doesn’t exist, it will be created. In the above command,
mv simply replaces the source filename in the directory with the destination
filename (new name). If the destination file exists, then it will be overwritten and
the source file will be deleted. By default, mv doesn’t prompt for overwriting the
existing file.
For example, moving palash.txt to b.txt(exist):
$ ls
b.txt c.txt d.txt geek.txt
$ cat palash.txt
India
$ cat b.txt
Bachelor of Computer Application
$ mv geek.txt b.txt
$ ls
b.txt c.txt d.txt
$ cat b.txt
India

Options:

-i (Interactive): Like in cp, the -i option makes the command ask the user for
confirmation before moving a file that would overwrite an existing file, you have to
press y for confirm moving, any other key leaves the file as it is. This option doesn’t
work if the file doesn’t exist, it simply renames it or moves it to a new location.
$ ls
b.txt c.txt d.txt geek.txt
$ cat palash.txt
India

Page 147 of 159


Operating System

$ cat b.txt
bca
$ mv -i geek.txt b.txt
mv: overwrite 'b.txt'? y
$ ls
b.txt c.txt d.txt
$ cat b.txt
bca

-f (Force): mv prompts for confirmation overwriting the destination file if a file is


write-protected. The -f option overrides this minor protection and overwrites the
destination file forcefully and deletes the source file.
$ ls
b.txt c.txt d.txt geek.txt
$ cat b.txt
Linux Operating System
$ ls -l b.txt
-r--r--r--+ 1 User User 13 Jan 9 13:37 b.txt
$ mv geek.txt b.txt
mv: replace 'b.txt', overriding mode 0444 (r--r--r--)? n
$ ls
b.txt c.txt d.txt geek.txt
$ mv -f geek.txt b.txt
$ ls
b.txt c.txt d.txt
$ cat b.txt
India

-n (no-clobber): With the -n option, mv prevents an existing file from being


overwritten. In the following example, the effect is for nothing to happen as a file
would be overwritten.
$ ls
b.txt c.txt d.txt geek.txt
$ cat b.txt
Linux Operating System
$ mv -n geek.txt b.txt
$ ls
b.txt c.txt d.txt geek.txt
$ cat b.txt
Linux Operating System

Page 148 of 159


Operating System

-b(backup): With this option, it is easier to take a backup of an existing file that
will be overwritten as a result of the mv command. This will create a backup file
with the tilde character (~) appended to it.
$ ls
b.txt c.txt d.txt geek.txt
$ mv -b geek.txt b.txt
$ ls
b.txt b.txt~ c.txt d.txt

cp COMMAND
cp stands for a copy. This command is used to copy files or groups of files or
directories. It creates an exact image of a file on a disk with a different file name. cp
command requires at least two filenames in its arguments.
Syntax:
cp [OPTION] Source Destination
cp [OPTION] Source Directory
cp [OPTION] Source-1 Source-2 Source-3 Source-n Directory
The first and second syntax is used to copy the Source file to the Destination
file or Directory. The third syntax is used to copy multiple Sources(files) to the
Directory.
cp command works on three principal modes of operation and these
operations depend upon the number and type of arguments passed in the cp
command:

Two file names: If the command contains two file names, then it copies the
contents of 1st file to the 2nd file. If the 2nd file doesn’t exist, then first it creates
one, and content is copied to it. But if it existed then it is simply overwritten
without any warning. So be careful when you choose the destination file name.
cp Src_file Dest_file
Suppose there is a directory named bca having a text file a.txt.
Example:
$ ls
a.txt
$ cp a.txt b.txt
$ ls
a.txt b.txt

One or more arguments: If the command has one or more arguments,


specifying file names and following those arguments, an argument specifying
directory name then this command copies each source file to the destination

Page 149 of 159


Operating System

directory with the same name, created if not exist but if already existed then it will
be overwritten.
cp Src_file1 Src_file2 Src_file3 Dest_directory
Suppose there is a directory named bca having a text file a.txt, b.txt and a directory
name new in which we are going to copy all files.
Example:
$ ls
a.txt b.txt new
Initially new is empty
$ ls new
$ cp a.txt b.txt new
$ ls new
a.txt b.txt
For this case, the last argument must be a directory name. For the above
command to work, Dest_directory must exist because the cp command won’t create
it.

Two directory names: If the command contains two directory names, cp


copies all files of the source directory to the destination directory, creating any files
or directories needed. This mode of operation requires an additional option,
typically R, to indicate the recursive copying of directories.
cp -R Src_directory Dest_directory
In the above command, cp behavior depends upon whether Dest_directory
exists or not. If the Dest_directory doesn’t exist, cp creates it and copies the content
of the Src_directory recursively as it is. But if Dest_directory exists then a copy of
Src_directory becomes a sub-directory under Dest_directory.

Options: There are many options for the cp command, here we will discuss some
of the useful options:
Suppose a directory named bca contains two files having some content
named a.txt and b.txt. This scenario is useful in understanding the following
options.
$ ls bca
a.txt b.txt
$ cat a.txt
LOS
$ cat b.txt
LOS

-i (interactive): i stands for Interactive copying. With this option system first
warns the user before overwriting the destination file. cp prompts for a response, if
you press y then it overwrites the file and with any other option leaves it uncopied.
$ cp -i a.txt b.txt

Page 150 of 159


Operating System

cp: overwrite 'b.txt'? y


$ cat b.txt
LOS

-b (backup): With this option, the cp command creates the backup of the
destination file in the same folder with a different name and a different format.
$ ls
a.txt b.txt
$ cp -b a.txt b.txt
$ ls
a.txt b.txt b.txt~

-f(force): If the system is unable to open the destination file for writing operation
because the user doesn’t have writing permission for this file then by using the -f
option with the cp command, the destination file is deleted first, and then copying
of content is done from source to destination file.
$ ls -l b.txt
-r-xr-xr-x+ 1 User User 3 Nov 24 08:45 b.txt
Users, groups, and others don’t have writing permission.
Without the -f option, command not executed
$ cp a.txt b.txt
cp: cannot create regular file 'b.txt': Permission denied
With the -f option, the command is executed successfully
$ cp -f a.txt b.txt

-r or -R: Copying directory structure. With this option, the cp command shows its
recursive behavior by copying the entire directory structure recursively.
Suppose we want to copy the bca directory containing many files, and
directories into the bca1 directory (which does not exist).
$ ls bca/
a.txt b.txt b.txt~ Folder1 Folder2
Without the -r option, the error
$ cp bca bca1
cp: -r not specified; omitting directory 'geeksforgeeks'
With -r, execute successfully
$ cp -r bca bca1
$ ls bca1/
a.txt b.txt b.txt~ Folder1 Folder2

-p(preserve): With the—p option, cp preserves the following characteristics of


each source file in the corresponding destination file: the time of the last data
modification and the time of the last access, the ownership (only if it has
permission to do this), and the file permission bits.

Page 151 of 159


Operating System

For the preservation of characteristics, you must be the root user of the
system, otherwise, characteristics change.
$ ls -l a.txt
-rwxr-xr-x+ 1 User User 3 Nov 24 08:13 a.txt
$ cp -p a.txt c.txt
$ ls -l c.txt
-rwxr-xr-x+ 1 User User 3 Nov 24 08:13 c.txt
As we see above both a.txt and c.txt (created by copying) have the same
characteristics.

Examples:
Copying using * wildcard: The star wildcard represents anything i.e., all files
and directories. Suppose we have many text documents in a directory and want to
copy them to another directory, it takes lots of time if we copy files 1 by 1 or the
command becomes too long if specify all these file names as the argument, but by
using * wildcard it becomes simple.
Initially, Folder1 is empty
$ ls
a.txt b.txt c.txt d.txt e.txt Folder1
$ cp *.txt Folder1
$ ls Folder1
a.txt b.txt c.txt d.txt e.txt

MANAGING USERS ACCOUNTS


A user is an entity, in a Linux operating system, that can manipulate files
and perform several other operations. Each user is assigned an ID that is unique
for each user in the operating system. In this post, we will learn about users and
commands which are used to get information about the users. After installation of
the operating system, the ID 0 is assigned to the root user, and the IDs 1 to 999
(both inclusive) are assigned to the system users hence the IDs for local users begin
from 1000 onwards.
In a single directory, we can create 60,000 users. Now we will discuss the
important commands to manage users in Linux.

1. To list out all the users in Linux, use the awk command with the -F option.
Here, we are accessing a file and printing only the first column with the help of
print $1 and awk.
awk -F':' '{ print $1}' /etc/passwd

Page 152 of 159


Operating System

2. Using the id command, you can get the ID of any username. Every user has
an id assigned to it and the user is identified with the help of this id. By
default, this id is also the group id of the user.
id username
Example: id test

3. The command to add a user. useradd command adds a new user to the
directory. The user is given the ID automatically depending on which category
it falls in. The username of the user will be as provided by us in the command.
sudo useradd username
Example: sudo useradd geeks

Page 153 of 159


Operating System

4. Using the passwd command to assign a password to a user. After using this
command we have to enter the new password for the user and then the
password gets updated to the new password.
passwd username
Example: passwd geeks

5. Accessing a user configuration file.


cat /etc/passwd
This command prints the data of the configuration file. This file contains
information about the user in the format.
username : x : user id : user group id : : /home/username : /bin/bash

Now we will go through the commands to modify information.

6. The command to change the user ID for a user.


usermod -u new_id username
This command can change the user ID of a user. The user with the given
username will be assigned with the new ID given in the command and the old
ID will be removed.
Example: sudo usermod -u 1982 test

Page 154 of 159


Operating System

7. Command to Modify the group ID of a user.


usermod -g new_group_id username
This command can change the group ID of a user and hence it can even be
used to move a user to an already existing group. It will change the group ID of
the user whose username is given and set the group ID as the given
new_group_id.
Example: sudo usermod -g 1005 test

8. You can change the user login name using the usermod command. The below
command is used to change the login name of the user. The old login name of
the user is changed to the new login name provided.
sudo usermod -l new_login_name old_login_name
Example: sudo usermod -c John_Wick John_Doe

9. The command to change the home directory. The below command changes
the home directory of the user whose username is given and sets the new home
directory as the directory whose path is provided.
usermod -d new_home_directory_path username
Example: usermod -d new_home_directory test

Page 155 of 159


Operating System

10. You can also delete a user name. The below command deletes the user whose
username is provided. Make sure that the user is not part of a group. If the
user is part of a group then it will not be deleted directly, hence we will have to
first remove him from the group and then we can delete him.
sudo userdel -r username
Example: sudo userdel -r new_geeks

CHANGING PASSWORD
Both Unix and Linux-like operating systems apply the passwd commands for
changing the password of the user. The passwd command is used for updating the
authentication password or token of the user which is saved in the /etc/shadow
file.
The passwd command changes the passwords for group accounts and users.
A normal user might only modify the password for her/his account, the root user
or super user might modify the password for other accounts.
The group administrator might modify the password for a group. Also, the
passwd command changes the information of an account like the user's full name,
the login shell of the user, or the interval and expiry date of the password.
Type the following passwd command for changing our password:
$ passwd
Initially, the user is requested for her/his previous password when one is
available. The password is further compared and encrypted. The password is
compared to the stored or saved password.
The user has only a single chance of entering an accurate password. The
root user is allowed to bypass this step. Hence, the forgotten passwords might be
modified. A newer password is checked for complexity. The passwords must be a

Page 156 of 159


Operating System

combination of 10 to 20 characters containing multiple characters from all of the


below sets as a normal guideline:
Upper case alphabetic
Lower case alphabetic
Digits 0 to 9
Special characters or punctuation marks

Other account change password in Linux- If we want to change the


password for other accounts of the user in Linux, we have to log in as the super
user. Then, we have to type the below command to change the password for user
palash:
$ passwd Palash
Changing password for palash.
Current password:
New password:
OR
$ sudo passwd palash
Output:
[sudo] passwd for Palash:
New password:

Linux changes the password of a group- The password for a named


group will be changed when we use the -g option. In this example, we will change
the password for group1 group:
# passwd -g group1
The option -r is applied with the option -g for removing the latest password
through the named group. It permits group access to every member. Option -R is
applied with option -g for restricting the named group for every user.

Modifying user passwords in Linux- As a Linux sysadmin (system


administrator) we can change the password for the users on our server. For
changing the password on behalf of any user:
1. First of all, sign on "sudo" or "su" to the "super" or "root" account in Linux.
2. After that enter the following command for changing the password for john
user:
passwd john
3. The system will request us to type the password twice.
For changing or setting a new super user or root password, we have to enter
the following command:
$ sudo passwd

Page 157 of 159


Operating System

Forcing users to change the password at the next login- Linux


passwords by default never expire for any users. But we can also force the users to
change the password they log in by CLI or GUI methods next time. The syntax is as
follows:
$ sudo passwd -e {username}
$ sudo passwd --expire {username}
Let us expire the password of an account immediately, we can use the following
command:
$ sudo passwd -e Palash
Output-
$sudo passwd –expire Palash
Passwd-password expiry information changed
The system would confirm this:

Lock and unlock user passwords


Lock password: By using the following command, we can lock the user password:
$ sudo passwd -1 {username}
This option will disable the password by modifying it to any value which is
not matching to the possible encrypted value. It will add the ! sign at the start of
the password inside the /etc/shadow file.

Unlock password: We can use the following command to unlock a password:


$ sudo passwd -u {username}
The above option command will re-enable the password by modifying the
password back to the previous value.

CREATING GROUP ACCOUNTS


Groups in Linux refer to the user groups. In Linux, there can be many users
of a single system, (a normal user can take uid from 1000 to 60000, and one root
user (uid 0) and 999 system users (uid 1 to 999)). In a scenario where there are
many users, there might be some privileges that some users have and some don’t,
and it becomes difficult to manage all the permissions at the individual user level.
So, using groups, we can group several users, and set privileges and permissions
for the entire group. groupadd command is used to create a new user group.
Syntax: groupadd [option] group_name

Example: sudo groupadd developers


Every new group created is registered in the file “/etc/group“. To verify that
the group has been created, enter the command
$sudo tail /etc/group
Output: The file shows group information in the following format:

Page 158 of 159


Operating System

group_name: password: group-id: list-of-members

Options:
➢ -f, –force: This option forces the command to silently abort if the group with
the given already exists. If this option is used with the -g or –gid option and the
group id given already exists, the command forcefully ignores the given group
id and creates a new and unique group id.
Example- $groupadd developers
Goupadd: group ‘developers’ already exists.
$groupadd -f developers
$
➢ -g, –gid GID: This option is used to provide a group id (numeric) to the new
group, and it should be non-negative and unique unless explicitly created to be
non-unique (using the -o option). If this option is not used, the default id is
assigned, which is greater than every other group already present.
➢ -h, –help: Display help message and exit.
➢ -K, –key KEY=VALUE: Overrides /etc/login.defs defaults (GID_MIN,
GID_MAX and others). Multiple -K options can be specified. GID_MIN and
GID_MAX are the parameters set in /etc/login.defs which defines the minimum
and maximum values that a group id can take.
Example: groupadd -K GID_MIN=500 -K GID_MAX=700
➢ -o, –non-unique: This option permits to add of a group with a non-unique
GID.
➢ -p, –password PASSWORD: The encrypted password, as returned by crypt
(3). The default is to disable the password. This password is visible to the
users. You should make sure the password respects the system’s password
policy. The group passwords are stored in the “/etc/gshadow” file.
➢ -r, –system: Create a system group. The numeric identifiers of new system
groups are chosen in the SYS_GID_MIN-SYS_GID_MAX range, defined in
login.defs, instead of GID_MIN and GID_MAX.
➢ -R, –root CHROOT_DIR: Apply changes in the CHROOT_DIR directory and
use the configuration files from the CHROOT_DIR directory.

Page 159 of 159

You might also like