0% found this document useful (0 votes)
20 views45 pages

Unix Assigentment

UNIX is a multi-user, multitasking operating system developed in the 1970s. It is known for its stability, security, and efficiency. The mkdir command creates directories, while rmdir removes empty directories and pwd prints the current working directory. The ls command lists files and directories in a directory.

Uploaded by

fakemailb4k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views45 pages

Unix Assigentment

UNIX is a multi-user, multitasking operating system developed in the 1970s. It is known for its stability, security, and efficiency. The mkdir command creates directories, while rmdir removes empty directories and pwd prints the current working directory. The ls command lists files and directories in a directory.

Uploaded by

fakemailb4k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

What is Unix

UNIX is a multi-user, multitasking operating system that was developed in the 1970s at Bell Labs.
It is a popular operating system for servers, and is also used on many other types of computers,
including desktop and laptop computers.

UNIX is known for its stability, security, and efficiency, and it has a large number of features that
make it well-suited for use in a wide variety of applications. It is often used in academic and
research settings, as well as in businesses and other organizations.

One of the key features of UNIX is its use of a command-line interface, which allows users to enter
commands to perform various tasks. UNIX also includes a number of utilities and tools that can be
used to perform a wide range of tasks, including text editing, file management, and system
administration.

In addition to its popularity as a standalone operating system, UNIX has also had a significant
influence on other operating systems, including Linux and macOS. Many of the concepts and
technologies used in UNIX have been adopted by other operating systems, making it an important
and influential operating system in the history of computing.

MKDIR
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. It is important to note that the user executing this command must
have enough permissions to create a directory in the parent directory, or he/she may receive a
‘permission denied’ error.

Syntax:

mkdir [options...] [directories ...]

Options:

 –version: It displays the version number, some information regarding the license and
exits.

Syntax:

mkdir --version

 Output:

mkdir (GNU coreutils) 9.1


Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by David MacKenzie.

1
 –help: It displays the help related information and exits.
Syntax:

mkdir --help

 Output:

Usage: mkdir [OPTION]... DIRECTORY...


Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask
-p, --parents no error if existing, make parent directories as needed,
with their file modes unaffected by any -m option.
-v, --verbose print a message for each created directory
-Z set SELinux security context of each created directory
to the default type
--context[=CTX] like -Z, or if CTX is specified then set the SELinux
or SMACK security context to CTX
--help display this help and exit
--version output version information and exit

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>


Full documentation <https://www.gnu.org/software/coreutils/mkdir>
or available locally via: info '(coreutils) mkdir invocation'

 -p: A flag which enables the command to create parent directories as necessary. If the
directories exist, no error is specified.
Syntax:
mkdir -p [directories]
 Suppose you execute the following command –
mkdir -p first/second/third
 If the first and second directories do not exist, due to the -p option, mkdir will create these
directories for us. If we do not specify the -p option, and request the creation of directories,
where parent directory doesn’t exist, we will get the following output –

mkdir: cannot create directory ‘first/second/third’: No such file or directory

 If we specify the -p option, the directories will be created, and no error will be reported.
Following is the output of one such execution. We’ve also provided the -v option, so that we
can see it in action.
Output:
mkdir: created directory 'first'
mkdir: created directory 'first/second'
mkdir: created directory 'first/second/third'

 -m: This option is used to set the file modes, i.e. permissions, etc. for the created
directories. The syntax of the mode is the same as the chmod command.
Syntax:
mkdir -m a=rwx [directories]
 The above syntax specifies that the directories created give access to all the users to read
from, write to and execute the contents of the created directories. You can use ‘a=r’ to only
allow all the users to read from the directories and so on.
2
RMDIR
rmdir command is used remove empty directories from the filesystem in Linux. The rmdir
command removes each and every directory specified in the command line only if these
directories are empty. So if the specified directory has some directories or files in it then this
cannot be removed by rmdir command.
Syntax:
rmdir [-p] [-v | –verbose] [–ignore-fail-on-non-empty] directories …
Options:

–help: It will print the general syntax of the command along with the various options
that can be used with the rmdir command as well as give a brief description about each
option.
Output:
Usage: rmdir [OPTION]... DIRECTORY...
Remove the DIRECTORY(ies), if they are empty.

--ignore-fail-on-non-empty
ignore each failure that is solely because a directory
is non-empty

-p, --parents remove DIRECTORY and its ancestors; e.g., 'rmdir -p a/b/c'
is similar to 'rmdir a/b/c a/b a'

-v, --verbose output a diagnostic for every directory processed


--help display this help and exit
--version output version information and exit

GNU coreutils online help: <https://www.gnu.org/software/coreutils/>


Full documentation <https://www.gnu.org/software/coreutils/rmdir>
or available locally via: info '(coreutils) rmdir invocation'

 rmdir -p: In this option each of the directory argument is treated as a pathname of which all
components will be removed, if they are already empty, starting from the last component.
 rmdir -v, –verbose: This option displays verbose information for every directory being
processed.
 rmdir –ignore-fail-on-non-empty: This option do not report a failure which occurs solely
because a directory is non-empty. Normally, when rmdir is being instructed to remove a
non-empty directory, it simply reports an error. This option consists of all those error
messages.
 rmdir –version: This option is used to display the version information and exit.
Output:
rmdir (GNU coreutils) 9.1
Copyright (C) 2022 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by David MacKenzie.

Example 1: This will first remove the child directory and then remove the parent directory.
rmdir -p mydir/mydir1

3
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

PWD
The pwd command is a command-line utility that is used to print the current working directory.
It stands for "print working directory."

Here is the syntax for the pwd command, along with some of the options that are available:

pwd [options]

Some of the options that can be used with the pwd command include:
 -L: Print the logical current working directory, following symbolic links. This is the default
behavior.
 -P: Print the physical current working directory, without following symbolic links.

Here is an example of using the pwd command to print the current working directory:

pwd

This will print the full path of the current working directory.

Here is an example of using the pwd command with the -P option to print the physical current
working directory:

pwd -P

This will print the full path of the current working directory, without following any symbolic links.
Note that the pwd command does not take any arguments, so you cannot specify a specific
directory to print the path for. It will always print the path of the current working directory.

LS
The ls command is a command-line utility for listing the files and directories in a directory. It is
a standard Unix command, available on virtually all Unix-like systems, including Linux, MacOS,
and BSD.

Here are some common options for the ls command:

 -l: Display the files and directories in a long format, showing detailed information such as
permissions, owner, group, size, and modification time.
Output:
total 40
drwxr-xr-x 28 root root 4096 Dec 16 13:02 chrome
drwxr-xr-x 2 root root 4096 Dec 11 11:14 Desktop
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Documents
drwxr-xr-x 8 root root 4096 Dec 15 12:59 Downloads
drwxr-xr-x 3 root root 4096 Dec 17 10:51 first
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Music
4
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Pictures
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Public
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Templates
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Videos

 -a: Include hidden files and directories in the listing. These are files and directories that are
typically hidden from view because their names begin with a dot (.).

Output:
-rw------- 1 root root 95 Dec 15 12:47 .bash_history
-rw-r--r-- 1 root root 220 Oct 25 08:57 .bash_logout
-rw-r--r-- 1 root root 5550 Dec 17 10:45 .bashrc
-rw-r--r-- 1 root root 571 Aug 8 06:04 .bashrc.original
drwxr-xr-x 28 root root 4096 Dec 16 13:02 chrome
drwx------ 20 root root 4096 Dec 4 11:56 .config
drwx------ 3 root root 4096 Oct 25 06:12 .dbus
drwxr-xr-x 2 root root 4096 Dec 11 11:14 Desktop
-rw-r--r-- 1 root root 35 Oct 25 08:57 .dmrc
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Documents
drwxr-xr-x 8 root root 4096 Dec 15 12:59 Downloads
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Music
drwxr-xr-x 4 root root 4096 Nov 28 07:53 .npm
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Pictures
drwx------ 3 root root 4096 Dec 2 14:19 .pki
-rw-r--r-- 1 root root 161 Jul 26 09:31 .profile
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Public
drwxr-xr-x 3 root root 4096 Nov 29 14:02 .set
drwx------ 2 root root 4096 Dec 2 13:15 .ssh
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Templates
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Videos
drwxr-xr-x 3 root root 4096 Dec 2 14:13 .wdm
-rw-r--r-- 1 root root 250 Nov 29 13:35 .wget-hsts
-rw------- 1 root root 38055 Dec 17 10:48 .zsh_history
-rw-r--r-- 1 root root 10876 Dec 17 10:49 .zshrc
 -h: Display file sizes in "human-readable" format, meaning that the sizes are displayed in a
more easily readable format, such as in kilobytes (KB), megabytes (MB), or gigabytes (GB).
 -R: Recursively list the files and directories in a directory and all of its subdirectories.
 -t: Sort the listing by modification time, with the most recently modified files and directories
appearing first.
Output:
total 40
drwxr-xr-x 3 root root 4096 Dec 17 10:51 first
drwxr-xr-x 28 root root 4096 Dec 16 13:02 chrome
drwxr-xr-x 8 root root 4096 Dec 15 12:59 Downloads
drwxr-xr-x 2 root root 4096 Dec 11 11:14 Desktop
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Documents
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Music
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Pictures
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Public
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Templates
drwxr-xr-x 2 root root 4096 Oct 25 08:57 Videos

5
TOUCH
The touch command is a standard command used in UNIX/Linux operating system which is
used to create, change and modify timestamps of a file. Basically, there are two different
commands to create a file in the Linux system which is 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
touch command is empty. This command can be used when the user doesn’t have data to
store at the time of file creation.

Using touch Command

Initially, we are in home directory and this can be checked using the pwd command. Checking
the existing files using command ls and then long listing command(ll) is used to gather more
details about existing files. As you can see in the below figure there is no existing files.

Touch command Syntax to create a new file: You can create a single file at a time using
touch command.

Syntax:
touch file_name

The file which is created can be viewed by ls command and to get more details about the file
you can use long listing command ll or ls -l command . Here file with name ‘File1‘ is created
using touch command.

Touch command to create multiple files: Touch command can be used to create the
multiple numbers of files at the same time. These files would be empty while creation.

Syntax:
touch File1_name File2_name File3_name

Multiple files with name Doc1, Doc2, Doc3 are created at the same time using touch command
here.

6
touch Command Options
Like all other command Touch command have various options. These options are very useful
for various purpose.

touch -a: This command is used to change access time only. To change or update the last
access or modification times of a file touch -a command is used.

Syntax:
touch -a fileName
Here touch -a command changes access time of the file named Doc1.

touch -c : This command is used to check whether a file is created or not. If not created then
don’t create it. This command avoids creating files.
Syntax:
touch -c fileName

touch -c-d : This is used to update access and modification time.


Syntax:

7
touch -c-d fileName

touch -m : This is used to change the modification time only. It only updates last modification time.
Syntax:
touch -m fileName

CAT
Cat(concatenate) command is very frequently used in Linux. It reads data from the file and gives
their content as output. It helps us to create, view, concatenate files. So let us see some frequently
used cat commands.
8
1) To view a single file
Command:

$cat filename
Output

It will show content of given filename


2) To view multiple files
Command:
$cat file1 file2
Output

This will show the content of file1 and file2.


3) To view contents of a file preceding with line numbers.
Command:

$cat -n filename
Output

It will show content with line number


example:-cat-n geeks.txt
1)This is geeks
2)A unique array
4) Create a file
Command:

$ cat > newfile


Output

Will create a file named newfile


5) Copy the contents of one file to another file.
Command:

$cat [filename-whose-contents-is-to-be-copied] > [destination-filename]


Output

The content will be copied in destination file


6) Cat command can suppress repeated empty lines in output
Command:

$cat -s geeks.txt
Output
Will suppress repeated empty lines in output
7) 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
8) Cat command can display content in reverse order using tac command.
Command:

9
$tac filename
Output

Will display content in reverse order


9) Cat command can highlight the end of line.

Command:
$cat -E "filename"

Output
Will highlight the end of line

10) If you want to use the -v, -E and -T option together, then instead of writing -vET in the
command, you can just use the -A command line option.

Command :
$cat -A "filename"

11) Cat command to open dashed files.

Command:
$cat -- "-dashfile"

Output
Will display the content of –dashfile

12) 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, which could fit in terminal and will ask to show more.

13) Cat command to merge the contents of multiple files.

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

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

14) Cat command to display the content of all text files in the folder.

Command:
$cat *.txt

Output

Will show the content of all text files present in the folder.

15) Cat command to write in an already existing file.

10
Command :
$cat >> geeks.txt

The newly added text.

Output
Will append the text "The newly added text." to the end of the file.
CHMOD
In Unix-like operating systems, the chmod command is used to change the access mode of a file.
The name is an abbreviation of change mode.
Syntax :
chmod [reference][operator][mode] file...
The references are used to distinguish the users to whom the permissions apply i.e. they are list of
letters that specifies whom to give permissions. The references are represented by one or more of
the following letters:

Reference Class Description


u owner file's owner

g group users who are members of


the file's group

o others users who are neither the


file's owner nor members of
the file's group

a all All three of the above, same as ugo

The operator is used to specify how the modes of a file should be adjusted. The following
operators are accepted:

Operator Description
+ Adds the specified modes to the
specified classes

- Removes the specified modes from


the specified classes

= The modes specified are to be made


the exact modes for the specified
classes

Note : Putting blank space(s) around operator would make the command fail.
The modes indicate which permissions are to be granted or removed from the specified classes.
There are three basic modes which correspond to the basic permissions:

r : Permission to read the file.


w: Permission to write (or delete) the file.
x: Permission to execute the file, or, in
the case of a directory, search it.

11
Types of permissions which we will be changing using chmod command :
In linux terminal, to see all the permissions to different files, type ls -l command which lists the files
in the working directory in long format.

Let us take a look at above figure. To make things easy to understand some columns and rows
are eliminated and extra spaces are added to the permissions column to make it easier to read as
shown below:
- rw- rw- r-- mik mik assgn1_client.c
- rw- rw- r-- mik mik assgn1_server.c
d rwx rwx r-x mik mik EXAM
- rw- rw- r-- mik mik raw.c
- rwx r-x r-x mik mik header.sh
... so on...

 The very first column represents the type of the file i.e. is it a normal file or a
directory where d represents a directory and – represents a normal file.
 The first set three letters after the file type tell what the Owner of the file, have permissions
to do. For example: In assgn1_client.c, has owner’s permission as rw-, which means the
owner mik can only read(r) and write(w) the file but cannot execute(x).
 Note: The 3rd and 4th columns represents the name of the owner of the file and the group
to which the owner belongs respectively.
 The next three letters after the user’s permission are the group’s permissions.
For example: header.sh has group permissions as r-x, which means Other people in the
mik group can not write(w) the header.sh script but can only read(r) or execute(x) it.
 Note that when a directory has the x set, this takes the special meaning of “permitted to
search this directory”.
 The last three letters in the permissions column tell us what the “others” may do. The
general practice is to protect the files from external access so that others can’t write any
files or directories. They may read(r) or execute(x) it. For example: The assgn1_client.c has
others permission as r- – which means it can only be read by other(external) access but
cannot be written or executed by them.
Now, let us see how chmod command can be used to change the access mode of a file.
Example 1 :
Let’s change the assgn1_client.c permission so that the owner cannot write(w) in the file but can
only read it.

BEFORE: -rw-rw-r-- mik mik assgn1_client.c

COMMAND: chmod u=r assgn1_client.c

AFTER: -r--rw-r-- mik mik assgn1_client.c

CHOWN
Different users in the operating system have ownership and permission to ensure that the files are
secure and put restrictions on who can modify the contents of the files. In Linux there are different
users who use the system:
 Each user has some properties associated with them, such as a user ID and a home
directory. We can add users into a group to make the process of managing users easier.
 A group can have zero or more users. A specified user can be associated with a “default
group”. It can also be a member of other groups on the system as well.
Ownership and Permissions: To protect and secure files and directory in Linux we use
permissions to control what a user can do with a file or directory. Linux uses three types of
permissions:
12
 Read: This permission allows the user to read files and in directories, it lets the user read
directories and subdirectories stores in it.
 Write: This permission allows a user to modify and delete a file. Also it allows a user to
modify its contents (create, delete and rename files in it) for the directories. Unless the
execute permission is not given to directories changes does do affect them.
 Execute: This permission on a file allows it to get executed. For example, if we have a file
named php.sh so unless we don’t give it execute permission it won’t run.
Types of file Permissions:
 User: These type of file permission affect the owner of the file.
 Group: These type of file permission affect the group which owns the file. Instead of the
group permissions, the user permissions will apply if the owner user is in this group.
 Other: These type of file permission affect all other users on the system.
Note: To view the permissions we use:
ls -l

chown command is used to change the file Owner or group. Whenever you want to change
ownership you can use chown command.

Syntax:

chown [OPTION]… [OWNER][:[GROUP]] FILE…


chown [OPTION]… –reference=RFILE FILE…

Example: To change owner of the file:

chown owner_name file_name

In our case we have files as follows:

Now if I use file1.txt in my case, to change ownership I will use the following syntax:
chown master file1.txt

13
where the master is another user in the system. Assume that if you are user named user1 and you
want to change ownership to root (where your current directory is user1). use “sudo” before
syntax.
sudo chown root file1.txt
Options:
 -c: Reports when a file change is made.
Example:
chown -c master file1.txt

 -v: It is used to show the verbose information for every file processed.
Example:
chown -v master file1.txt

 -f: It suppresses most of the error messages. When you are not permitted to change group
