0% found this document useful (0 votes)
3 views

FOSS 3rd Module

Free and open source software Module third,bsc ku(2021)onwards

Uploaded by

vorera6922
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)
3 views

FOSS 3rd Module

Free and open source software Module third,bsc ku(2021)onwards

Uploaded by

vorera6922
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/ 55

FOSS

Module III
Linux Commands: date, time, who, echo, man, info, cal, pwd, more, less, head, tail, mkdir, cd, cp, mv,
rm, touch, sort, wc, cut, cat with options, ls with options ,grep with options, chmod, diff, mounting the
file system, command line processing etc. Types of editors in Linux, Introduction to vi editor, modes in
vi editor, common vi editor commands for open a file, save a file, delete a file, quit a file etc

*******************

LINUX COMMANDS

DATE COMMAND
The date command is used to display system date, time, time zone, and more.
Syntax: date [OPTION]... [+FORMAT]

Options with Examples


1: date (no option): With no options, the date command displays the current date and time, including
the abbreviated day name, abbreviated month name, day of the month, the time separated by colons,
the time zone name, and the year.
Command: $ date
Output:

2: -u Option: Displays the time in GMT(Greenwich Mean Time)/UTC(Coordinated Universal Time


)time zone.
Command: $date -u
Output : Wed Oct 11 06:11:31 UTC 2017

3: –date or -d Option: Displays the given date string in the format of date. But this will not affect the
system’s actual date and time value. Rather it uses the date and time given in the form of string.
Syntax: $date --date=" string "
Command: $date --date="2/02/2010"
$date --date="Feb 2 2010"
Output:
Tue Feb 2 00:00:00 PST 2010
Tue Feb 2 00:00:00 PST 2010

1
FOSS

4: Using –date option for displaying past dates:


a) Date and time of 2 years ago.
Command: $date --date="2 year ago"
Output: Sat Oct 10 23:42:15 PDT 2015
b) Date and time of 5 seconds ago.
Command: $date --date="5 sec ago"
Output: Tue Oct 10 23:45:02 PDT 2017
c) Date and time of previous day.
Command: $date --date="yesterday"
Output: Mon Oct 9 23:48:00 PDT 2017
d) Date and time of 2 months ago.
Command: $date --date="2 month ago"
Output: Thu Aug 10 23:54:51 PDT 2017
e) Date and time of 10 days ago.
Command: $date --date="10 day ago"
Output: Sat Sep 30 23:56:55 PDT 2017

5: Using –date option for displaying future date:


Date and time of upcoming particular week day.
Command: $date --date="next tue"
Output: Tue Oct 17 00:00:00 PDT 2017

a) Date and time after two days.


Command: $date --date="2 day"
Output: Fri Oct 13 00:05:52 PDT 2017
b) Date and time of next day.
Command: $date --date="tomorrow"
Output: Thu Oct 12 00:08:47 PDT 2017
c) Date and time after 1 year on the current day.
Command: $date --date="1 year"
Output: Thu Oct 11 00:11:38 PDT 2018

6: -s or –set Option: To set the system date and time -s or –set option is used.
Syntax: $date --set="date to be set"

2
FOSS

Command: $date
Output: Wed Oct 11 15:23:26 PDT 2017

Command: $date --set="Tue Nov 13 15:23:34 PDT 2018"


$date
Output: Tue Nov 13 15:23:34 PDT 2018

7: –file or -f Option: This is used to display the date string present at each line of file in the date and
time format. This option is similar to –date option but the only difference is that in –date we can only
give one date string but in a file we can give multiple date strings at each line.
Syntax: $date --file=file.txt
$cat >> datefile
Sep 23 2018
Nov 03 2019

Command: $date --file=datefile


Output: Sun Sep 23 00:00:00 PDT 2018
Sun Nov 3 00:00:00 PDT 2019

8:-r Option: This is used to display the last modified timestamp of a datefile .
Syntax: $date -r file.txt

We can modify the timestamp of a datefile by using touch command.


$touch datefile
$date -r datefile
Wed Oct 11 15:54:18 PDT 2017
//this is the current date and time

$touch datefile
//The timestamp of datefile is changed using touch command.
This was done few seconds after the above date command’s output.
$date -r datefile
Wed Oct 11 15:56:23 PDT 2017
//display last modified time of datefile

3
FOSS

9: List of Format specifiers used with date command:


%D: Display date as mm/dd/yy.
%d: Display the day of the month (01 to 31).
%a: Displays the abbreviated name for weekdays (Sun to Sat).
%A: Displays full weekdays (Sunday to Saturday).
%h: Displays abbreviated month name (Jan to Dec).
%b: Displays abbreviated month name (Jan to Dec).
%B: Displays full month name(January to December).
%m: Displays the month of year (01 to 12).
%y: Displays last two digits of the year(00 to 99).
%Y: Display four-digit year.
%T: Display the time in 24 hour format as HH:MM:SS.
%H: Display the hour.
%M: Display the minute.
%S: Display the seconds.

Syntax: $date +%[format-option]


Eg: Command: $date "+%D"
Output: 10/11/17
Command: $date "+%D %T"
Output: 10/11/17 16:13:27
Command: $date "+%Y-%m-%d"
Output: 2017-10-11
Command: $date "+%Y/%m/%d"
Output: 2017/10/11
Command: $date "+%A %B %d %T %y"
Output: Thursday October 12 07:54:29 17

TIME COMMAND
The time command is used to display the time to execute a command.
Syntax: time [option] [COMMAND]
Command: $time
Output:

4
FOSS

Command: $time sleep 3

sleep 3 is used to create a dummy job which lasts 3 seconds.


Options:
• time -p : This option is used to print time in POSIX format.

