You are on page 1of 34

Unit-2

1.Linux Commands with Examples:

 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 (CLI) is a text-based interface
that will enable you to type text commands to instruct the computer to do
specific tasks
 Commands in Linux are case-sensitive.
 some basic tasks such as creating a file, deleting a file, moving a file, and
more can be done
 Advanced tasks such as administrative tasks (including package
installation, user management), networking tasks (ssh connection),
security tasks, can also be performed..
 To open the Linux terminal, press "CTRL + ALT + T" keys together, and
execute a command by pressing the 'ENTER' key.

The command line environment

When you log in to your account using SSH, the first thing you see is the Linux
command line prompt:

username@example.com [~]#

The tilde symbol ~ indicates that you are in your home directory, which is
usually /home/username.
Basic commands:

1. who :
The ‘$ who’ command displays all the users who have logged into
the system currently.

$ who
Output: harssh tty2 2017-07-18 09:32 (:0)

As shown above the only one user currently logged in. The thing
tty2 is terminal line the user is using and the next line gives the current date
and time

2. pwd :
The ‘$pwd’ command stands for ‘print working directory’ and as
the name says it is used to display the location of the current working
$ pwd
directory.
Output: /home/harssh
Output shows we are in harssh directory,which is present inside the home
directory .

3. mkdir :
The ‘$ mkdir’ stands for ‘make directory’ and it creates a new
directory.

$ mkdir newfolder
$ cd newfolder
$ pwd
Output: /home/harssh/newfolder

We have used ‘$ cd’ to get into the newly created directory and again on
giving ‘$ pwd’ command,we are displayed with the new ‘newfolder’
directory.

4. rmdir :
The ‘$ rmdir’ command deletes any directory we want to delete and
it can remembered by its names ‘rmdir’ which stands for ‘remove
directory’.

$ rmdir newfolder
5. cd :
The ‘$ cd’ command stands for ‘change directory’ and it changes
your current directory to the ‘newfolder’ directory..

For example,

if you are working in /home/username/Documents and want to go in


the Pictures subdirectory of the same directory, you can write cd Pictures

If you want to go to a new directory, you can write cd followed by


the absolute path of the directory – cd /home/username/Music.

Command Description

cd to go to the home folder

cd.. to move one directory up

cd- move to your previous directory

8. cp :
This ‘$ cp ‘ command stands for ‘copy’ and it simply copy/paste the
file wherever you want to.

Example :1
$ cp /home/harssh/file.txt /home/harssh/new/

In the above example, we are copying a file ‘file.txt’ from the


directory harssh to a new directory new.

Example: 2 – to copy the contents of the red file into the blue file.
$ cp red.txt blue.txt

9. mv :

The ‘$ mv’ command stands for ‘move’ and it simply move a file
from a directory to another directory.

$ mv /home/harssh/file.txt /home/harssh/new

In the above example a file named ‘file.txt’ is being moved into a


new directory ‘new’.

mv command syntax – to rename a file

mv old_filename new_filename
10. rm :

The rm command deletes directories as well as the contents within


them. This command needs to be used carefully as it deletes everything.

Syntax: $ rm <filename>

Example : $ rm file.txt

11.touch command

With the touch command, you can create a new blank file with the
given name.

touch command syntax

$ touch <Filename>

You can also create multiple files simultaneously

$ touch <filename1> <filename2>

Example:

$ touch example

$ ls

Output:

Desktop Documents Downloads Music Pictures Public Scratch


Templates Videos example
12. echo command

The echo command displays a text or a string to the standard output


or a file.

echo command syntax

$echo “<String>”

Example

$ echo “This is an example of echo”

13. grep :

grep is an acronym for ‘globally search a regular expression and


print it’. The ‘$ grep’ command searches the specified input fully(globally)
for a match with the supplied pattern and displaysit.

Example:

$ grep picture newsfile

In the example, this would search for the word ‘picture’ in the file
newsfile and if found,the lines containing it would be displayed on the
screen.
14. Cat Command

The cat command is used to display the contents of a file.

Syntax of cat command:

cat <filename.extension>

Example:

cat newfile.txt

A few other use of cat command in Linux:

Option Function

cat > [fileName] Create a new file.

Copy content from old file


cat [old_file] > [new_file]
to new file.

Concatenate contents of
cat [file1, file2,….] > [new file name]
multiple files into one file.
cat –n [File_Name] / cat -b [File_Name] Display line numbers.

Display $ character at the


cat -e [fileName]
end of each line.

15. wc

The wc(word count) command is used to find out the number of


new lines, word count, byte, and characters count in a file specified by
the file arguments.

