UNIT3 Command
UNIT3 Command
Unix Commands
cd (Change Directory) Command
🞂 The cd command is used to change the current directory (i.e., the
directory in which the user is currently working)
🞂 Syntax :
cd [-Options] [Directory]
🞂 Example :
Option Use
Option Use
To show long listing information about the
ls -l
file/directory
ls -a List all files including hidden file starting with '.'
ls -r List in reverse order
ls -t Sort by time & date
ls -s Sort by file size
ls Command
drwxr-
xr-x
rs
own
er
othe
grou
p
🞂 Directory & Files
🞂 A read, write, execute permissions for user(root), group and others
respectively
🞂 A number of links for file / dir.
🞂 It specifies owner of the file / dir.
🞂 It specifies group of the file / dir.
🞂 It indicates the file / dir size in bytes.
🞂 It specifies the date and time of the last modification of the file.
🞂 It specify name of the file / dir.
ls Command Example
To show long listing information about the
ls -l
file/directory
ls Command Example
List all files including hidden file starting
ls -a
with '.'
ls Command Example
ls -r List in reverse order
man Command
• It is the interface used to view the system's reference manuals.
🞂 Syntax :
man [command name]
🞂 Example
echo Command
🞂 Display a line of text/string on standard output or a file.
🞂 Syntax :
echo [option] [string]
🞂 Example :
Option Use
echo -n Do not output a trailing newline
Enable interpretation of backslash escape
echo -e
sequences
Option Use
\b It removes all the spaces in between the text
\n It creates new line from where it is used
\t It create horizontal tab spaces
echo Command Example
echo -n Do not output a trailing newline
echo Command Example
Enable interpretation of backslash escape
echo -e
sequences
\b It removes all the spaces in between the text
\n It creates new line from where it is used
\t It create horizontal tab spaces
cal Command
🞂 Displays a simple, formatted calendar in your terminal.
🞂 Syntax :
cal [options] [[[day] month] year]
🞂 Example :
Option Use
cal -1 Display single month output. (This is the default.)
cal -3 Display three months spanning the date.
cal -s Display Sunday as the first day of the week.
cal -m Display Monday as the first day of the week.
Use day-of-year numbering for all calendars. These are also
cal -j
called ordinal days. Ordinal days range from 1 to 366.
cal –y Display a calendar for the whole year
cal Command Example
Cal or cal -1 Display single month output. (This is the default.)
cal Command Example
cal -3 Display three months spanning the date.
cal Command Example
cal
cal -s 2018 | more
Display Sunday as the first day of the week.
cal Command Example
cal -m Display Monday as the first day of the week.
cal Command Example
Use day-of-year numbering for all calendars. These are
cal -j also called ordinal days. Ordinal days range from 1 to
366.
cal Command Example
cal –y Display a calendar for the whole year
date Command
🞂 Print or set the system date and time.
🞂 Syntax :
date [OPTION]... [+FORMAT]
🞂 Example :
Option Use
date +%a The abbreviated weekday name (e.g., Sun)
date +%A The full weekday name (e.g., Sunday)
date +%b The abbreviated month name (e.g., Jan)
date +%B Locale's full month name (e.g., January)
The current century; like %Y, except omit last two
date +%C
digits (e.g., 20)
date +%w day of week (0..6); 0 is Sunday
date Command
Option Use
date +%d Display the day of the month
date +%m Displays the month of year (01 to 12)
date +%y Displays last two digits of the year(00 to 99)
date +%Y Display four-digit year.
date +%T Display the time in 24 hour format as HH:MM:SS
date +%H Display the hour
date +%M Display the minute
date +%S Display the seconds
ISO week number, with Monday as first day of
date +%V
week (01..53)
date +%P locale's equivalent of either AM or PM
date Command Example
date +%a The abbreviated weekday name (e.g., Sun)
date +%A The full weekday name (e.g., Sunday)
date Command Example
date +%b The abbreviated month name (e.g., Jan)
date +%B Locale's full month name (e.g., January)
date Command Example
date +%c Full date with IST timing
The current century; like %Y, except omit last
date +%C
two digits (e.g., 20)
date Command Example
date +%d Display the day of the month
date +%m Displays the month of year (01 to 12)
date +%y Displays last two digits of the year(00 to 99)
date Command Example
date +%y Displays last two digits of the year(00 to 99)
date +%Y Display four-digit year.
date Command Example
Display the time in 24 hour format as
date +%T
HH:MM:SS
date +%H Display the hour
date +%M Display the minute
date +%S Display the seconds
date Command Example
ISO week number, with Monday as first day of
date +%V
week (01..53)
date Command Example
date +%P locale's equivalent of either AM or PM
clear Command
🞂 Clear the terminal screen.
🞂 If you take a detailed look after running the clear command, you'll find
that it doesn't really clear the terminal. The tool just shifts the text
upwards, out of the viewable area.
🞂 Syntax :
clear
clear Command Example
touch Command
• It is used to create empty file or hidden file content.
🞂 Syntax :
touch [FILE]
🞂 Example :
cat Command
• It is used to create, display and concatenate file contents.
🞂 Syntax :
cat [OPTION] [FILE]
🞂 Example :
Option Use
cat -b Omits line numbers for blank space in the output
cat -E Displays a $ (dollar sign) at the end of each line
cat -n Line numbers for all the output lines
cat -s Suppress repeated empty output lines
cat -T Displays the tab characters as ^I in the output
cat Command
🞂 Example :
$ cat > file1.txt
🞂 It creates file1.txt and allow us to insert content for this file.
🞂 After inserting content you can use ctrl+c to exit the file.
$cat file.txt > newfile.txt
🞂 Read the contents of file.txt and write them to newfile.txt, overwriting
anything newfile.txt previously contained. If newfile.txt does not exist, it
will be created.
$cat file.txt >> newfile.txt
🞂 Read the contents of file.txt and append them to the end of newfile.txt.
If newfile.txt does not exist, it will be created.
cat Command
🞂 Example :
cat file1.txt file2.txt
• It will read the contents of file1.txt and file2.txt and display the result in
the terminal.
cat file1.txt file2.txt > combinedfile.txt
• It will concatenate the contents of file1.txt and file2.txt and write them to
a new file combinedfile.txt using the (>) operator.
• If the combinedfile.txt file doesn’t exist the command will create it.
Otherwise it will overwrite the file.
cat Command Example
🞂 $ cat > file1.txt
• It creates file1.txt and allow us to insert content for this file.
• After inserting content you can use ctrl+c to exit the file.
cat Command Example
cat -b Omits line numbers for blank space in the output
cat -E Displays a $ (dollar sign) at the end of each line
cat Command Example
🞂 $cat file.txt > newfile.txt
• Read the contents of file.txt and write them to newfile.txt, overwriting
anything newfile.txt previously contained.
• If newfile.txt does not exist, it will be created.
cat Command Example
🞂 $cat file.txt >> newfile.txt
• Read the contents of file.txt and append them to the end of newfile.txt.
If newfile.txt does not exist, it will be created.
cat Command Example
🞂 cat file1.txt file2.txt
• It will read the contents of file1.txt and file2.txt and display the result in
the terminal.
cat Command Example
🞂 cat file1.txt file2.txt > combinedfile.txt
• It will concatenate the contents of file1.txt and file2.txt and write them to
a new file combinedfile.txt using the (>) operator.
• If the combinedfile.txt file doesn’t exist the command will create it
otherwise it will overwrite the file.
cat Command Example
• Reverse command tac filename
• The ‘-A’ option allows you to combine the effects of ‘-v’, ‘-E’, and ‘-T’
options cat –A filename.
• display the content of all text files in a folder, use the wildcard (‘*.txt’):
cat *.txt
• The –T options allows you to visually distinguish between tabs and spaces.
pwd (Print working directory) Command
• It prints the current working directory name with the complete path
starting from root (/).
🞂 Syntax :
pwd [-OPTION]
🞂 Example :
who Command
• It display the users that are currently logged into your Unix computer
system.
🞂 Syntax :
who [-options] [filename]
🞂 Example :
Optio
Use
n
who -b Display the time of the last system boot
who -H Print a line of column headings
Displays all login names, and a count of all logged-on
who -q
users
who -a Display all details of current logged in user
who Command Example
Option Use
whoami --help Display a help message, and exit
whoami --
Display version information, and exit
version
whoami Command Example
whoami --help Display a help message, and exit
whoami Command Example
whoami --
Display version information, and exit
version
uname (unix name) Command
• Print information about the current system.
🞂 Syntax :
uname [-OPTION]
🞂 Example :
Option Use
uname -s Print the kernel name
uname -
Print the network node hostname
n
uname -v Print the kernel version
uname -
Print the machine hardware name
m
uname -
Print the operating system
o
uname Command Example
uname -
Print the kernel name
s
uname Command Example
uname -
Print the network node hostname
n
uname Command Example
uname -
Print the kernel version
v
uname Command Example
uname -
Print the machine hardware name
m
uname Command Example
uname -
Print the operating system
o
passwd Command
• The passwd command is used to change the password of a user account.
🞂 Syntax :
passwd [-options] [username]
🞂 Example :
mkdir Command
• This command is used to make Directories.
🞂 Syntax :
mkdir [-OPTION] DIRECTORY
🞂 Example :
Option Use
mkdir -v Print a message for each created directory
mkdir -p No error if existing, make parent directories as needed
mkdir -
To control the permissions of new directories
m
mkdir Command Example
mkdir -v Print a message for each created directory
mkdir Command Example
mkdir -p No error if existing, make parent directories as needed
mkdir Command Example
mkdir -m To control the permissions of new directories
Option Use
Remove directory and its ancestors… e.g., ‘rmdir -p
rmdir -p
a/b/c’ is similar to ‘rmdir a/b/c a/b a’
Option Use
cp -i Interactive - ask before overwrite
cp -f Force copy by removing the destination file if needed
cp -n Do not overwrite an existing file
cp -u Update - copy when source is newer than destination
cp -s Make symbolic links instead of copying
cp -R Copy directories recursively
cp -v Print informative messages
cp Command Example
cp Command Example
cp -i Interactive - ask before overwrite
cp Command Example
cp -v Print informative messages
cp Command Example
cp -s Make symbolic links instead of copying
mv(move) Command
• mv command is used to move and rename files and directories.
🞂 Syntax :
mv [-options] source dest
🞂 Example :
Optio
Use
n
mv -i Interactive prompt before overwrite
mv -f Force move by overwriting destination file without prompt
mv -n Never overwrite any existing file
mv -u Update - move when source is newer than destination
mv -v Print informative messages
mv Command Example
rm(remove) Command
• The ‘rm’ command is used to delete files and directories.
🞂 Syntax :
rm [-OPTION] Filename
🞂 Example :
Optio
Use
n
rm -i Prompt before every removal
rm -d Delete a empty directory
rm -r Remove directories and their contents recursively
rm -f To remove the file forcefully
rm Command Example
rm -i Prompt before every removal
cut Command
• The cut command extracts a given number of characters or columns from
a file.
🞂 Syntax :
cut [-options] [file]
🞂 Example :
Optio
Use
n
Select only the characters from each line as specified in
cut -c
LIST
cut -b Select only the bytes from each line as specified in LIST
Cuts the input file using list of field. The default field to be
cut -f used TAB. The default behavior can be overwritten by
use of -d option
Specifies a delimiter to by used as a field. Default field is
cut -d
TAB and this option overwrites this default behavior
cut Command Example
Select only the characters from each line as specified
cut -c
in LIST
cut Command Example
cut -b Select only the bytes from each line as specified in LIST
cut Command Example
Cuts the input file using list of field. The default field to be used TAB. The
cut -f
default behavior can be overwritten by use of -d option
Specifies a delimiter to by used as a field. Default field is TAB and this
cut -d
option overwrites this default behavior
paste Command
• The paste command displays the corresponding lines of multiple files side-
by-side.
🞂 Syntax :
paste [-options] [file]
🞂 Example :
Optio
Use
n
paste -
Reuse characters from LIST instead of tabs
d
paste -
Paste one file at a time instead of in parallel
s
paste Command Example
paste - Reuse characters from LIST instead
d of tabs
paste Command Example
paste Paste one file at a time instead of in
-s parallel
more Command
• The more command is a command line utility for viewing the contents of a
file or files once screen at a time.
🞂 Syntax :
more [-options] [file]
🞂 Example :
Option Use
more -c Clear screen before displaying
more - To Specify how many lines are printed in the screen
number for a given file
more -s Doesn’t display extra blank lines
more Command Example
more Command Example
more - To Specify how many lines are printed in the
number screen for a given file
more Command Example
more -c Clear screen before displaying
cmp Command
• cmp command in Linux/UNIX is used to compare the two files byte by
byte and helps you to find out whether the two files are identical or not.
• If a difference is found, it reports the byte and line number where the first
difference is found.
• If no differences are found, by default, cmp returns no output.
🞂 Syntax :
• cmp [OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]]
cmp Command Example
Option Use
cmp -b Print differing bytes
cmp -i Skip a particular number of initial bytes from both the files
Do not print anything; only return an exit status indicating
cmp -s
whether the files differ
cmp -n Compare at most LIMIT bytes
cmp -l Print byte position and byte value for all differing bytes
cmp Command Example
cmp -b Print differing bytes
cmp Command Example
Skip a particular number of initial bytes from both the
cmp -i
files
cmp Command Example
Do not print anything; only return an exit status
cmp -s
indicating whether the files differ
cmp Command Example
cmp -n Compare at most LIMIT bytes
cmp Command Example
Print byte position and byte value for all differing
cmp -l
bytes
comm Command
• Compare two sorted files line by line.
🞂 Syntax :
comm [OPTION]... FILE1 FILE2
🞂 Example :
comm Command Example
Option Use
comm -
Suppress column 1 (lines unique to FILE1)
1
comm -
Suppress column 2 (lines unique to FILE2)
2
comm -
Suppress column 3 (lines that appear in both files)
3
diff(difference) Command
• This command is used to display the differences in the files by comparing
the files line by line
• diff analyzes two files and prints the lines that are different. Essentially, it
outputs a set of instructions for how to change one file to make it identical
to the second file.
🞂 Syntax :
diff [options] File1 File2
🞂 Example :
Option Use
diff -b Ignores spacing differences
diff -i Ignores case
diff Command Example
Logout:
The correct command to end the session at the login shell is logout, but
the exit command also terminates the session.
chmod(change mode) Command
• chmod is used to change the permissions of files or directories.
🞂 Syntax :
chmod [reference][operator][mode] file...
🞂 Example :
Referenc Clas
Description
e s
u owner file's owner
g group users who are members of the file's group
other users who are neither the file's owner nor
o
s members of the file's group
a all All three of the above
chmod(change mode) Command
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
Permissi
Description
on
r Permission to read the file
w Permission to write (or delete) the file
Permission to execute the file, or, in the case of a
x
directory, search it
chmod Command Example
r (read) 4
w (write) • Each
2 write, read, and execute permissions have following
number value:
x (execute) 1
no
0
permissions
u owner
g group
o others
a all
chmod Command Example
chown(change owner) Command
• The chown command changes ownership of files and directories in a Linux
filesystem.
🞂 Syntax :
chown [OPTIONS] USER[:GROUP] FILE(s)
Optio
Use
n
Display every active process on a Linux system in
ps -e
generic (Unix/Linux) format
ps -x View all processes owned by you
ps -f To provide more information on processes
ps -u Filter processes by its user
ps Command Example
Display every active process on a Linux system in
ps -e
generic (Unix/Linux) format
ps Command Example
ps -x View all processes owned by you
ps Command Example
ps -f To provide more information on processes
kill Command
• It is used to terminate processes manually.
• kill command sends a signal to a process which terminates the process.
• If the user doesn’t specify any signal which is to be sent along with kill
command then default TERM signal is sent that terminates the process..
🞂 Syntax :
kill [option] PID
kill Command Example
kill Command Example
Kill -l To display all the available signals
wc Command
• It is used to find out number of newline count, word count, byte and
characters count in a files specified by the file arguments.
🞂 Syntax :
wc [options] filenames
Optio
Use
n
wc -l Prints the number of lines in a file
wc -w Prints the number of words in a file
wc -c Displays the count of bytes in a file
wc -L Prints only the length of the longest line in a file
wc Command Example
Optio
Use
n
nl -i Line number increment at each line
nl -s Add STRING after (possible) line number
nl -w Use NUMBER columns for line numbers
nl Command Example
nl Command Example
nl -i Line number increment at each line
nl Command Example
nl -s Add STRING after (possible) line number
nl Command Example
nl -w Use NUMBER columns for line numbers
nl Command
nl Command
file Command
• The file command is used to determine a file's type.
🞂 Syntax :
file [OPTIONS] file1 file2 …
🞂 Example :
file Command Example
To view the mime type of a file rather than the human
file -i
readable format
finger Command
• finger looks up and displays information about system users.
🞂 Syntax :
finger [-option] [username]
🞂 Example :
finger Command Example
finger - Match arguments only on user name (not first or last
m name)
finger Command Example
finger -l Force long output format
head Command
• head makes it easy to output the first part (10 lines by default) of files.
🞂 Syntax :
head [OPTION]... [FILE]...
🞂 Example :
Optio
Use
n
head - Print the first n lines instead of the first 10; with the
n leading '-', print all but the last n lines of each file
Print the first n bytes of each file; with a leading '-', print
head -c
all but the last n bytes of each file
head -
Never print headers identifying file names
q
head Command Example
head Command Example
head - Print the first n lines instead of the first 10; with the
n leading '-', print all but the last n lines of each file
head Command Example
head - Print the first n bytes of each file; with a leading '-',
c print all but the last n bytes of each file
head Command Example
head -
Never print headers identifying file names
q
tail Command
• tail is a command which prints the last few number of lines (10 lines by
default) of a certain file, then terminates.
🞂 Syntax :
tail [OPTION]... [FILE]...
Optio
Use
n
tail -n Output the last num lines, instead of the default (10)
tail -c Output the last num bytes of each file
tail -q Never output headers
tail Command Example
tail Command Example
tail -n Output the last num lines, instead of the default (10)
tail Command Example
tail -c Output the last num bytes of each file
ln Command
• ln creates links between files.
• ln creates hard links by default, or symbolic links if the -s (--symbolic)
option is specified. When creating hard links, each TARGET must exist.
🞂 Syntax :
ln [OPTION]… [-T] TARGET LINK_NAME
Optio
Use
n
ln -f If the destination file or files already exist, overwrite them
ln -i Prompt the user before overwriting destination files
ln -s Make symbolic links instead of hard links
ln Command Example
ln Command Example
ln -s Make symbolic links instead of hard links
f2.txt f6.txt
(hello good (hello good
morning) morning)
find Command
• find command searches for files in a directory hierarchy.
🞂 Syntax :
find [option] [path...] [expression]
Option Use
find -name Search for files that are specified by
filename ‘filename’
find -newer Search for files that were modified/created
filename after ‘filename’
Search for files owned by user name or ID
find -user name
‘name’
Search for files of ‘N’ blocks; ‘N’ followed by
find -size +N/-N
‘c’ can be used to measure size in characters
find -empty Search for empty files and directories
find -perm octal Search for the file if permission is ‘octal’
find Command Example
find Command Example
find -newer Search for files that were
filename modified/created after ‘filename’
find Command Example
Search for files owned by user name or ID
find -user name
‘name’
find Command Example
Search for files of ‘N’ blocks; ‘N’ followed
find -size +N/-N by ‘c’ can be used to measure size in
characters
find Command Example
find -
Search for empty files and directories
empty
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.
Using options in sort command, it can also be used to sort numerically.
🞂 Syntax : sort [OPTION]... [FILE]...
Option Use
sort -c To check if the file given is already sorted or not
sort -r Reverse the result of comparisons
sort -n Compare according to string numerical value
sort -nr To sort a file with numeric data in reverse order
sort -k Sorting a table on the basis of any column
sort -b Ignore leading blanks
sort Command Example
sort Command Example
sort -c To check if the file given is already sorted or not
sort Command Example
sort -r Reverse the result of comparisons
sort Command Example
sort -n Compare according to string numerical value
sort -nr To sort a file with numeric data in reverse order
sort Command Example
sort -k Sorting a table on the basis of any column
uniq Command
• uniq reports or filters out repeated lines in a file.
• It can remove duplicates, show a count of occurrences, show only
repeated lines, ignore certain characters and compare on specific fields.
🞂 Syntax :
uniq [OPTION]... [INPUT [OUTPUT]]
Optio
Use
n
uniq -u Prints only unique lines
uniq -d Only print duplicated lines
uniq -D Print all duplicate lines
Prefix lines with a number representing how many times
uniq -c
they occurred
uniq -i Ignore case when comparing
uniq Command Example
uniq Command Example
uniq -u Prints only unique lines
uniq Command Example
uniq -d Only print duplicated lines
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 globally search for regular expression and print out.
🞂 Syntax :
grep [options] pattern [files]
Optio
Use
n
grep -c Prints only a count of the lines that match a pattern
Display the matched lines, but do not display the
grep -h
filenames
grep -l Displays list of a filenames only
grep -i Ignores, case for matching
grep Command Example
grep Command Example
Prints only a count of the lines that match a
grep -c
pattern
Display the matched lines, but do not display the
grep -h
filenames
grep -l Displays list of a filenames only
grep Command Example
grep -n Display the matched lines and their line numbers
grep Command Example
This prints out all the lines that do not matches
grep -v
the pattern
grep Command Example
grep -w Match whole word
grep Command Example
grep -o Print only the matched parts of a matching line
grep Command Example
pipe (|) Command
• It redirects the command STDOUT or standard output into the given next
command STDIN or standard input.
• In short, the output of each process directly as input to the next one like a
pipeline.
• The symbol '|' denotes a pipe.
• Pipes help you mash-up two or more commands at the same time and run
them consecutively.
🞂 Syntax :
command_1 | command_2 | command_3 | .... | command_N…
pipe Command Example
pipe Command Example
pipe Command Example
tr(translate) Command
• The tr command in UNIX is a command line utility for translating or
deleting characters.
• It supports a range of transformations including uppercase to lowercase,
squeezing repeating characters, deleting specific characters and basic find
and replace.
• It can be used with UNIX pipes to support more complex translation.
• tr stands for translate.
🞂 Syntax :
tr [OPTION] SET1 [SET2]
tr(translate) Command
🞂 POSIX Character set supported by tr command :
• [:digit:] Only the digits 0 to 9.
• [:alnum:] Any alphanumeric character.
• [:alpha:] Any alpha character A to Z or a to z.
• [:blank:] Space and TAB characters only.
• [:xdigit:] Hexadecimal notation 0-9, A-F, a-f.
• [:upper:] Any alpha character A to Z.
• [:lower:] Any alpha character a to z..
Option Use
Replaces repeated characters listed in the set1 with single
tr -s
occurrence
tr -d Delete characters in string1 from the input
complements the set of characters in string. i.e., operations apply
tr -c
to characters not in the given set
tr -cd Remove all characters except digits
tr Command Example
tr Command Example
tr Command Example
Replaces repeated characters listed in the set1 with single
tr -s
occurrence
tr Command Example
tr -d Delete characters in string1 from the input
tr Command Example
complements the set of characters in string.
tr -c
i.e., operations apply to characters not in the given set
tr Command Example
tr -cd Remove all characters except digits
history Command
• history command is used to view the previously executed command.
🞂 Syntax :
history
🞂 Example :
history Command Example
write Command
• write sends a message to another user.
🞂 Syntax :
write user [ttyname]
🞂 Example
Optio
Use
n
user The user to write to
The specific terminal to write to, if the user is logged in to
tty
more than one session
write Command Example
• Open first
terminal.
Optio
Use
n
wall -n --nobanner Suppress banner
--timeout TIMEOUT Write timeout to terminals in
seconds. TIMEOUT must be positive integer. Default
wall -t
value is 300 seconds, which is a legacy from time when
people ran terminals over modem lines.
wall Command Example
• Open four different terminal, execute command on first terminal,
message will display on everybody’s terminal.
tty Command
• tty display information related your terminal.
🞂 Syntax :
tty
🞂 Example
script Command
• script is used to make typescript or record all the terminal activities.
🞂 Syntax :
script filename
🞂 Example
Shell Script
🞂 Script is a sequence of commands written as plain text and run by an
interpreter (shell).
🞂 A shell script is a computer program designed to be run by the Unix/Linux
shell which could be one of the following:
⮩ The Bourne Shell
⮩ The C Shell
⮩ The Korn Shell
⮩ The GNU Bourne-Again Shell
Shell Script - Cont.…
🞂 The prompt, $, which is called the command prompt, is issued by the
shell. While the prompt is displayed, you can type a command.
🞂 The shell interprets commands the user types and manages their
execution.
🞂 A shell is a command-line interpreter and typical operations performed by
shell scripts include file manipulation, program execution, and printing
text.
Steps to write and execute a shell script
1. Create a file using a vi editor(or any other editor like gedit).
2. Name script file with extension .sh
3. Write some code.
4. Save the script file as filename.sh
5. For executing the script type bash filename.sh
OR ./filename.sh
OR /path/filename.sh
Shell Comments
1) Single line comment (#)
2) Multiline comments (<<comment stat comment)
Shell Variables
🞂 The user variable name can be any sequence of letters, digits, and the
underscore character, but the first character must be a letter.
🞂 To assign a value to a variable:
number=25
name=“abc"
🞂 There cannot be any space before or after the “=“
🞂 Internally, all values are stored as strings.
🞂 To use a variable, precede the name with a “$”.
num=3
a=$num
User input in Shell Script
🞂 The read command allows a user to provide the runtime input.
🞂 Shell allows to prompt for user input.
🞂 Syntax:
read varname [more vars]
• Value entered by user is assigned to varname
🞂 Run shell script :
bash filename.sh
Operators
Arithmetic Operators
Bash
Operator Description
Operator
+ + Addition
- - Subtraction
\* * Multiplication
/ / Division
% % Modulus
Assignment Operators
Assigns right operand in
= =
left operand i.e. a=$b
Operators
Relational Operators – for Numeric
Bash
Operator Description
Operator
= or == == Equal
!= != Not equal
str1 is less than
str1 < str2 <
str2
str1 is greater
str1 > str2 >
str2
Operators
Boolean Operators
- (Subtraction) Subtracts right hand operand from left hand operand `expr $a - $b` will give -10
* (Multiplication) Multiplies values on either side of the operator `expr $a \* $b` will give 200
/ (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2
% (Modulus) Divides left hand operand by right hand operand and `expr $b % $a` will give 0
returns remainder
= (Assignment) Assigns right operand in left operand a = $b assign value of b into a
== (Equality) Compares two numbers, if both are same then [ $a == $b ] would return false.
returns true.
!= (Not Equality) Compares two numbers, if both are different then [ $a != $b ] would return true.
returns true.
Relational Operator Example (e.g. a=10, b=20)
-le Checks if the value of left operand is less than or equal to the value of right
operand; if yes, then the condition becomes true. [ $a -le $b ] is
true.
Boolean Operator Example (e.g. a=10, b=20)
!= Checks if the value of two operands are equal or not; if values are not [ $a != $b ] is
equal then the condition becomes true. true.
-z Checks if the given string operand size is zero; if it is zero length, then it [ -z $a ]
returns true. is not true.
-n Checks if the given string operand size is non-zero; if it is nonzero length, [ -n $a ]
then it returns true. is not false.
str Checks if str is not the empty string; if it is empty, then it returns false. [ $a ]
is not false.
expr Command
• The expr (external program) command in Unix evaluates a given
expression and displays its corresponding output.
• It is used for:
• Basic operations like addition, subtraction, multiplication, division, and
modulus on integers.
• Evaluating regular expressions, string operations like substring, length of
strings etc.
• Syntax : expr EXPRESSION
Backti
ck
num1=10
$ expr 3 + $ expr 3 \* num2=20
5 5 sum=`expr $num1 + +
sum=`expr $num1
output: output: $num2`
8 15 $num2`
echo $sum
output: 30
if Statement
• If statements use the if, then, else, and fi keywords.
• The condition goes in square brackets.
🞂 Syntax :
if [ <some test> ]
if [ $no -gt 100 ] then
<commands> then
fi echo "Greater than
The spaces
before and
100"
after the fi
square
brackets
[ ] are
required.
if Statement
if [ $a -gt $b ] if [ $a -ne $b ]
then then
echo “A is Greater echo “A is not eqal to
than B" B"
fi fi
if [ `expr $mid1_total +
$mid2_total` -gt 50 ]
then
echo “Total Marks is Greater than
50"
fi
if…else Statement
if [ $a -eq $b ]
if [control then
command] echo "a is equal to b"
then else
<statements-1> echo "a is not equal
to b"
else fi
<statements-2>
fi
if [ $i -eq 5 ]
then
echo "Value of i is 5"
elif [ $i -eq 10 ]
then
echo "Value of i is 10"
elif [ $i -eq 20 ]
then
echo "Value of i is 20"
elif [ $i -eq 30 ]
then
echo "Value of i is 30"
else
echo "Value of i is not equal to
5,10,20 or 30"
fi
case Structure
• Use the case statement for a decision that is based on
multiple choices. echo "Enter number:"
case $word in
pattern1) c read num
case $num in
ommand-list1 1)
;; echo "It's one!"
pattern2) ;;
command-list2 2)
;; echo "It's two!"
;;
patternN) 3)
command-listN echo "It's three!"
;; ;;
*) *)
;; echo "It's something else!"
;;
esac esac
Repetition Constructs
213
while loop
until
It keeps looping as long as the
[ condition ] condition is false (opposite of
do while construct)
command1
command2
…..
.....
done
for loop using “in” and list of values
1
2
3
4
5
Decimal:
100
Octal: 144
Hex: 64
select loop
a=10
b=2
c=12
d=5
sum=$(( a + b + c + d))
avg=`echo $sum / 4 | bc –l`
printf %0.3f “$avg”
OUTPUT :
7.250
Division using bc Command
# get the first number
printf "Enter first integer number: "
read a
# get the second number
printf "Enter second integer number: "
read b
# if b is 0
if [ $b == 0 ]
then
printf "Division by 0 not allowed.\n"
exit # exit the script
fi
# perform division
result=`expr "$a / $b" | bc -l`
printf "%d / %d = %.5f\n" "$a" "$b"
"$result"
Division using bc Command
Find user su – pritesh
Create group sudo groupadd groupname
Show group getent group
getent group <groupname>su