WHO COMMAND
The who command is used to get information about currently logged in user on to system. Who
command is used to find out the following information :
1. Time of last system boot
2. Current run level of the system
3. List of logged in users and more.
Syntax : $who [options] [filename] ‘
Options:
1. The who command displays the following information for each user currently logged in to the
system if no option is provided :
a. Login name of the users
b. Terminal line numbers
c. Login time of the users in to system
d. Remote host name of the user
hduser@mahesh-Inspiron-3543:~$ who
hduser tty7 2018-03-18 19:08 (:0)

2. To show list of users logged in to system


hduser@mahesh-Inspiron-3543:~$ who -u
hduser tty7 2018-03-18 19:08 01:16 3357 (:0)

5
FOSS

3. To display system’s username


hduser@mahesh-Inspiron-3543:~$ whoami
hduser
4. To count number of users logged on to system
hduser@mahesh-Inspiron-3543:~$ who -q -H
hduser
# users=1

ECHO COMMAND
The echo command in Linux is a built-in command that allows users to display lines of text or strings
that are passed as arguments.
Syntax: echo [option] [string]
Example: If we want to display “MACAS”.
echo "MACAS"
OPTIONS
NOTE :- -e here enables the interpretation of backslash escapes
1. \b : it removes all the spaces in between the text
Example:

2. \c : suppress trailing new line with backspace interpreter ‘-e‘ to continue without emitting new line.
Example:
echo -e "Geeks \cfor Geeks"

In the above example, text after \c is not printed and omitted trailing new line.

6
FOSS

3. \n : this option creates a new line from where it is used.


Example:
echo -e "Geeks \nfor \nGeeks"

4. \t : this option is used to create horizontal tab spaces.


Example:
echo -e "Geeks \tfor \tGeeks"

5. \r : carriage return with backspace interpreter ‘-e‘ to have specified carriage return in output.
Example:
echo -e "Geeks \rfor Geeks"

In the above example, text before \r is not printed.

7
FOSS

6. \v : this option is used to create vertical tab spaces.


Example:
echo -e "Geeks \vfor \vGeeks

7. \a : alert return with backspace interpreter ‘-e‘ to have sound alert.


Example:
echo -e "\aGeeks for Geeks

This command when executed, it will produce an alert sound or Bell.

8. echo *: this command will print all files/folders, similar to ls command.


Example:
echo *

8
FOSS

9. -n: this option is used to omit echoing trailing newline.


Example:
echo -n "Geeks for Geeks"

10. Redirecting `echo` Output


The output of the `echo` can be redirected to a file instead of displaying it on the terminal. We can
achive this by using the `>` or `>>` operators for output redirection.
Example:
echo "Welcome GFG" > output.txt
This will write the output of the echo command to the file name `output.txt`. File will be overwritten
if it already exists.
If we want to append the output in an existing file, we use `>>` instead of `>`.

Man Command
man command in Linux is used to display the user manual of any command that we can run on the
terminal. It provides a detailed view of the command which includes NAME, SYNOPSIS,
DESCRIPTION, OPTIONS, EXIT STATUS, RETURN VALUES, ERRORS, FILES, VERSIONS,
EXAMPLES, AUTHORS and SEE ALSO.

Syntax : $ man [OPTION] [COMMAND NAME]


Options:
1) No Option: It displays the whole manual of the command.
Syntax : $ man [COMMAND NAME]
Example: $ man printf
Output:

9
FOSS

2. Section-num: Since a manual is divided into multiple sections so this option is used to display only
a specific section of a manual.
Syntax : $ man [SECTION-NUM] [COMMAND NAME]
Example: $ man 2 intro
Output:

3. -f option: One may not be able to remember the sections in which a command is present. So this
option gives the section in which the given command is present.
Syntax:
$ man -f [COMMAND NAME]

10
FOSS

Example:
$ man -f ls
Output:

CAL COMMAND
cal command is a calendar command in Linux which is used to see the calendar of a specific month or a
whole year.
Syntax: cal [ [ month ] year]
Example : cal jun 2023
cal : Shows current month calendar on the terminal with the current date highlighted.

cal -y : Shows the calendar of the complete current year with the current date highlighted.

11
FOSS

cal 08 2000 : Shows calendar of selected month and year.

cal 2018 : Shows the whole calendar of the year.

cal 2018 | more : But year may not be visible in the same screen use more with cal use spacebar to
scroll down.

12
FOSS

Cal -3: Shows calendar of previous, current and next month.

cal -j : Shows the calendar of the current month in the Julian calendar format not in the
default Gregorian calendar format. In Julian calendar format, the date does not reset to 1 after every
month’s end i.e. after 31st Jan, Feb will start as 32nd Feb, not as 1st Feb. But in the Gregorian calendar
format, the date is reset to 1 after every month’s end i.e after 31st Jan, Feb will start as of 1st Feb.

INFO COMMAND:
Info command reads documentation in the info format. It will give detailed information for a command
when compared with the man page.
Syntax:
info [OPTION]... [MENU-ITEM...]
Options:
• -a, –all: It use all matching manuals.
• -k, –apropos=STRING: It look up STRING in all indices of all manuals.
• -d, –directory=DIR: It add DIR to INFOPATH.
• -f, –file=MANUAL: It specify Info manual to visit.
• -h, –help: It display this help and exit.
• -n, –node=NODENAME: It specify nodes in first visited Info file.
• -o, –output=FILE: It output selected nodes to FILE.

13
FOSS

• -O, –show-options, –usage: It go to command-line options node.


• -v, –variable VAR=VALUE: It assign VALUE to Info variable VAR.
• –version: It display version information and exit.
• -w, –where, –location: It print physical location of Info file.

Examples:
• -a : It use all matching manuals and display them for a particular command.
info -a cvs

• -k : It look up STRING in all indices of all manuals and then display the same.
info -k cvs

14
FOSS

• -d : It adds DIR to INFOPATH and also display the same.


info -d cvs