Syntax: wc [options] filenames.

Example: $ wc –l readme.txt

Shows the output as - 120 readme.txt

 wc -l : Prints the number of lines in a file.

 wc -w: Prints the number of words in a file.

 wc -c : Displays the count of bytes in a file.

 wc -m: Prints the count of characters from a file.

 wc -L: Prints only the length of the longest line in a file.

16. head command

This command allows users to view the first lines of any text file.
It shows the first ten lines by default.
head command syntax

$ head [Filename]

You can also manually input the number of lines you want to view.

Syntax

$ head -n <number> <Filename>

17. tail command

This command shows the last ten lines of a text file.

tail command syntax

$ head [Filename]

The number of output lines is ten by default, however, this can be changed
to any number with the -n (number) option.

Syntax

tail -n <number> <Filename>

18. man command

This command is used to check the reference manual pages for


commands or programs.

man command syntax


$ man [Command Name]

Example

$ man head

$ man pwd

19. lpr :

The ‘$ lpr’ command send a file to the printer for printing.

Example: $ lpr new.txt

20. clear :

The ‘$ clear’ command is used to clean up the terminal so that you

can type with more accuracy

Example: $ clear

21. sort :

As the name suggests the ‘$ sort’ sorts the contents of the file
according to the ASCII rules.

$ sort file

22. chmod :
The ‘$ chmod’ command stands for change mode command. As
there are many modes in Unix that can be used to manipulate files in the
Unix environment.

Basically there are 3 modes that we can use with the ‘chmod’
command

1. +w (stands for write and it changes file permissions to write)


2. +r (stands for read and it changes file permissions to read)
3. +x (generally it is used to make a file executable)

Examples:

$ chmod +w file.txt

$ chmod +r file.txt

$ chmod +x file.txt

ls Command

ls is probably the first command every Linux user typed in their terminal.
It list the contents of the directory (the current directory by default), including
files and other nested directories.

ls

2.What is the Linux File System?

 Linux file system is generally a built-in layer of a Linux operating


system used to handle the data management of the storage.
 It helps to arrange the file on the disk storage.
 It manages the file name, file size, creation date, and much more
information about a file.
 If we have an unsupported file format in our file system, we can
download software to deal with it.

The Linux file system contains the following sections:

o The root directory (/)


o A specific data storage format (EXT3, EXT4, BTRFS, XFS and so on)
o A partition or logical volume having a particular file system.

Linux File System Structure

 Linux file system has a hierarchal file structure as it contains a root


directory and its subdirectories.
 All other directories can be accessed from the root directory.
 A partition usually has only one file system, but it may have more than
one file system.
 A file system is designed in a way so that it can manage and provide space
for non-volatile storage data.
 All file systems required a namespace that is a naming and organizational
methodology.
 The namespace defines the naming process, length of the file name, or a
subset of characters that can be used for the file name.
 It also defines the logical structure of files on a memory segment, such as
the use of directories for organizing the specific files.
 Once a namespace is described, a Metadata description must be defined
for that particular file.
 The data structure needs to support a hierarchical directory structure; this
structure is used to describe the available and used disk space for a
particular block.
 It also has the other details about the files such as file size, date & time of
creation, update, and last modified.

Linux file system contains two-part file system software implementation


architecture. Consider the below image:

The file system requires an API (Application programming interface) to access


the function calls to interact with file system components like files and
directories. API facilitates tasks such as creating, deleting, and copying the files.
It facilitates an algorithm that defines the arrangement of files on a file system.

The first two parts of the given file system together called a Linux virtual file
system. It provides a single set of commands for the kernel and developers to
access the file system. This virtual file system requires the specific system driver
to give an interface to the file system.
Linux File System Features

o Specifying paths: Linux does not use the backslash (\) to separate the
components; it uses forward slash (/) as an alternative. For example, as in
Windows, the data may be stored in C:\ My Documents\ Work, whereas,
in Linux, it would be stored in /home/ My Document/ Work.

o Partition, Directories, and Drives: Linux does not use drive letters to
organize the drive as Windows does.

o Case Sensitivity: Linux file system is case sensitive. It distinguishes


between lowercase and uppercase file names. Such as, there is a difference
between test.txt and Test.txt in Linux. This rule is also applied for
directories and Linux commands.

o File Extensions: In Linux, a file may have the extension '.txt,' but. If we
use the graphical file manager, it symbolizes the files and folders.

o Hidden files: Linux distinguishes between standard files and hidden files,
mostly the configuration files are hidden in Linux OS. The hidden files in
Linux are represented by a dot (.) before the file name (e.g., .ignore). To
access the files, we need to change the view in the file manager or need to
use a specific command in the shell.

