OS Unit - IV
OS Unit - IV
UNIT – IV
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.
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
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.
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.
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.
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.
Microkernels
Exo kernels
Hybrid kernels
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.
Directory Files- These types of files are a warehouse for other file types. It may
be a directory file within a directory (subdirectory).
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.
/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.
/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.
/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.
/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.
/lib Directory- The /lib directory stores all the essential standard libraries
required by user binaries in the /bin directory.
/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.
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.
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.
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.
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:
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
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.
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
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)
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.
Step 5: Now, we have successfully created a new user called JTP2. Consider the
below image.
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.
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.
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.
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.
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.
[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).
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.
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.
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:
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.
This will open the last file you edited (i.e., second.txt)
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.
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
$ ls -A: To show the hidden files, but not the ‘.’ (current directory) and ‘..’ (parent
directory).
$ 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.
$ ls -i /etc/apt
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.
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.
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
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:
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.
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
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.
Create a file
Command: $ cat > newfile
Output- Will create a file named newfile
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
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.
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.
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
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
mv COMMAND
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
$ 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
-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
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.
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
-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
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
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
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
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
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
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
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.