permissions and shows error, this option forcefully/silently changes the ownership.
Examples:
 To Change group ownership In our case I am using group1 as a group in the system. To
change ownership we will use
chown :group1 file1.txt

You can see that the group permissions changed to group1 from root, if you use -v option it will
report that. We just need to add a “:” to change group.

14
 To change the owner as well as group: Again taking master as user and group1 as a
group in the system
chown master:group1 greek1
Here, greek1 is a file.

 To change the owner from particular ownership only: Suppose we want to change
ownership from master to root where current owner must be master only.
chown --from=master root greek1

 To change group from a particular group:


chown --from=:group1 root greek1

Here, the group of greek1 is changed to root.


 To copy ownership of one file to another:
chown --reference=greek1 greek2

15
 To change ownership of multiple files:
chown master:group greek2 greek3

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.

Syntax:
vi filename

Input:

Output:

Modes of Operation in vi editor: There are three modes of operation in vi:

 Command Mode: When vi starts up, it is in Command Mode. This mode is where vi
interprets any characters we type as commands and thus does not display them in the
window. This mode allows us to move through a file, and to delete, copy, or paste a piece
16
of text. To enter into Command Mode from any other mode, it requires pressing
the [Esc] key. If we press [Esc] when we are already in Command Mode, then vi will beep
or flash the screen.

 Insert mode: This mode enables you to insert text into the file. Everything that’s typed in
this mode is interpreted as input and finally, it is put in the file. The vi always starts in
command mode. To enter text, you must be in insert mode. To come in insert mode you
simply type i. To get out of insert mode, press the Esc key, which will put you back into
command mode.

 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


There are following way you can 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.

17
 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: Here is the list of important 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 Past 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.

The formal syntax for searching is:


:s/string

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

:s/geeksforgeeks

Input:

Output: finding the first match for “geeksforgeeks” in text will then be highlighted.

SED
SED command in UNIX stands for stream editor and it can perform lots of functions on file like
searching, find and replace, insertion or deletion. Though most common use of SED command in
UNIX is for substitution or for find and replace. By using SED you can edit files even without
opening them, which is much quicker way to find and replace something in file, than first opening
that file in VI Editor and then changing it.
 SED is a powerful text stream editor. Can do insertion, deletion, search and
replace(substitution).
 SED command in unix supports regular expression which allows it perform complex pattern
matching.

Syntax:
sed OPTIONS... [SCRIPT] [INPUTFILE...]

Example:
Consider the below text file as an input.

$cat > geekfile.txt


unix is great os. unix is opensource. unix is free os.
learn operating system.

19
unix linux which one you choose.
unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

Sample Commands
1. Replacing or substituting string : Sed command is mostly used to replace the text in a
file. The below simple sed command replaces the word “unix” with “linux” in the file.
2. $sed 's/unix/linux/' geekfile.txt

Output :

linux is great os. unix is opensource. unix is free os.


learn operating system.
linux linux which one you choose.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search
pattern and the “linux” is the replacement string.
By default, the sed command replaces the first occurrence of the pattern in each line and it won’t
replace the second, third…occurrence in the line.

Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first,
second occurrence of a pattern in a line. The below command replaces the second occurrence of
the word “unix” with “linux” in a line.
$sed 's/unix/linux/2' geekfile.txt

Output:
unix is great os. linux is opensource. unix is free os.
learn operating system.
unix linux which one you choose.
unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.

Replacing all the occurrence of the pattern in a line : The substitute flag /g (global
replacement) specifies the sed command to replace all the occurrences of the string in the line.

$sed 's/unix/linux/g' geekfile.txt

Output :
linux is great os. linux is opensource. linux is free os.
learn operating system.
linux linux which one you choose.
linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

Replacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc
and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed
command replaces the third, fourth, fifth… “unix” word with “linux” word in a line.

$sed 's/unix/linux/3g' geekfile.txt

Output:
unix is great os. unix is opensource. linux is free os.
learn operating system.
unix linux which one you choose.
unix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful.

20
Parenthesize first character of each word : This sed example prints the first character of every
word in parenthesis.

$ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g'

Output:
(W)elcome (T)o (T)he (G)eek (S)tuff

Replacing string on a specific line number : You can restrict the sed command to replace the
string on a specific line number. An example is

$sed '3 s/unix/linux/' geekfile.txt

Output:
unix is great os. unix is opensource. unix is free os.
learn operating system.
linux linux which one you choose.
unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

The above sed command replaces the string only on the third line.

Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the
terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line
only once.

$sed 's/unix/linux/p' geekfile.txt

Output:
linux is great os. unix is opensource. unix is free os.
linux is great os. unix is opensource. unix is free os.
learn operating system.
linux linux which one you choose.
linux linux which one you choose.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

Printing only the replaced lines : Use the -n option along with the /p print flag to display only the
replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and
prints the replaced lines only one time.

$sed -n 's/unix/linux/p' geekfile.txt

Output:
linux is great os. unix is opensource. unix is free os.
linux linux which one you choose.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

If you use -n alone without /p, then the sed does not print anything.

Replacing string on a range of lines : You can specify a range of line numbers to the sed
command for replacing a string.

21
$sed '1,3 s/unix/linux/' geekfile.txt

Output:
linux is great os. unix is opensource. unix is free os.
learn operating system.
linux linux which one you choose.
unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
Here the sed command replaces the lines with range from 1 to 3. Another example is

$sed '2,$ s/unix/linux/' geekfile.txt

Output:
unix is great os. unix is opensource. unix is free os.
learn operating system.
linux linux which one you choose.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful
Here $ indicates the last line in the file. So the sed command replaces the text from second line to
last line in the file.

Deleting lines from a particular file : SED command can also be used for deleting lines from a
particular file. SED command is used for performing deletion operation without even opening the
file

Examples:
1. To Delete a particular line say n in this example
Syntax:
$ sed 'nd' filename.txt
Example:
$ sed '5d' filename.txt

2. To Delete a last line


Syntax:
$ sed '$d' filename.txt