Types of Linux File System

When we install the Linux operating system, Linux offers many file systems such
as Ext, Ext2, Ext3, Ext4, JFS, ReiserFS, XFS, btrfs, and swap.

1. Ext, Ext2, Ext3 and Ext4 file system


The file system Ext stands for Extended File System. It was primarily developed
for MINIX OS. The Ext file system is an older version, and is no longer used due
to some limitations.

Ext2 is the first Linux file system that allows managing two terabytes of data.
Ext3 is developed through Ext2; it is an upgraded version of Ext2 and contains
backward compatibility. The major drawback of Ext3 is that it does not support
servers because this file system does not support file recovery and disk snapshot.

Ext4 file system is the faster file system among all the Ext file systems. It is a
very compatible option for the SSD (solid-state drive) disks, and it is the default
file system in Linux distribution.

2. JFS File System

JFS stands for Journaled File System, and it is developed by IBM for AIX
Unix. It is an alternative to the Ext file system. It can also be used in place of
Ext4, where stability is needed with few resources. It is a handy file system
when CPU power is limited.

3. ReiserFS File System

ReiserFS is an alternative to the Ext3 file system. It has improved performance


and advanced features. In the earlier time, the ReiserFS was used as the default
file system in SUSE Linux, but later it has changed some policies, so SUSE
returned to Ext3. This file system dynamically supports the file extension, but it
has some drawbacks in performance.

4. XFS File System


XFS file system was considered as high-speed JFS, which is developed for
parallel I/O processing. NASA still using this file system with its high storage
server (300+ Terabyte server).

5. Btrfs File System

Btrfs stands for the B tree file system. It is used for fault tolerance, repair system,
fun administration, extensive storage configuration, and more. It is not a good
suit for the production system.

6. Swap File System

The swap file system is used for memory paging in Linux operating system during
the system hibernation. A system that never goes in hibernate state is required to
have swap space equal to its RAM size.

3.What is the VI editor?


The VI editor is the most popular and classic text editor in the Linux family.

1) It is available in almost all Linux Distributions

2) It works the same across different platforms and Distributions

3) It is user-friendly. Hence, millions of Linux users use it for their editing needs.

The most popular one is VIM which is Vi Improved

Some of the other ones are Elvis, Nvi, Nano, and Vile.
Modes of Operation in vi editor

There are three modes of operation in vi:

 Command Mode:
The vi editor opens in this mode, and it only understands
commands
In this mode, you can, move the cursor and cut, copy, paste
the text

This mode also saves the changes you have made to the file

Commands are case sensitive.

vi Editor Insert mode:

 This mode is for inserting text in the file.


 You can switch to the Insert mode from the command mode by pressing
‘i’ on the keyboard
 Once you are in Insert mode, any key would be taken as an input for the
file on which you are currently working.
 To return to the command mode and save the changes you have made you
need to press the Esc key

 Last Line Mode(Escape Mode):

 Line Mode is invoked by typing a colon [:], while vi is in Command


Mode.
 The cursor will jump to the last line of the screen and vi will wait
for a command.
 This mode enables you to perform tasks such as saving files,
executing commands.

Starting the vi Editor

The way to start using vi editor :

Commands and their Description

 vi filename: Creates a new file if it already not exist, otherwise


opens existing file.
 vi -R filename : Opens an existing file in read only mode.
 view filename : Opens an existing file in read only mode.

Moving within a File(Navigation):


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

Commands and their Description

 k : Moves the cursor up one line.


 j : Moves the cursor down one line.
 h : Moves the cursor to the left one character position.
 l : Moves the cursor to the right one character position.
 0 or | : Positions cursor at beginning of line.
 $ : Positions cursor at end of line.
 W : Positions cursor to the next word.
 B : Positions cursor to previous word.
 ( : Positions cursor to beginning of current sentence.
 ) : Positions cursor to beginning of next sentence.
 H : Move to top of screen.
 nH : Moves to nth line from the top of the screen.
 M : Move to middle of screen.
 L : Move to bottom of screen.
 nL : Moves to nth line from the bottom of the screen.
 colon along with x : Colon followed by a number would position
the cursor on line number represented by x.

Control Commands(Scrolling):

There are following useful commands which can used along with Control Key:

Commands and their Description:

 CTRL+d : Move forward 1/2 screen.


 CTRL+f : Move forward one full screen.
 CTRL+u : Move backward 1/2 screen.
 CTRL+b : Move backward one full screen.
 CTRL+e : Moves screen up one line.
 CTRL+y : Moves screen down one line.
 CTRL+u : Moves screen up 1/2 page.
 CTRL+d : Moves screen down 1/2 page.
 CTRL+b : Moves screen up one page.
 CTRL+f : Moves screen down one page.
 CTRL+I : Redraws screen.

Editing and inserting in Files(Entering and Replacing Text):

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

 i : Inserts text before current cursor location.


 I : Inserts text at beginning of current line.
 a : Inserts text after current cursor location.
 A : Inserts text at end of current line.
 o : Creates a new line for text entry below cursor location.
 O : Creates a new line for text entry above cursor location.
 r : Replace single character under the cursor with the next character
typed.
 R : Replaces text from the cursor to right.
 s : Replaces single character under the cursor with any number of
characters.
 S :Replaces entire line.

Deleting Characters:
List of commands which can be used to delete characters and lines in an opened
file.

 X Uppercase: Deletes the character before the cursor location.


 x Lowercase : Deletes the character at the cursor location.
 Dw : Deletes from the current cursor location to the next word.
 d^ : Deletes from current cursor position to the beginning of the
line.
 d$ : Deletes from current cursor position to the end of the line.
 Dd : Deletes the line the cursor is on.

Copy and Paste Commands:

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

 Yy : Copies the current line.


 9yy : Yank current line and 9 lines below.
 p : Puts the copied text after the cursor.
 P : Puts the yanked text before the cursor.

Save and Exit Commands of the ex Mode :

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

 q : Quit
 q! : Quit without saving changes i.e. discard changes.
 r fileName : Read data from file called fileName.
 wq : Write and quit (save and exit).
 w fileName : Write to file called fileName (save as).
 w! fileName : Overwrite to file called fileName (save as
forcefully).
 !cmd : Runs shell commands and returns to Command mode.

Searching and Replacing in (ex Mode):


vi also has powerful search and replace capabilities.

syntax
:s/string

For example, to search some text for the string “geeksforgeeks” Type the
following and press ENTER:

:s/geeksforgeeks

Output:

finding the first match for “geeksforgeeks” in text will then be highlighted.
The syntax for replacing one string with another string in the current line is:

:s/pattern/replace/

Here “pattern” represents the old string and “replace” represents the new string.
For example, to replace each occurrence of the word “geeks” in a line with
“geeksforgeeks” type:

:s/geeksforgeeks/gfg/
output

The syntax for replacing every occurrence of a string in the entire text is
similar. The only difference is the addition of a “%” in front of the “s”:

:%s/pattern/replace/

Thus repeating the previous example for the entire text instead of just for a single
line would be:

:%s/gfg/geeksforgeeks/

4.Partitions creation :

Creating disk partitions enables you to split your hard drive into multiple
sections that act independently. Partitioning is particularly useful if you run
multiple operating systems.
Steps to create a partition using the Linux fdisk command.

Step 1: List Existing Partitions

Run the following command to list all existing partitions:

sudo fdisk –l

Step 2: Select Storage Disk

Select the storage disk where to create partitions on by running the following
command:

sudo fdisk /dev/sdb

now, the /dev/sdbstorage disk is open:

(/dev/sda is the hard disk of the computer we are using. sd[a-z] is the currently used
naming format for disks in Linux. And lastly, /dev/sda[1-15] shows the partitions within hard
disk)

Step 3: Create a New Partition

1. Run the n command to create a new partition.

2. Select the partition number by typing the default number (2).

3. After that, you are asked for the starting and ending sector of your hard drive.
It is best to type the default number in this section (3622912).

4. The last prompt is related to the size of the partition. one can choose to have
several sectors or to set the size in megabytes or gigabytes.

Type +2GB to set the size of the partition to 2GB.


Finally ,A message appears confirming that the partition is created.

Step 4: Write on Disk

The system created the partition, but the changes are not written on the disk.

1. To write the changes on disk, run the w command:

2. Verify that the partition is created by running the following command:

sudo fdisk -l

Now output will be, the partition /dev/sdb2 has been created.

Format the Partition

Once a partition has been created with the parted of fdisk command, format it
before using it.

Format the partition by running the following command:

sudo mkfs -t ext4 /dev/sdb1

5.What is Shell?

 A shell is special user program which provide an interface to user to use


operating system services.
 Shell accept human readable commands from user and convert them into
something which kernel can understand.
 It is a command language interpreter that execute commands read from
input devices such as keyboards or from files.
 The shell gets started when the user logs in or start the terminal.

Shell Prompt