• -O : It go to command-line options node for a particular command and display the same.
info -O cvs

15
FOSS

• -w Command : It print physical location of Info file.


info -w cvs

PWD COMMAND
pwd stands for Print Working Directory. It prints the path of the working directory, starting from the
root.
Syntax: pwd [OPTIONS]
Example: pwd -L: Prints the symbolic path.
pwd -P: Prints the actual path.

MORE COMMAND
more command is used to view the text files in the command prompt, displaying one screen at a time in
case the file is large (For example log files).
Syntax: more [-options] [-num] [+/pattern] [+linenum] [file_name]
• [-options]: any option that you want to use in order to change the way the file is displayed. Choose
any one from the followings: (-d, -l, -f, -p, -c, -s, -u)
• [-num]: type the number of lines that you want to display per screen.
• [+/pattern]: replace the pattern with any string that you want to find in the text file.
• [+linenum]: use the line number from where you want to start displaying the text content.
• [file_name]: name of the file containing the text that you want to display on the screen.

Options:
• -d : Use this command in order to help the user to navigate. It displays “[Press space to continue,
‘q’ to quit.]” and displays “[Press ‘h’ for instructions.]” when wrong key is pressed.

16
FOSS

Example: more -d sample.txt

• -f : This option does not wrap the long lines and displays them as such.
Example:
more -f sample.txt

17
FOSS

• -p : This option clears the screen and then displays the text.
Example:
more -p sample.txt

• -c : This command is used to display the pages on the same area by overlapping the previously
displayed text.
Example:
more -c sample.txt

18
FOSS

• -s : This option squeezes multiple blank lines into one single blank line.
Example:
more -s sample.txt

• -u : This option omits the underlines.


Example: more -u sample.txt
• +/pattern : This option is used to search the string inside your text document. You can view all
the instances by navigating through the result.
Example:more +/reset sample.txt

19
FOSS

• +num : This option displays the text after the specified number of lines of the document.
Example:
more +30 sample.txt

Less Command
Less command is a Linux utility that can be used to read the contents of a text file one page (one screen)
at a time. It has faster access because if a file is large, it doesn’t access the complete file, but accesses it
page by page.
Syntax: less [options] filename
Example: less -p "sample.txt"

USING LESS WITH PIPELINES


The less command can also be used in conjunction with other commands through pipelines. This
allows us to view the output of a command directly in the less pager.

SEARCHING FOR A PATTERN


dmesg | less -p "fail"
The above command tells less to start at first occurrence of pattern “fail” in the file and displaying the
file from that point.
Output:

20
FOSS

DISPLAYING LINE NUMBER


dmesg | less -N
The -N option displays line numbers along with the file content, allowing you to reference specific
lines easily.
Output:

CHECKING A SMALL FILE


less -F /home/Mandeep/test/first.erl
In this example, the file `/home//Mandeep/test/first.erl` is small enough to fit on a single screen. The
`-F` option causes less to exit immediately without displaying the file since it can be fully shown in
one go.

21
FOSS

HEAD COMMAND
The head command, as the name implies, print the top N number of data of the given input. By default,
it prints the first 10 lines of the specified files
Syntax: head [OPTION]... [FILE]...
Example: $ cat state.txt
Andhra Pradesh Arunachal Pradesh Assam Bihar Chhattisgarh Goa Gujarat
Haryana Himachal Pradesh Jammu and Kashmir Jharkhand Karnataka
Kerala Madhya Pradesh Maharashtra Manipur Meghalaya Mizoram
Nagaland Odisha Punjab Rajasthan Sikkim Tamil Nadu
Telangana Tripura Uttar Pradesh Uttarakhand West Bengal

Without any option, it displays only the first 10 lines of the file specified.
$head state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir
Options

1. -n num: Prints the first ‘num’ lines instead of first 10 lines. num is mandatory to be specified in
command otherwise it displays an error.
$ head -n 5 state.txt
Andhra Pradesh Arunachal Pradesh Assam Bihar Chhattisgarh

22
FOSS

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

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

Without using -q option


$ head state.txt capital.txt
==> state.txt <== ==> capital.txt <==
Andhra Pradesh Hyderabad
Arunachal Pradesh Itanagar
Assam Dispur
Bihar Patna
Chhattisgarh Raipur
Goa Panaji
Gujarat Gandhinagar
Haryana Chandigarh
Himachal Pradesh Shimla
Jammu and Kashmir Srinagar

With using -q option


$ head -q state.txt capital.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir

23
FOSS

Hyderabad
Itanagar
Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar

4. -v: By using this option, data from the specified file is always preceded by its file name.
$ head -v state.txt
==> state.txt <==
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Goa
Gujarat
Haryana
Himachal Pradesh
Jammu and Kashmir

Applications of head Command


1. Print line between M and N lines(M>N): For this purpose, we use the head, tail, and pipeline(|)
commands. The command is: head -M file_name | tail +N since the head command takes first M
lines and from M lines tail command cuts lines starting from +N till the end, we can also use head
-M file_name | tail +(M-N+1) command since the head command takes first M lines and from M
lines tail command cuts (M-N+1) lines starting from the end. Let say from the state.txt file we have
to print lines between 10 and 20.
$ head -n 20 state.txt | tail -10
Jharkhand
Karnataka

24
FOSS

Kerala
Madhya Pradesh
Maharashtra
Manipur
Meghalaya
Mizoram
Nagaland
Odisha

2) How to use the head with pipeline(|): The head command can be piped with other commands. In
the following example, the output of the ls command is piped to head to show only the three most
recently modified files or folders.
Display all recently modified or recently used files.
$ ls -t
e.txt
d.txt
c.txt
b.txt
a.txt

Cut three most recently used file.


$ ls -t | head -n 3
e.txt
d.txt
c.txt

3) It can also be piped with one or more filters for additional processing. For example, the sort filter
could be used to sort the three most recently used files or folders in the alphabetic order.