3. To Delete line from range x to y


Syntax:
$ sed 'x,yd' filename.txt

Example:
$ sed '3,6d' filename.txt

4. To Delete from nth to last line


Syntax:
$ sed 'nth,$d' filename.txt

Example:
$ sed '12,$d' filename.txt

5. To Delete pattern matching line


Syntax:
$ sed '/pattern/d' filename.txt

Example:

22
$ sed '/abc/d' filename.txt

MORE
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). The more command also allows the user do
scroll up and down through the page. The syntax along with options and command is as follows.
Another application of more is to use it with some other command after a pipe. When the output is
large, we can use more command to see output one by one.
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.

While viewing the text file use these controls:

Enter key: to scroll down line by line.


Space bar: To go to the next page.
b key: To go to back one page.

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.
Example:

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

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

+num : This option displays the text after the specified number of lines of the document.
Example:

more +30 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

GREP
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]

Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
24
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.

-A n : Prints searched line and nlines after the result.


-B n : Prints searched line and n line before the result.
-C n : Prints searched line and n lines after before the result.

Consider the below file as an input.

$cat > geekfile.txt

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


learn operating system.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

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.

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

25
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.
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
6. Show line number while displaying the output using grep -n : To show the line number of
file with the line matched.

$ grep -n "unix" geekfile.txt


Output:

1:unix is great os. unix is free os.


4:uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
7. Inverting the pattern match : You can display the lines that are not matched with the specified
search string pattern using the -v option.

$ grep -v "unix" geekfile.txt


Output:

learn operating system.


Unix linux which one you choose.
8. Matching the lines that start with a string : The ^ regular expression pattern specifies the
start of a line. This can be used in grep to match the lines which start with the given string or
pattern.

$ grep "^unix" geekfile.txt


Output:

unix is great os. unix is free os.


9. Matching the lines that end with a string : The $ regular expression pattern specifies the end
of a line. This can be used in grep to match the lines which end with the given string or pattern.

$ grep "os$" geekfile.txt


10.Specifies expression with -e option. Can use multiple times :

$grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" geekfile.txt


11. -f file option Takes patterns from file, one per line.

26
$cat pattern.txt

Agarwal
Aggarwal
Agrawal

$grep –f pattern.txt geekfile.txt


12. Print n specific lines from a file: -A prints the searched line and n lines after the result, -B
prints the searched line and n lines before the result, and -C prints the searched line and n lines
after and before the result.
Syntax:
$grep -A[NumberOfLines(n)] [search] [file]

$grep -B[NumberOfLines(n)] [search] [file]

$grep -C[NumberOfLines(n)] [search] [file]


Example:
$grep -A1 learn geekfile.txt
Output:
learn operating system.
Unix linux which one you choose.
--
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