The prompt, $, which is called the command prompt, is issued by the shell.
While the prompt is displayed, you can type a command.

Shell reads your input after you press Enter.

Example :the date command, which displays the current date and time −

$date

o/p : Thu Jun 25 08:30:19 MST 2009


Shell Types

In linux, there are two major types of shells −


 Bourne shell − If you are using a Bourne-type shell, the $ character is the
default prompt.

 C shell − If you are using a C-type shell, the % character is the default
prompt.

The Bourne Shell has the following subcategories −


 Bourne shell (sh)
 Korn shell (ksh)
 Bourne Again shell (bash)
 POSIX shell (sh)

The different C-type shells follow −


 C shell (csh)
 TENEX/TOPS C shell (tcsh)

Shell Scripts

 Shells are interactive, they accept command as input from users and
execute them.
 Some times to execute a bunch of commands routinely, instead of typing
in all commands each time in terminal..
 we can write these commands in a file and can execute them in shell to
avoid this repetitive work. These files are called Shell Scripts or Shell
Programs.
 Shell scripts are similar to the batch file in MS-DOS. Each shell script is
saved with .sh file extension eg. myscript.sh
 To create a script containing commands, u put the shebang line first and
then add the commands − ( It's called a shebang because the # symbol is called
a hash, and the ! symbol is called a bang.) to alert the system that shell script is start….

#!/bin/bash

pwd

ls

 Save the above content and make the script executable −

$chmod +x test.sh

 The shell script is now ready to be executed –


To execute a program available in the current directory,
use ./program_name

$./test.sh

 Upon execution, you will receive the following result −

/home/amrood

index.htm unix-basic_utilities.htm unix-directories.htm

test.sh unix-communication.htm unix-environment.htm

Example2

The following script uses the read command which takes the input from the
keyboard and assigns it as the value of the variable PERSON and finally prints it
on STDOUT.
#!/bin/sh

echo "What is your name?"

read PERSON

echo "Hello, $PERSON"

O/P:

$./test.sh

What is your name?

Zara Ali

Hello, Zara Ali

6.What is a process?

 A process is an instance of a running program.


 It is the job of Kernel to manage CPU time and other resources among
multipleprocesses.
Each process is given a unique PID (process ID).
 PID is allotted by Kernel when a process is born.

ListingProcess:
# ps (displays the following)
PID TTY TIME CMD

22794 tty1 00:00:00 bash

22809 tty1 00:00:00 ps

Finding Process:

# ps axu | grep tty2


(shows all process, running on all terminal by all users. Use grep for
filtering)

# pgrep -u username
(to see PID related to specific user)

#pidof crond
(to see PID of specific process)

Signals:

 Signals are messages that are sent to processes with a command like kill.
The advantage of signals is that they can be sent to a process even if it is
not attached to a terminal.
 So if a web server or a graphical program whose interface has “frozen”
can still be shut down by sending appropriate signal.
Sending signals to processes:
 Process normally terminate on their own when they have completed.
 Interactive application may need the user to issue a quit command.
 CTRL + C also terminate the process, which send an interrupt (INT) signal
to a process.
 If a process doesn’t terminate using above method, you can
use KILL signal.

Scheduling Priority:

 Every running process has a scheduling priority, Whoever has got higher
priority, gets more attention of the CPU.
 The priority of process is set by altering niceness value.
 The niceness value defaults to zero(0) but can be set from -20 (least value,
highest piority) to 19 (highest value, least priority)

To set the niceness value to a specific value when starting a


process, use nice -n as following:

nice -n 13 vim file.txt (to run vim at 13 niceness value)


nice -n -13 vim file.txt (to run vim at -13 niceness value)

To modify the niceness value of running processes, use renice command as


following:
renice 15 PID (Where PID is process ID of running process)
renice -15 PID
Interactive Process Management Tools:

 Running top presents a list of the processes running on your system,


updated every 5 seconds,
 you can use keystrokes to kill, renice, colorize processes, define the order
to display etc.
 Press the ? key while in top to view the complete list of hotkeys.

Job Control:

 Jobs running in the foreground can be suspended: temporarily stopped,


without being killed.
 To suspend a job, Press Ctrl + z.
 Once a process is suspended, it can be resume in the background using
the bg command or resumed in the foreground using the fg command.
 When the job resumes, it will continue executing from the point at which
it was suspended. It will not have to start over from the beginning.

# man mkdir (press ctrl + z to suspend this job)

[1]+ stopped

Bg to resume the recent suspended job in background

bg 2 to resume the job 2 in background

Jobs to see all suspended job

fg 2 to resume the job 2 in foreground

You might also like