$ ls -t | head -n 3 | sort
c.txt
d.txt
e.txt

25
FOSS

TAIL COMMAND
The tail command print the last N number of data of the given input. By default it prints the last 10 lines
of the specified files.
Syntax: tail [OPTION]... [FILE]...
Without any option it display only the last 10 lines of the file specified.
Example:$ tail state.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
WEST BENGAL
Options:

1. -n num: Prints the last ‘num’ lines instead of last 10 lines. num is mandatory to be specified in
command otherwise it displays an error. This command can also be written as without symbolizing
‘n’ character but ‘-‘ sign is mandatory.
$ tail -n 3 state.txt $ tail -3 state.txt
Uttar Pradesh Uttar Pradesh
Uttarakhand Uttarakhand
West Bengal West Bengal
OR

Tail command also comes with an ‘+’ option which is not present in the head command. With this
option tail command prints the data starting from specified line number of the file instead of end. For

26
FOSS

command: tail +n file_name, data will start printing from line number ‘n’ till the end of the file
specified.

$ tail +25 state.txt


Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal

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

Note: Without positive or negative sign before num, command will display the last num bytes from
the file specified.
With negative num
$ tail -c -6 state.txt
Bengal
OR
$ tail -c 6 state.txt
Bengal

With positive num


$ tail -c +263 state.txt
Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand

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

27
FOSS

Without using -q option


$ tail state.txt capital.txt
state.txt capital.txt
Odisha Dispur
Punjab Patna
Rajasthan Raipur
Sikkim Panaji
Tamil Nadu Gandhinagar
Telangana Chandigarh
Tripura Shimla
Uttar Pradesh Srinagar
Uttarakhand Ranchi
West Bengal

With using -q option


$ tail -q state.txt capital.txt
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal Dispur
Patna
Raipur
Panaji
Gandhinagar
Chandigarh
Shimla
Srinagar
Ranchi
Bengaluru

28
FOSS

4. -f: This option is mainly used by system administration to monitor the growth of the log files written
by many Unix program as they are running. This option shows the last ten lines of a file and will
update when new lines are added. As new lines are written to the log, the console will update with the
new lines. The prompt doesn’t return even after work is over so, we have to use the interrupt key to
abort this command. In general, the applications writes error messages to log files. You can use the -
f option to check for the error messages as and when they appear in the log file.

$ tail -f logfile

5. -v: By using this option, data from the specified file is always preceded by its file name.
$ tail -v state.txt
==> state.txt <==
Odisha
Punjab
Rajasthan
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal

6. –version: This option is used to display the version of tail which is currently running on your
system.
$ tail --version
tail (GNU coreutils) 8.26
Packaged by Cygwin (8.26-1)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later .
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Paul Rubin, David MacKenzie, Ian Lance Taylor,
and Jim Meyering.

29
FOSS

Applications of tail Command


1. How to use tail with pipes(|): The tail command can be piped with many other commands of the
unix. In the following example output of the tail command is given as input to the sort command with
-r option to sort the last 7 state names coming from file state.txt in the reverse order.
$ tail -n 7 state.txt
Sikkim
Tamil Nadu
Telangana
Tripura
Uttar Pradesh
Uttarakhand
West Bengal

$ tail -n 7 state.txt | sort -r


West Bengal
Uttarakhand
Uttar Pradesh
Tripura
Telangana
Tamil Nadu
Sikkim
It can also be piped with one or more filters for additional processing. Like in the following example,
we are using cat, head and tail command and whose output is stored in the file name list.txt using
directive(>).

$ cat state.txt | head -n 20 | tail -n 5 > list.txt


$ cat list.txt
Manipur
Meghalaya
Mizoram
Nagaland
Odisha

30
FOSS

MKDIR COMMAND
mkdir command in Linux allows the user to create directories (also referred to as folders in some
operating systems). This command can create multiple directories at once as well as set the permissions
for the directories.
Syntax: mkdir [options...] [directories ...]
example: mkdir -p [mydirectory]

1) HOW TO CREATE A DIRECTORY USING `MKDIR` COMMAND?


Syntax: mkdir [directory_name]
For Example: If we want to create a directory name “jayesh_gfg”.
Syntax: mkdir jayesh_gfg

2) HOW TO CREATE A DIRECTORY WITH VERBOSE OUTPUT USING `MKDIR`


COMMAND?
Syntax: mkdir -v [directory_name]
For Example: If we want to create a directory name “geeksforgeeks” and see verbose at same time.
You can enter your directory_name.
Syntax: mkdir -v geeksforgeeks

3) HOW TO CREATE MULTIPLE DIRECTORIES USING `MKDIR` COMMAND?


Syntax: mkdir [directorie_name_1] [directorie_name_1] [directorie_name_1] .......
For Example: If we want to create a directory name “jayesh_gfg_1, jayesh_gfg_2, jayesh_gfg_3”.
Syntax: mkdir jayesh_gfg_1 jayesh_gfg_2 jayesh_gfg_3

31
FOSS

Here we have used `ls` command to display all files and directories.

CD COMMAND
The cd command in Linux stands for change directory. It is used to change the current directory of the
terminal. The terminal, by default, opens the home directory.
SYNTAX: CD [DIRECTORY]
Example : cd /
To go to the root directory, we input / as the argument.

cd
We do not provide any arguments to the cd command to go to the home directory.

32
FOSS

cd . .
To shift one level above the current directory, we input .. as the argument.

cd -
To go to the previous directory, we use - as our argument.
cd /folder/subfolder

CP COMMAND
cp stands for copy. This command is used to copies files or groups of files or directories from a source
to a destination.
Syntax: cp [options] 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.
Example : $ cp a.txt b.txt

Suppose there is a directory named geeksforgeeks having a text file a.txt, b.txt and a directory
name new in which we are going to copy all files.
$ ls
a.txt b.txt new