(Prints the searched line along with the next n lines (here n = 1 (A1).)
(Will print each and every occurrence of the found line, separating each output by --)
(Output pattern remains the same for -B and -C respectively)
Unix linux which one you choose.
--
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
Unix linux which one you choose.
--
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
13. Search recursively for a pattern in the directory: -R prints the searched pattern in the given
directory recursively in all the files.
Syntax
$grep -R [Search] [directory]
Example :
$grep -iR geeks /home/geeks
Output:
./geeks2.txt:Well Hello Geeks
./geeks1.txt:I am a big time geek
----------------------------------
-i to search for a string case insensitively
-R to recursively check all the files in the directory.

WC
wc stands for word count. As the name implies, it is mainly used for counting purpose.
 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.

27
 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 [OPTION]... [FILE]...
Let us consider two files having name state.txt and capital.txt containing 5 names of the Indian
states and capitals respectively.
$ cat state.txt
Andhra Pradesh
Arunachal Pradesh
Assam
Bihar
Chhattisgarh

$ cat capital.txt
Hyderabad
Itanagar
Dispur
Patna
Raipur
Passing only one file name in the argument.

$ wc state.txt
5 7 58 state.txt
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
Note : When more than file name is specified in argument then command will display four-
columnar output for all individual files plus one extra row displaying total number of lines, words
and characters of all the files specified in argument, followed by keyword total. Options: 1. -
l: This option prints the number of lines present in a file. With this option wc command displays
two-columnar output, 1st column shows number of lines present in a file and 2nd itself represent
the file name.
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 this option wc command
displays two-columnar output, 1st column shows number of words present in a file and 2nd is the
file name.
With one file name
$ wc -w state.txt
7 state.txt

28
With more than one file name
$ wc -w state.txt capital.txt
7 state.txt
5 capital.txt
12 total
3. -c: This option displays count of bytes present in a file. With this option it display two-columnar
output, 1st column shows number of bytes present in a file and 2nd is the file name.
With one file name
$ wc -c state.txt
58 state.txt

With more than one file name


$ wc -c state.txt capital.txt
58 state.txt
39 capital.txt
97 total
4. -m: Using -m option ‘wc’ command displays count of characters from a file.
With one file name
$ 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
5. -L: The ‘wc’ command allow an argument -L, it can be used to print out the length of longest
(number of characters) line in a file. So, we have the longest character line Arunachal Pradesh in a
file state.txt and Hyderabad in the file capital.txt. But with this option if more than one file name is
specified then the last row i.e. the extra row, doesn’t display total but it display the maximum of all
values displaying in the first column of individual files. Note: A character is the smallest unit of
information that includes space, tab and newline.
With one file name
$ wc -L state.txt
17 state.txt

With more than one file name


$ wc -L state.txt capital.txt
17 state.txt
10 capital.txt
17 total
6. –version: This option is used to display the version of wc which is currently running on your
system.
$ wc --version
wc (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 and David MacKenzie.

29
Applications of wc Command
1. To count all files and folders present in directory: As we all know ls command in unix is
used to display all the files and folders present in the directory, when it is piped with wc command
with -l option it display count of all files and folders present in current directory.
$ ls gfg
a.txt
b.txt
c.txt
d.txt
e.txt
geeksforgeeks
India

$ ls gfg | wc -l
7
2. Display number of word count only of a file: We all know that this can be done
with wc command having -w option, wc -w file_name, but this command shows two-columnar
output one is count of words and other is file name.
$ wc -w state.txt
7 state.txt
So to display 1st column only, pipe(|) output of wc -w command to cut command with -c option.
Or use input redirection(<).
$ wc -w state.txt | cut -c1
7
OR
$ wc -w < state.txt
7

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

SYNTAX:
tee [OPTION]... [FILE]...
Options :
1.-a Option : It basically do not overwrite the file but append to the given file.
Suppose we have file1.txt
Input: geek
for
geeks
and file2.txt
Input:geeks
for
geeks
SYNTAX :
geek@HP:~$ wc -l file1.txt|tee -a file2.txt
OUTPUT :
3 file1.txt
geek@HP:~$cat file2.txt
OUTPUT:
geeks
30
for
geeks
3 file1.txt

2.–help Option : It gives the help message and exit.


SYNTAX :
anurag@HP:~$ tee --help

3.–version Option : It gives the version information and exit.


SYNTAX :
anurag@HP:~$ tee --version

Application

Suppose we want to count number of characters in our file and also want to save the output to
new text file so to do both activities at same time, we use tee command.

anurag@HP:~$ wc -l file1.txt| tee file2.txt

OUTPUT:
anurag@HP:~$15 file1.txt
Here we have file1 with 15 characters, so the output will be 15 and the output will be stored to
file2. In order to check the output we use :

anurag@HP:~$ cat file2.txt

OUTPUT:
anurag@HP:~$15 file1.txt

BC
bc command is used for command line calculator. It is similar to basic calculator by using which
we can do basic mathematical calculations.
Arithmetic operations are the most basic in any kind of programming language. Linux or Unix
operating system provides the bc command and expr command for doing arithmetic
calculations. You can use these commands in bash or shell script also for evaluating arithmetic
expressions.
Syntax:
31
bc [ -hlwsqv ] [long-options] [ file ... ]
Options:
-h, {- -help } : Print the usage and exit
-i, {- -interactive } : Force interactive mode
-l, {- -mathlib } : Define the standard math library
-w, {- -warn } : Give warnings for extensions to POSIX bc
-s, {- -standard } : Process exactly the POSIX bc language
-q, {- -quiet } : Do not print the normal GNU bc welcome
-v, {- -version } : Print the version number and copyright and quit
The bc command supports the following features:

 Arithmetic operators
 Increment or Decrement operators
 Assignment operators
 Comparison or Relational operators
 Logical or Boolean operators
 Math functions
 Conditional statements
 Iterative statements

1. Arithmetic Operators
Examples:
Input : $ echo "12+5" | bc
Output : 17

Input : $ echo "10^2" | bc


Output : 100
How to store the result of complete operation in variable?
Example:
Input:
$ x=`echo "12+5" | bc`
$ echo $x
Output:17
Explanation: Stores the result of first line of input in variable x and then display variable x as $x.
2. Assignment Operators
The list of assignments operators supported are:
 var = value : Assign the value to the variable
 var += value : similar to var = var + value
 var -= value : similar to var = var – value
 var *= value : similar to var = var * value
 var /= value : similar to var = var / value
 var ^= value : similar to var = var ^ value
 var %= value : similar to var = var % value
Examples:
Input: $ echo "var=10;var" | bc
Output: 10
Explanation: Assign 10 to the variable and print the value on the terminal.
Input: $ echo "var=10;var^=2;var" | bc
Output: 100
Explanation: Squares the value of the variable and print the value on the terminal.

How to store the result of complete operation in variable?


Example:

32
Input:
$ x=`echo "var=500;var%=7;var" | bc`
$ echo $x
Output:3
Explanation: Stores the result of 500 modulo 7 i.e. remainder of 500/7 in variable x and then
display variable x as $x.
3. Increment Operators
There are 2 kinds of increment operators:
 ++var : Pre increment operator, variable is increased first and then result of variable is
stored.
 var++ : Post increment operator, result of the variable is used first and then variable is
incremented.
Examples:
Input: $ echo "var=10;++var" | bc
Output: 11
Explanation: Variable is increased first and then result of variable is stored.
Input: $ echo "var=10;var++" | bc
Output: 10
Explanation: Result of the variable is used first and then variable is incremented.
4. Decrement Operators
There are 2 kinds of decrement operators:
 – – var : Pre decrement operator, variable is decreased first and then result of variable is
stored.
 var – – : Post decrement operator, result of the variable is used first and then variable is
decremented.
Examples:
Input: $ echo "var=10;--var" | bc
Output: 9
Explanation: Variable is decreased first and then result of variable is stored.
Input: $ echo "var=10;var--" | bc
Output: 10
Explanation: Result of the variable is used first and then variable is decremented.
5. Comparison or Relational Operators
Relational operators are used to compare 2 numbers. If the comparison is true, then result is 1.
Otherwise(false), returns 0. These operators are generally used in conditional statements like if.
The list of relational operators supported in bc command are shown below:
 expr1<expr2 : Result is 1 if expr1 is strictly less than expr2.
 expr1<=expr2 : Result is 1 if expr1 is less than or equal to expr2.
 expr1>expr2 : Result is 1 if expr1 is strictly greater than expr2.
 expr1>=expr2 : Result is 1 if expr1 is greater than or equal to expr2.
 expr1==expr2 : Result is 1 if expr1 is equal to expr2.
 expr1!=expr2 : Result is 1 if expr1 is not equal to expr2.
Examples:
Input: $ echo "10>5" | bc
Output: 1

Input: $ echo "1==2" | bc


Output: 0
6. Logical or Boolean Operators
Logical operators are mostly used in conditional statements. The result of the logical operators is
either 1(TRUE) or 0(FALSE).
 expr1 && expr2 : Result is 1 if both expressions are non-zero.
 expr1 || expr2 : Result is 1 if either expression is non-zero.

33
 ! expr : Result is 1 if expr is 0.
Examples:
Input: $ echo "10 && 5" | bc
Output: 1

Input: $ echo "0 || 0" | bc


Output: 0

Input: $ echo "! 0" | bc


Output: 1
7. Mathematical Functions
The built-in math functions supported are :
 s (x): The sine of x, x is in radians.
 c (x) : The cosine of x, x is in radians.
 a (x) : The arctangent of x, arctangent returns radians.
 l (x) : The natural logarithm of x.
 e (x) : The exponential function of raising e to the value x.
 j (n,x) : The bessel function of integer order n of x.
 sqrt(x) : Square root of the number x. If the expression is negative, a run time error is
generated.
In addition to the math functions, the following functions are also supported :
 length(x) : returns the number of digits in x.
 read() : Reads the number from the standard input.
 scale(expression) : The value of the scale function is the number of digits after the decimal
point in the expression.
 ibase and obase define the conversion base for input and output numbers. The default for
both input and output is base 10.
 last (an extension) is a variable that has the value of the last printed number.
Examples:
Input:
$ pi=`echo "h=10;4*a(1)" | bc -l`
$ echo $pi
Output: 3.14159265358979323844
Explanation: Assign the value of “pi” to the shell variable pi. Here, a refers to the arctangent
function, which is part of the math library loaded with the -l option.
Input: $ echo "scale($pi)" | bc -l
Output: 20
Explanation: Gives the number of digits after decimal point in value of “pi” calculated in previous
example.
Input: $ echo "s($pi/3)" | bc -l
Output: .86602540378443864675
Explanation: Gives sine values at “pi/3” angle. Angle must be in radians. Here, s refers to the sine
function
Input: $ echo "c($pi/3)" | bc -l
Output: .50000000000000000001
Explanation: Gives cosine values at “pi/3” angle. Angle must be in radians. Here, c refers to the
cosine function.
Input: $ echo "e(3)" | bc -l
Output:20.08553692318766774092
Explanation: Gives exponential^value as output.
Input: $ echo "l(e(1))" | bc -l
Output: .99999999999999999999
Explanation: Gives natural logarithm of the value i.e. w.r.t. base ‘e’.

34
Input: $ echo "obase=2;15" | bc -l
Output: 1111
Explanation: Convert Decimal to Binary.
Input: $ echo "obase=8;9" | bc -l
Output: 11
Explanation: Convert Decimal to Octal.
Input: $ echo "ibase=2;1111" | bc -l
Output: 15
Explanation: Convert Binary to Decimal.
Input: $ echo "ibase=2;obase=8;10" | bc -l
Output: 2
Explanation: Convert Binary to Octal.
8. Conditional Statements
Conditional Statements are used to take decisions and execute statements based on these
decisions. bc command supports the if condition.
Syntax:
if(condition) {statements} else {statements}
Example:
Input: $ echo 'n=8;m=10;if(n>m) print "n is greater" else print "m is greater" ' | bc -l
Output: m is greater
9. Iterative statements
bc command supports the for loop and while loop for doing iterations.
Syntax:
for(assignment; condition; updation)
{
statements.....
.......
........
}

OR

while(condition)
{
statements.....
.......
........
}
Examples:
Input: $ echo "for(i=1; i<=10; i++) {i;}" | bc
Output:
1
2
3
4
5
6
7
8
9
10
Input: $ echo "i=1;while(i<=10) {i; i+=1}" | bc
Output:

35
1
2
3
4
5
6
7
8
9
10
Explanation: Both examples prints numbers from 1 to 10 using the respective looping syntax.
Some Pseudo Statements:
 break : This statement causes a forced exit of the most recent enclosing while statement or
for statement.
 continue : The continue statement (an extension) causes the most recent enclosing for
statement to start the next iteration.
 halt : The halt statement (an extension) is an executed statement that causes the bc
processor to quit only when it is executed. For example, “if (0 == 1) halt” will not cause bc to
terminate because the halt is not executed.
 return : Return the value 0 from a function. (See the section on functions).
 return(expression) : Return the value of the expression from a function. (See the section on
functions). As an extension, the parenthesis are not required.
 limits : Print the local limits enforced by the local version of bc. (This is an extension).
 quit : When the quit statement is read, the bc processor is terminated, regardless of where
the quit statement is found. For example, “if (0 == 1) quit” will cause bc to terminate.
 warranty : Print a warranty notice. (This is an extension).
10. Functions : Functions provide a method of defining a computation that can be executed later.
Functions in bc always compute a value and return it to the caller. Function definitions are
“dynamic” in the sense that a function is undefined until a definition is encountered in the input.
That definition is then used until another definition function for the same name is encountered. The
new definition then replaces the older definition.
Syntax:
define name (parameters)
{
statements.......
.......
........
return statement

}
11. We can write our arithmetic expressions in a file and then execute those statements by
providing the filename to the bc command.
Example:
Input :
$ cat >> example.txt
2+5;
var = 10*3
var
print var
quit

Press ctrl+D

36
$ bc example.txt
Output :
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
7
30
TO AVOID SYSTEM GENERATED MESSAGE ON OUTPUT SCREEN, USE:
$ bc -q example.txt
Output :
7
30
12. Important Points:
1. Bc command treats the semicolon (;) or newline as the statement separator.
2. To group statements use the curly braces. Use with functions, if statement, for and while
loops.
3. If only an expression is specified as a statement, then bc command evaluates the
expression and prints the result on the standard output.
4. If an assignment operator is found. Bc command assigns the value to the variable and do
not print the value on the terminal.
5. A function should be defined before calling it. Always the function definition should appear
first before the calling statements.
6. If a standalone variable is found as a statement, bc command prints the value of the
variable. You can also Use the print statement for displaying the list of values on the
terminal.

PASSWD
passwd command in Linux is used to change the user account passwords. The root user reserves
the privilege to change the password for any user on the system, while a normal user can only
change the account password for his or her own account.
Syntax:
passwd [options] [username]
Example:
Command: passwd

Command [root]: passwd user1

37
Note: sudo can be used to invoke root privileges by normal users, and can change the password
for root itself. This is particularly helpful when a user is member of admin group (holds a position in
sudoers list (/etc/sudoers) and can use commands with sudo) and the root password is not set,
which is case with many common distributions of linux.
Command: sudo passwd root

Processing in passwd command:


1. Verify current user password : Once the user enters passwd command, it prompts for
current user password, which is verified against the password stored in /etc/shadow file
user. The root user can bypass this step and can directly change the password, so as the
forgotten passwords may be recovered.
2. Verify password aging information : In Linux, a user password can be set to expire after
a given period of time. Also, a user can be prohibited to change his/her password for a
period. This password aging information (and the password itself) is stored in a file
/etc/shadow.
3. Change the password : After authentication, the user is prompted to enter the new
password and verify it by retyping the password.

Shell Script

1.Linux shell script program to add two numbers

#!/bin/bash
# Program name: "add_two_num.sh"
# Shell script program to add two numbers.
num1=10
num2=20
num3=`expr $num1 + $num2`
echo "Sum is: $num3"

38
Output:
$ sh add_two_num.sh
Sum is: 30

2. Linux shell script program to swap two numbers

#!/bin/bash
# Program name: "swap.sh"
# shell script program to swap two numbers.
num1=10
num2=20
echo "Before Swapping"
echo "Num1: $num1"
echo "Num2: $num2"
num3=$num1
num1=$num2
num2=$num3
echo "After Swapping"
echo "Num1: $num1"
echo "Num2: $num2"

Output:
$ sh swap.sh
Before Swapping
Num1: 10
Num2: 20
After Swapping
Num1: num2
Num2: num3

3.Linux shell script program to multiply two numbers

#!/bin/bash
# Program name: "multiply.sh"
# Linux shell script program to multiply two numbers.
echo "Enter num1: "
read num1
echo "Enter num2: "
39
read num2
multiply=`expr $num1 \* $num2`
echo "Multiplication is: $multiply"

Output:
$ sh multiply.sh
Enter num1:
10
Enter num2:
5
Multiplication is: 50

4.Write a shell script to find factorial of given number n.


read -p "Enter the number : " number
fact=1
while[$number -gt1]
do
fact=$((fact * number))#fact = fact * num
number=$((number -1))#num = num - 1
done
echo"Result:"$fact

Output

5.Write a shell script which will accept a number b and display first n
prime numbers as output.

read -p "Enter the NUmber: " n


echo"The prime numbers $n are: "
m=2
while[$m -le $n]
do
i=2
40
flag=0
while[$i -le `expr $m / 2`]
do
if[`expr $m % $i` -eq 0]
then
flag=1
break
fi
i=`expr $i + 1`
done
if[$flag -eq 0]
then
echo$m
fi
m=`expr $m + 1`
done
Output:

6.Write a shell script which will generate first n fibonnacci numbers like: 1,
1, 2, 3, 5, 13, …
read -p "Enter the Number: " number
x=0
y=1
i=2
echo"Fibonacci Series Upto$numberNumber: "
41
echo"$x"
echo"$y"
while[$i -lt$number]
do
i=`expr $i + 1`
z=`expr $x + $y`
echo"$z"
x=$y
y=$z
done
Output:

7.Write a menu driven shell script which will print the following menu and
execute the given task.
a. Display calendar of current month
b. Display today’s date and time
c. Display usernames those are currently logged in the system
d. Display your name at given x, y position
e. Display your terminal number
echo"Select Anyone Option"
echo"**************************************************"
echo"1)DisplayCalener of current month"
echo"2)Display Today's Date and Time"
echo"3)Display Username who are currently logged in"
echo"4)Display your name on given x,y position"
echo"5)Display your terminal Number"
echo"6)Exit"
echo"Enter your choice:"
42
readch
case$chin
1)cal;;
2)date;;
3)who;;
4)row=$(tput lines)
col=$(tput cols)
echo"Terminal Window has Rows=$row Cols=$col"
echo"Enter desired X,Y position"
echo"X position="
read x
echo"Y position="
read y
echo"Enter the name"
read name
tput cup $x$y
echo"$name";;
5)tty;;
6)echo "Exit";;
*)echo"Enter valid choice";;
esac