Initially new is empty


$ ls new

$ cp a.txt b.txt new


$ ls new
a.txt b.txt

33
FOSS

For this case the last argument must be a directory name. For the above command to work, Dest
directory must exist because cp command won’t create it.

MV COMMANDS
MV stands for move. This command is used to rename file directories and move files from one location
to another within a file system.
Two Distinct Functions of `mv` Command
1) Renaming a file or directory.
2) Moving a file or directory to another location

Syntax: mv [options(s)] [source_file_name(s)] [Destination_file_name]


source_file_name(s) = The name of the files that we want to rename or move.
Destination_file_name = The name of the new location or the name of the file.

Example: 1) Renaming a file in linux:


Syntax: mv [source_file_name(s)] [Destination_file_name]
If we have a file “name = jayesh_gfg” and want to rename it to “name = geeksforgeeks”.
mv jayesh_gfg geeksforgeeks

This command is renamed `jayesh_gfg` to `geeksforgeeks`. If `geeksforgeeks` already exists, in that


case, it will be overwritten without prompting for confirmation.

2) MOVING A FILE IN LINUX


Syntax: mv [source_file_name(s)] [Destination_path]
eg: mv geeksforgeeks /home/jayeshkumar/jkj/

34
FOSS

This command moved file “name = `geeksforgeeks`” to the destination “name =


“/home.jayeshkumar/jkj/”.

3) MOVING MULTIPLE FILES IN LINUX


Syntax:
mv[source_file_name_1][source_file_name_2][source_file_name_.....][Destination_path]
eg: mv gfg_1 gfg_2 /home/jayeshkumar/jkj/

This command moved file “name = `gfg_1 and gfg_2`” to the destination “name =
“/home.jayeshkumar/jkj/”.

4) RENAMING A DIRECTORY IN LINUX


Syntax: mv [source_directory_name(s)] [Destination_directory_name]
eg: mv jkj new_gfg

This command renames `jkj` to `new_gfg`. If `new_gfg` already exists, in that case it will be
overwritten without prompting for confirmation.

RM COMMAND
rm stands for remove here. rm command is used to remove objects such as files, directories, symbolic
links and so on from the file system
syntax : rm [OPTION]... FILE...
Example: $ ls
a.txt b.txt c.txt d.txt e.txt
Removing one file at a time
$ rm a.txt

35
FOSS

$ 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 for confirm deletion, any other key leaves the file un-
deleted.

TOUCH COMMAND
The touch command is a standard command used in the UNIX/Linux operating system which is used
to create, change and modify the timestamps of a file.
there are two different commands to create a file in the Linux system which are as follows:
• cat command: It is used to create the file with content.
• touch command: It is used to create a file without any content. The file created using the touch
command is empty. This command can be used when the user doesn’t have data to store at the time
of file creation.
• You can update the modification and access time of each file with the help of touch command.
Syntax: touch <filename>
Example: touch myfile1
• Touch command can be used to create multiple numbers of files at the same time. These files would
be empty while creation.
Syntax: touch File1_name File2_name File3_name
Options:
i) touch -a Doc1
Here touch -a command changes access time of the file named Doc1.
ii) touch -c-d filename
this is used to update access and modification time.
iii) touch -m fileName
This is used to change the modification time only. It only updates last modification time.

36
FOSS

SORT COMMAND
• SORT command is used to sort a file, arranging the records in a particular order.
• By default, the sort command sorts file assuming the contents are ASCII.
Syntax: sort <fileName>
Example: $ cat > mix.txt
abc
apple
BALL
Abc
bat
Now use the sort command
$ sort mix.txt
Output :
Abc
BALL
abc
apple
bat

OPTIONS:
Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag. the -r flag is an
option of the sort command which sorts the input file in reverse order i.e. descending order by default.
Syntax :
$ sort -r inputfile.txt
Command : $ sort -r file.txt
Output: :
satish
rajan
naveen
harsh
divyam
chitransh
abhishek

37
FOSS

n Option: To sort a file numerically used –n option.


Command :
$ cat > file1.txt
50
39
15
89
200
Syntax: $ sort -n filename.txt
Command : $ sort -n file1.txt
Output :
15
39
50
89
200

-nr option: To sort a file with numeric data in reverse order we can use the combination of two
options as stated below.
Example: The numeric file is the same as above.
Syntax : $ sort -nr filename.txt
Command : $ sort -nr file1.txt
Output :
200
89
50
39
15

-M Option: To sort by month pass the -M option to sort. This will write a sorted list to standard
output ordered by month name.
Example:
Suppose the following file exists and is saved as months.txt
$ cat > months.txt
February

38
FOSS

January
March
August
September

Syntax : $ sort -M filename.txt


Command :
$ sort -M months.txt
$ cat months.txt
Output :
January
February
March
August
September

wc Command
• wc stands for word count.
• It is used to find out number of lines, word count, byte and characters count in the files
specified in the file arguments.
• By default it displays four-columnar output.
• First column shows number of lines present in a file specified, second column shows number of
words present in the file, third column shows number of characters present in file and fourth
column itself is the file name which are given as argument.
Syntax: wc <file name>
Example : $ cat state.txt $ cat capital.txt
Andhra Pradesh Hyderabad
Arunachal Pradesh Itanagar
Assam Dispur
Bihar Patna
Chhattisgarh Raipur

$ wc state.txt
5 7 58 state.txt

39
FOSS

OR
$ wc capital.txt
5 5 39 capital.txt

Passing more than one file name in the argument.


$ wc state.txt capital.txt
5 7 58 state.txt
5 5 39 capital.txt
10 12 97 total

Options:
1. -l: This option prints the number of lines present in a file.
With one file name
$ wc -l state.txt
5 state.txt

With more than one file name


$ wc -l state.txt capital.txt
5 state.txt
5 capital.txt
10 total

2. -w: This option prints the number of words present in a file.


With one file name
$ wc -w state.txt
7 state.txt

With more than one file name


$ wc -w state.txt capital.txt
7 state.txt
5 capital.txt
12 total

4. -m: Using -m option ‘wc’ command displays count of characters from a file.
With one file name

40
FOSS

$ wc -m state.txt
56 state.txt

With more than one file name


$ wc -m state.txt capital.txt
58 state.txt
39 capital.txt
97 total

CUT COMMAND
Linux cut command is useful for selecting a specific column of a file. It is used to cut a specific sections
by byte position, character, and field and writes them to standard output. It cuts a line and extracts the
text data.
Syntax:
cut OPTION... [FILE]...
eg: $ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh

OPTIONS:
1. -b(byte): To extract the specific bytes, you need to follow -b option with the list of byte numbers
separated by comma. Range of bytes can also be specified using the hyphen(-). It is necessary to
specify list of byte numbers otherwise it gives error. Tabs and backspaces are treated like as a
character of 1 byte.
List without ranges
$ cut -b 1,2,3 state.txt
And
Aru
Ass
Bih
Chh

41
FOSS

List with ranges


$ cut -b 1-3,5-7 state.txt
Andra
Aruach
Assm
Bihr
Chhtti

In this, 1- indicate from 1st byte to end byte of a line


$ cut -b 1- state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh

In this, -3 indicate from 1st byte to 3rd byte of a line


$ cut -b -3 state.txt
And
Aru
Ass
Bih
Chh

2. -c (column): To cut by character use the -c option. This selects the characters given to the -c option.
This can be a list of numbers separated comma or a range of numbers separated by hyphen(-).
$ cut -c 2,5,7 state.txt
nr
rah
sm
ir
hti
Above cut command prints second, fifth and seventh character from each line of the file.
$ cut -c 1-7 state.txt
Andhra

42
FOSS

Arunach
Assam
Bihar
Chhatti
Above cut command prints first seven characters of each line from the file.
Cut uses a special form for selecting characters from beginning upto the end of the line:
$ cut -c 1- state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh
Above command prints starting from first character to end. Here in command only starting
position is specified and the ending position is omitted.

$ cut -c -5 state.txt
Andhr
Aruna
Assam
Bihar
Chhat
Above command prints starting position to the fifth character. Here the starting position
is omitted and the ending position is specified.

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.
1) To view a single file
Syntax: cat file_name
Example: If our file_name = jayesh.txt
cat jayesh.txt

2) To view multiple files


Syntax: cat file_name1 file_name2
Example: cat file1 file2

43
FOSS

3) Create a file and add content


Syntax: cat > newfile_name
Example: If we want to create a newfile_name = jayesh1.
cat > jayesh1

4) Copy the contents of one file to another file.


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

5) Cat command can append the contents of one file to the end of another file.
Syntax: cat file_name1 >> file_name2
Example: cat file1 >> file2

LS COMMAND
• In Linux, the command "ls" is one of the most commonly used. It's used to display a list of files and
sub-directories in the current directory.
• The 'ls' command is used to list files and directories
• The contents of your current working directory, which is just a technical way of stating the directory
that your terminal is presently in, will be listed if you run the "ls" command without any further
options.

Option 1: ls
Display the hidden files and directories
Option 2: ls -a
Use the -a option of the ls command to show hidden files and directories in the current directory.The
files that start with the dot are hidden (.). The current directory (.) as well as the parent directory (..) are
displayed by "ls -a".
Option 3: ls –l Display complete information about the files
The "ls -l" option displays the contents of the current directory in a long listing format, one per line. The
line begin with the file or directory permission, owner and group name, file size, created/modified date
and time, file/folder name as some of the attributes.
Option 4: ls –i Display File Index Number
For internal purposes, you may need to know the index number of a file. To display the index number,
use the "ls -i" option. You can remove files with special characters in their names by using the index
number.

44
FOSS

Option 5: ls -t View last edited file


The most recently modified file is displayed first as the file is sorted by modification time. Use the ls
and head commands together to access the most recently edited file in the current directory.

grep command
The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that
pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for
global search for regular expression and print out).

Syntax: grep [options] pattern [files]


Option 1. Case insensitive search : The -i option enables to search for a string case insensitively in the
given file. It matches the words like “UNIX”, “Unix”, “unix”.
$grep -i "UNix" geekfile.txt
Output: unix is great os. unix was developed in Bell labs.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

Option 2. Displaying the count of number of matches : We can find the number of lines that matches
the given string/pattern
$grep -c "unix" geekfile.txt
Output: 2

Option 3. Display the file names that matches the pattern : We can just display the files that contains
the given string/pattern.
$grep -l "unix" *
or
$grep -l "unix" f1.txt f2.txt f3.xt f4.txt
Output: geekfile.txt

Option 4. Checking for the whole words in a file : By default, grep matches the given string/pattern even
if it is found as a substring in a file. The -w option to grep makes it match only the whole words.
$ grep -w "unix" geekfile.txt
Output:
unix is great os. unix was developed in Bell labs.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

45
FOSS

Option 5. Displaying only the matched pattern : By default, grep displays the entire line which has the
matched string. We can make the grep to display only the matched string by using the -o option.
$ grep -o "unix" geekfile.txt
Output:
unix
unix
unix
unix
unix
unix

CHMOD COMMAND
• In Unix operating systems, the chmod command is used to change the access mode of a file. The
name is an abbreviation of change mode.
• Which states that every file and directory has a set of permissions that control the permissions like
who can read, write or execute the file. In this the permissions have three categories: read, write,
and execute simultaneously represented by `r`, `w` and `x`.
These letters combine together to form a specific permission for a group of users.
• The `chmod` command is used to modify this permission so that it can grant or restrict access to
directories and files. Let’s have a look at the syntax and options for the `chmod` command in Linux
Operating System.