Output:

43
8.Write a shell script to read n numbers as command arguments and sort
them in descending order.
read -p "Enter The Number: " n
for((i=0;i<$n;i++))
do
read -p "Enter value of arr[$i]: "arr[$i]
done
#sorting code
for((i=0;i<$n;i++))
do
for((j=0; j<n-i-1;j++))
do
if[${arr[j]} -lt${arr[$((j+1))]}]
then
#swapping
temp=${arr[j]}
arr[$j]=${arr[$((j+1))]}
arr[$((j+1))]=$temp
fi
done
echo"Numbers in Descending order: "${arr[*]}
Output

9.Write a shell script to validate the entered date. (eg. Date format is : dd-
mm-yyyy).
echo"Enter Valid Date"
readdate
echo"You have entered $date"
date -d $date
if[$? -eq 0]
then
echo"Enter Date is Valid"
else
echo"Enter Date is Invalid"
fi
44
CONCLUSION

Unix is a powerful operating system that has been use since the
late 1960s. It has evolved over time, with various versions and
flavors developed to suit specific needs and requirements.

One of the key strengths of Unix is its flexibility and versatility. It


was designed to be modular and customizable, allowing users to
create their own tools and applications to meet their specific
needs. This has made it a popular choice for developers and
system administrators.

Another advantage of Unix is its stability and reliability. It was


designed to be robust and resilient, with built-in mechanisms for
error handling and recovery. This has made it a popular choice
for mission-critical applications that require high levels of uptime
and availability.

Unix has also been a major influence on the development of


other operating systems, including Linux and macOS. Many of
the principles and concepts introduce in Unix have been adopted
by these systems, helping to shape the modern computing
landscape.

45

You might also like