Syntax: chmod <options> <permissions> <file name>


The following operators can be used with the symbolic mode:

Operators Definition

`+` Add permissions

`-` Remove permissions

`=` Set the permissions to the specified values

The following letters that can be used in symbolic mode:

46
FOSS

Letters Definition

`r` Read permission

`w` Write permission

`x` Execute permission

The following Reference that are used:

Reference Class

u Owner

g Group

o Others

a All (owner,groups,others)

Example : chmod 674 [file_name]


Here.
• 6 represent permission of file Owner which are (rw).
• 7 represent permission of Group which are (rwx).
• 4 represent permission of Other which is (r).

chmod u=rw,go=rw Demo.txt


To set the permission of a file, execute a permission statement with the chmod command. For example,
we want to set the read and write permission for all users and groups of file 'Demo.txt.' We have to pass
the "u=rw,go=rw Demo.txt" permission statement with chmod command.

DIFF COMMAND
diff stands for difference. This command is used to display the differences in the files by comparing the
files line by line. Unlike its fellow members, cmp and comm, it tells us which lines in one file have is to
be changed to make the two files identical.
• Syntax : diff [options] File1 File2

47
FOSS

$ ls
a.txt b.txt

$ cat a.txt
Gujarat
Uttar Pradesh
Kolkata
Bihar
Jammu and Kashmir

$ cat b.txt
Tamil Nadu
Gujarat
Andhra Pradesh
Bihar
Uttar pradesh
Now, applying diff command without any option we get the following output:
$ diff a.txt b.txt
0a1
> Tamil Nadu
2,3c3
< Uttar Pradesh
Andhra Pradesh
5c5
Uttar pradesh
0a1 which means after lines 0(at the very beginning of file) you have to add Tamil Nadu to match
the second file line number 1. It then tells us what those lines are in each file preceded by the symbol:
• Lines preceded by a < are lines from the first file.
• Lines preceded by > are lines from the second file.
• Next line contains 2,3c3 which means from line 2 to line 3 in the first file needs to be changed to
match line number 3 in the second file. It then tells us those lines with the above symbols.
• The three dashes (“—“) merely separate the lines of file 1 and file 2.

48
FOSS

MOUNTING THE FILE SYSTEM


• All files in a Linux file system are arranged in form of a big tree rooted at ‘/‘.
• These files can be spread out on various devices based on your partition table, initially your parent
directory is mounted(i.e attached) to this tree at ‘/‘, others can be mounted manually using GUI
interface(if available) or using mount command.
• mount command is used to mount the filesystem found on a device to big tree structure (Linux
filesystem) rooted at ‘/‘. Conversely, another command umount can be used to detach these devices
from the Tree.
• Syntax: mount -t type device dir
• These commands tells the Kernel to attach the filesystem found at device to the dir.

COMMAND LINE PROCESSING


• The Linux command line is a text interface to your computer. Often referred to as the shell,
terminal, console, prompt or various other names, it can give the appearance of being complex
and confusing to use. Yet the ability to copy and paste commands from a website
• The shell is the command interpreter on the Linux systems. It the program that interacts with the
users in the terminal emulation window. Shell commands are instructions that instruct the system
to do some action.
• Each line that the shell reads from the standard input or a script is called a pipeline; it contains
one or more commands separated by zero or more pipe characters (|). For each pipeline it reads,
the shell breaks it up into commands, sets up the I/O for the pipeline,
• Steps in command line processing is shown in the figure
1) Splits the command into tokens that are separated by the fixed set of metacharacters: SPACE,
TAB, NEWLINE, ;, (, ), <, >, |, and &. Types of tokens include words, keywords, I/O
redirectors, and semicolons.
2) Checks the first token of each command to see if it is a keyword with no quotes or backslashes.
If it's an opening keyword, such as if and other control-structure openers, function, {, or (, then
the command is actually a compound command. The shell sets things up internally for the
compound command, reads the next command, and starts the process again. If the keyword isn't
a compound command opener (e.g., is a control-structure "middle" like then, else, or do, an
"end" like fi or done, or a logical operator), the shell signals a syntax error.
3) Checks the first word of each command against the list of aliases. If a match is found, it
substitutes the alias's definition and goes back to Step 1; otherwise, it goes on to Step 4. This
scheme allows recursive aliases (see Chapter 3). It also allows aliases for keywords to be defined,
e.g., alias aslongas=while or alias procedure=function.

49
FOSS

4) Performs brace expansion. For example, a{b,c} becomes ab ac.


5) Substitutes the user's home directory ($HOME) for tilde if it is at the beginning of a word.
Substitutes user's home directory for ~user.[7]
[7]
Two obscure variations on this: the shell substitutes the current directory ($PWD) for ~+ and the
previous directory ($OLDPWD) for ~-. In bash 2.0 there are two more: ~N+ and ~N-. These are
replaced by the corresponding element in the directory stack as given by the dirs command.
6) Performs parameter (variable) substitution for any expression that starts with a dollar sign ($).
7) Does command substitution for any expression of the form $(string).
8) Evaluates arithmetic expressions of the form $((string)).
9) Takes the parts of the line that resulted from parameter, command, and arithmetic substitution
and splits them into words again. This time it uses the characters in $IFS as delimiters instead of
the set of metacharacters in Step 1.
10) Performs pathname expansion, a.k.a. wildcard expansion, for any occurrences of *, ?, and [/] pairs.
11) Uses the first word as a command by looking up its source according to the rest of the list in Chapter
4, i.e., as a function command, then as a built-in, then as a file in any of the directories in $PATH.
12) Runs the command after setting up I/O redirection and other such things.

50
FOSS

TYPES OF TEXT EDITORS IN LINUX


Linux text editors can be used for editing text files, writing codes, updating user instruction files, and
more.
A Linux system supports multiple text editors. There are two types of text editors in Linux:
• Command-line text editors such as Vi, nano, pico, and more.
• GUI text editors such as gedit (for Gnome), Kwrite, and more.
A text editor plays an important role while coding. So, it is important to select the best text editor. A
text editor should not only be simple but also functional and should be good to work with. A text editor
with IDE features is considered as a good text editor.

THE FOLLOWING ARE SOME IMPORTANT TEXT EDITORS IN LINUX


1.VI/VIM EDITOR
Vim editor is one of the most used and powerful command-line based editor of the Linux system. By
default, it is supported by most Linux distros. It has enhanced functionalities of the old Unix Vi editor.
It is a user-friendly editor and provides the same environment for all the Linux distros. It is also termed
as programmer's editor because most programmers prefer Vi editor. it has two modes: command mode
and insert mode.

2. NANO EDITOR
Nano is a straight forward editor. It is designed for both beginners and advanced users. It has many
customization features.
Some advanced features of a nano text editor are as following:
o It has highly customizable key bindings
o It supports syntax highlighting
o It has undo and redo options
o It provides full line display on the standard output
o It has pager support to read from standard input

3. GEDIT EDITOR
Gedit editor is the default editor for the GNOME desktop environment. When we open a file, it will open
with the Gedit editor. It provides straightforward functionalities like any basic text editor. It is a
lightweight editor with a straight forward user interface. It was publicly released in the year 2000 with a
GNOME desktop environment. It is developed using the C programming language and supports all font
family.
Some key features of the gedit text editor are as following:

51
FOSS

o It provides syntax highlighting.


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

4. SUBLIME TEXT
The sublime text editor is also one of the most popular IDE-based text editors. It is used as a development
environment tool more than a text editor. It has several features to support many programming and mark-
up languages.
Some key features of a sublime text editor are as following:
o It has an excellent Command Palette.
o It is a python-based plugin API.
o It supports parallel editing of code.
o It provides project-specific preferences.

5. VSCODE EDITOR
VSCode editor is a modern and widely used text editor. It is built by Microsoft and has support for Linux,
Mac and Windows OS. It facilitates with many powerful features to support many programming
languages and markup language.
Some key features of VSCode editor are as following:
o It has full support for debugging with an interactive console, breakpoints, call stacks and more.
o It has built-in support for Git and Git commands.
o It facilitates with IntelliSense.
o It provides many customization options.
o It has massive support for languages.
o It supports togglable layouts.
o It provides a built-in terminal.

INTRODUCTION TO VI EDITOR
The default editor that comes with the UNIX operating system is called vi (visual editor). Using vi editor,
we can edit an existing file or create a new file from scratch. we can also use this editor to just read a
text file. The advanced version of the vi editor is the vim editor.
The vi editor has two modes:
Command Mode: In command mode, actions are taken on the file. The vi editor starts in command
mode. Here, the typed words will act as commands in vi editor. To pass a command, you need to be in
command mode.

52
FOSS

Insert Mode: In insert mode, entered text will be inserted into the file. The Esc key will take you to the
command mode from insert mode.
By default, the vi editor starts in command mode. To enter text, you have to be in insert mode, just type
'i' and you'll be in insert mode. Although, after typing i nothing will appear on the screen but you'll be
in insert mode. Now you can type anything.
To exit from insert mode press Esc key, you'll be directed to command mode. Modes of Vi Editors.

1.COMMAND MODE
This is what you'll see when you'll press enter after the above command. If you'll start typing, nothing
will appear as you are in command mode. By default vi opens in command mode.

Look at the above snapshot, it is blank as it is a new file. To start typing, you have to move to the insert
mode. At the end of the terminal window, directory name and file name are displayed.

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

From above snapshot, after pressing i we have entered into insert mode. Now we can write anything. To
move to the next line press enter.
Once you have done with your typing, press esc key to return to the command mode.

53
FOSS

COMMANDS IN VI EDITOR
1. OPEN VI EDITOR FILE
To open vi editors, we just need to type the command as:
vi [file_name]
Here, [file_name] = “macas” this is the file name we want to create or to open the pre-existing file.
Creating a new file with `file_name` = macas
vi macas.txt

2.SAVE A FILE IN VI EDITOR


There are 3 ways to save a file in the vi/vim editor which are mentioned below:
1. :w – Save changes but do not exit.
2. :wa: – Save all open multiple files without quitting.
3. :w filename – Save the file with a different name and continue editing the current file.
Example:
Step 1: Open a file or create using the vi editor
Step 2: Enter in command mode by pressing Esc if you are in insert mode
Step 3: Use any of the above commands (w, wa, w [filename]) to save the file, in the below
screenshot we have used :w [filename] to save the file using a new name in
the newFile.txt file.

3.DELETE A FILE IN VI EDITOR


You can delete or remove characters in different ways. r key is used to replace one single character. The
r key will bring you in insert mode for just one key press and then you'll be directed to command mode.
X :-The command x is used to delete current character.
dd:-The command dd deletes current line completely.
D:-The command D is used to delete from current character to the end of the line.
dG:-The command dG is used to delete from current line to the end line of the file.

4.QUIT A FILE IN VI EDITOR


There are four ways to quit the editor:
1. :q – To quit the editor
2. :q! – To force quit useful when changes are made to a file but the user doesn’t want to save them
3. :qa! – Quit all open files without saving changes (force-quit)
4. ZQ (Shift + ZQ) – Quit without saving changes
Example:

54
FOSS

Step 1: Open a file or create using the vi editor


Step 2: Enter in command mode by pressing Esc if you are in insert mode
Step 3: Use any of the above commands (q, q!, qa or ZQ) to quit the editor in the below screenshot
we have used:q to quit the editor

*******END OF MODULE 3*******

55

You might also like