1)
2
3)
4)
Unix Commands
cal:- Displays acalendar
Syntax:- cal [options] [ month ] [year]
Description :-
cal displays a simple calendar. If arguments are not specified, the current month is
displayed. The switching options are as follows:
-1 | Display single (current) month output. (This is the default)
=3 | Display previcurrentinext month output
=5_| Display Sunday as the firstday ofthe week (Thisisthe default.)
-m | Display Monday as the first day of the week
-{_ [Display Julian dates (days one-based, numbered from January 1)
~y | Display a calendar for the current year
Example:
$cal
or
$cal 02 2016
Feb 2016
Su. Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 1 12 «13
14°15 «#16 «17 «18 «19 «20
21 22 23 24 «425 «26 27
28 29
clear :-It clears the terminal screen
Syntax :- clear
Description :-
Clear clears your screen if this is possible, including its scroll back buffer.
1 Clear ignores any command-line parameters that may be present.
pwd :- Displays path from root to current directory
Syntax :- pwd [options]
Example:
$ pwd
/home/kumar/progs
cd: Itis used to change the directory.
Syntax :- cd [directory]
DescriptioUnix Commands
Usedto goback onedirectory onthe majority ofall UNIX shells. Itisimportant
that the space be between the cd and directory name or.
Example:-
$ pwd
/home/kumar
$ cd progs
$ pwd
/home/kumar/progs
Sed.
Jhome/kumar
5) Is:-Liststhecontents ofadirectory
Syntax -- Is [options]
Shows you all files, even files that are hidden (these files begin with a dot)
List all files including the hidden files. However, does not display the working
directory (.) or the parent directory (..).
Ifan argument is a directory it only lists its name not its contents
Shows you huge amounts of information (permissions, owners, size, andwhenlast
modified.)
Displays a slash (/) in front of all directories
Reverses the order of how the files are displayed
Includes the contents of subdirectories
Example:-
y
y
y
v
y
$Is-1
-tw-r—-- 1 student student 23 Jan 16 15:27 file1 txt
Field Explanation:
Iffirst character is — then itis normal file
Ifitis d then itis directory
Field 1 - File Permissions: Next 9 character specifies the files permission, Each 3
characters refers to the read, write, execute permissions for user, group and world
inthis example, -rw-+— indicates read-write permission for user, read permission
for group, and no permission for others.
Field 2-Number of links: Second field specifies the number of links for that fie. In
this example, 1 indicates only one link to this file.
Field 3 - Owner: Third field specifies owner of the file. Inthis example, this fileis
owned by username’student’
Field4—Group:Fourthfieldspecifiesthe group ofthefile. Inthisexample, thisfile
belongs to "student’ group,
Field 5— Size: Fifth field specifies the size of file. In this example, '13' indicates the8)
7
8)
9)
Unix Commands
file size.
> Field6—Last modified date & time: Sixth field specifies the date andtime ofthe
last modification of the file. In this example, ‘Jan 16 15:27' specifies the last
Modification time of the file.
> Field7—Fileordirectoryname: The lastfieldis the name of thefile or directory.
In this example, the file name is [Link]
exit :-Itis used to terminate a program, shell or log you out of a network normally.
Syntax :- exit
echo :-It prints the given input string to standard output.
Syntax :- echo string
Example:-
$ echo “hi.. hello unix”
hi.. hello unix
who :-who command can list the names of users currently logged in, their terminal, the
time they have been logged in, andthe name of the host fromwhich they haveloggedin
Syntax :- who [options] [file]
Description:-
‘am i | Plintthe username ofthe invoking user, The’am'and'T mustbe space
separated.
-b Prints time of last system boot.
-d print dead processes.
-H__| Print column headings above the output.
Includeidletimeas HOURS: MINUTES. Anidletimeof. indicatesactivity |
within the last minute.
=m_| Same as who am i
4 Prints onlythe usernames and the user count/total noofusersloggedin. |
Example :-
$ who
dietstaffpts/1 2016-02-20 22:42 (:0.0)
dietstaffpts/2 2016-02-20 09:30 (:0.0)
Here first column shows user name, second shows name of the terminal the user
isworkingon. Third& fourth column showsdateandtime oflogging, lastcolumn
shows machine name.
who am i:- Print effective userid
Syntax :- who am i10)
11)
12)
Unix Commands
Description: - Print the user name associated with the current effective user id.
Example :
$ who am i
dietstaffpts/3 2016-02-10 08:52 (:0.0)
Here first column shows user name, second shows name of the terminal the user
isworking on. Third& fourth columnshowsdateandtime flogging, lastcolumn
shows machine name.
mkdir:- This command is used to create a new directory
Syntax :- mkdir [options] directory
Description :-
m Set permission mode (as in chmod)
Pp No error ifexisting, make parent directories as
needed
Print a message for each created directory
directory |The name of the directory that you wish to
create
Example:-
$ mkdir aaa
The above command will create directory named aaa under the current directory.
We canalso create number of subdirectories with one mkdir command.
rmdir:- Itis used to delete/remove a directory and its subdirectories.
Syntax :- rmdir [options..] Directory
Description :-
It removes only empty directory.
Allow users to remove the directory and its parent directories which become
empty.
be:- be commandis used for command line calculator. Itis similar to basic calculator. By
using which we can do basic mathematical calculations.
‘Syntax :- bc [options]
Description :-
© be is a language that supports arbitrary precision numbers with interactive
execution of statements.
bc starts by processing code from all the files listed on the command line in the
orderlisted. Afterallfiles have been processed, bcreads fromthestandardinput.
Alll code is executed as itis readUnix Commands
- | To avoid bc welcome message
=| [Toinclude math library functionalities
Example:-
$be
bc 1.06 Copyright 1991-1994, 1997,1998, 2000 Free Software Foundation, Inc. This
is free software with ABSOLUTELY NO WARRANTY. For details type ‘warranty’. 2"3
6
The above command used is for mathematical calculations.
$be-1
boc 1.06 Copyright 1991-1994, 1997,1998, 2000 Free Software Foundation, Inc. This
is free software with ABSOLUTELY NO WARRANTY For details type ‘warranty’ 1142
13,
© The above command displays the sum of '11+2'
$ be [Link]
bbc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This
isfree softwarewith ABSOLUTELY NOWARRANTY Fordetailstype warranty’. 13,
‘calc. bet file have the following code:11+2. Getthe input from file and displaysthe
output
13) uname:- Itis used to print system information.
Syntax :- uname [options]
Description :-
Print certain system information.
-s__| print the kernel name
=n__[ print the network node hostname
=__| print the kernel release
-v__| print the kernelversion
=m_| print the machine hardware name
-o [print the operating system
Example:-
$ uname
Linux
14) tty:- Print the file name of the terminal connected to standard input.
Syntax :- tty
Description :-
tty writes the name of the terminal that is connected to standard input onto15)
16)
Unix Commands
standard output,
Command is very simple and needs no arguments.
Example ~
Stty
Istudentitty10
stty:- Change and print terminal line settings.
Syntax :- sty
Description :-
stty sets certain terminal I/O modes for the device that is the current standard
input.
Without arguments, it writes the settings of certain modes to standard output.
Example --
$sty
speed 19200 baud, 25 rows, 79 columns
kill =4U
cat:- Itis used to create, display and concatenate file contents.
Syntax : - cat [options] [FILE]...
Description :-
“A | Show all,
-b_| Omits line numbers for blank space in the output,
=e _| A$ character will be printed at the end of each line prior to a new line,
-E_| Displays a $ (dollar sign) at the end of each line
=n_| Line numbers for all the output lines.
-s_| Ifthe output has multiple empty lines it replaces it with one empty line.
=T_| Displays the tab characters in the output,
Non-printing characters (with the exception of tabs, new-lines and formeeds) are
printed visibly.
Two basically three uses of the cat command.
1) Create new files.
2) Display the contents of an existing file.
3) Concatenate the content of multiple files and display.
Example :-
$ cat filet.c
Above syntax will display the content of fle1.c
$cat> filet.c
Above syntax creates file1.c and allow us to insert content for this file.Unix Commands
After inserting content you can use ctrl+d to exit the file.
Iffile with same name exist then it will overwrite that file
$ cat file1.c
process management
memory management
file mgmt
$ cat filet.c >> file2.c
It can concatenate the contents of two files. For this you have to useappend
output redirection operator.
The contents of [Link] be appended to file1.c.
17) cp:-cp command copy files from one location to another. Ifthe destination is an existing
file, then the file is overwritten; ifthe destination is an existing directory, the file is copied
into the directory (the directory is not overwritten).
Syntax :- cp [options]... source destination
Description:-
Here, after cp command contents of both source file and destination file files are
the same.
Itwill copy the content of source file to destination file.
> Ifthe destination file doesn't exist, it will be created.
Ifit exists then it will be overwritten without any warning,
Ifthere is only one file to be copied then destination can be the ordinary file orthe
directory file,
archive files
force copy by removing the destination file ifneeded
interactive - ask before overwrite
link files instead of copy
follow symbolic links
no file overwrite
u update - copy when source is newer than dest
Example:-
$ cp file1 file2
The above cp command copies the content of file php to file2. php.
Copy folder and subfolders:
$ cp-R scripts scripts1
‘The above cp command copy the folder and subfolders from scripts to scripts1
18) _rm:-Itis used to remove/delete the file from the directory.Unix Commands
Syntax :- rm [options..] [file|directory]
Description :-
Files can be deleted with rm. It can delete more than one file with a single
invocation. Fordeletinga single file wehaveto userm commandwith filenameto
be deleted,
> Deleted file can't be recovered. rm can't delete the directories. If we want to
remove all the files from the particular directory we can use the * symbol
-¥ [Ignore nonexistent files, and never prompt before removing.
-i_| Prompt before every removal. |
Examiple :-
$ rm [Link]
Remove the file [Link]. Ifthe fie is write-protected, you will be prompted to
confirm that you really want to delete it.
$rm*
Remove all files in the working directory. If it is write-protected, you will be
prompted before rm removes it
$ rm -f [Link]
Remove the file [Link], You will not be prompted, even if the file is write-
protected; if rm can delete the file, it will
$ rm -f*
Remove all files in the working directory. rm will not prompt you for any reason
before deleting them.
$rm-i*
Attemptto remove every file in the working directory, but prompt before each file
to confirm,
19) _mv:- Itis used to move/rename file from one directory to another.
Syntax :- mv [options] oldname newname
Description :-
my command which is short for move.
._ mvcommandisdifferentfromcp commandasitcompletely removes the filefrom
the source and moves to the directory specified, where cp command just copies
the content from one file to another.
> mvhastwo functions: it renames a file and it moves a group of files to a different
directory. Mv doesn'tcreatea copy of the file, it merely renames it. No additional
‘spaceis consumedondiskduringrenaming. Forexampleifwerenameafileosto
081 and then ifwe try to read file os we will get error message as it is renamed to
081 there is no existence of file named os.Unix Commands
F mv will move the file(s) without prompting even ifitis writing over an
existing target. Note thatthisis the defaultifthe standard inputis nota
terminal
ai Prompts before overwriting another file
Example:-
$ cat filet
Memory
Process
Files
$ mv filet file2
rename file1 tofile2
> If the destination file doesn't exist it will be created. mv can also be used to
renamea directory. A group of files can also be moved toa directory. mv doesn't
prompt for overwriting destination file if it exists.
20) ni
nl numbers the lines in a file
Syntax: - nl [OPTION] [FILE]
Example
Scat [Link]
apples
oranges
potatoes
lemons
garlic
Snl [Link]
1 apples
2 oranges
3 potatoes
4 lemons
5 garlic
Inthe above example, we use the catcommandtodisplay the contents [Link].
Thenwe use nlto number each line and display the resultto standard output.
$nl [Link] > [Link]
Scat [Link]
1 apples
2 oranges
3 potatoes
4 lemons21)
Unix Commands
5 garlic
Inthe aboveexample, werunthe samen|command, butredirectthe outputtoa
new file, [Link]. Then we use cat to display the results.
cut :- cut command is used to cut out selected fields of each line of a file. The cut
command uses delimiters to determine where to split fields,
Syntax :- cut [options] filename
Description
file | A path name of an input file, Ifno file operands are specified, or ifa file
operand is -, the standard input will be used
~c_| The list following -c specifies character positions
-d_| The character following -d is the field delimiter
-f_ | select only these fields on each line
=b_| Select only the bytes from each line as specified in LIST
Example =
For example, let's say you have a file named [Link] which contains the following
text:
one two three four five
alpha beta gamma delta epsilon
Inthisexample, each of these words is separated by a tab character, not spaces.
The tab character is the default delimiter of cut, so it will by default consider a
field to be anything delimited by a tab.
To "cut" only the third field of each line, use the command:
$ cut -d’ ‘£3 [Link]
three
gamma
let's say you want the third field and every field after it, omitting the first two
fields. In this case, you could use the command:
$ cut -d’ '-f3- [Link]
three four five
gamma —_ delta. epsilon
$ cut -c 3 [Link]
r
m
For example, to output only the third-through-twelfth character of every line of
[Link], use thecommand:
$ cut -c 3-12 [Link]
e two thre
pha beta gUnix Commands
22) paste:-pastecommandisusedtopastethe content from [Link]
used to set column format for each line.
Syntax :- paste [option] file
Paste prints lines consisting of sequentially corresponding lines of each specified
file. In the output the original lines are separated by TABs. The output line is
terminated with anewline.
-d__ | Specify of a list of delimiters.
-s__| Paste one file at a time instead of in parallel |
File | Apathname ofan input file. If-is specified for one or more of the file s, the
standard input will be used.
Example:-
$cat>a
Unix
Linux.
Windows
$cat>b
Dedicated server
Virtual server
$ paste ab
Unix. Dedicated server
Linux Virtual server
Windows
$ paste -d"|"ab
Unix Dedicated server
Linux|Virtual server
Windows|
$ paste -s ab
Unix Linux Windows
Dedicatedserver Virtual server
$ paste -s -d"," ab
Unix,Linux, Windows
Dedicated server, Virtual server
23) more:-Displaystext one screen at atime.
Syntax :- more [options] filename
Description :-
More command displays its output a page ata time. For example we are having a24)
Unix Commands
big file with thousands of records and we want to read that file then we should
usemore command. Considera filenamed employeesthen wewilluse following
command to read its contents a page at atime.
~c_| Clear screen before displaying
-e_| Exitimmediately after writing the lastline of the lastfile in the argumentlist.
=n_| Specify how many lines are printed in the screen for a given file.
+n | Starts up the file from the given number.
Example:-
cm
$ more -c [Link]
Clears the screen before printing the file
$ more -3 [Link]
Prints first three lines of the given file. Press Enter to display the file line by line.
$ more +/"hope" [Link]
Display the contents of file [Link], beginning at the first line containingthe
string "hope",
p:- It compares two files and tells you which line numbers are different.
Syntax : - cmp [options..] filet file2
Description :-
-e
> _Let's create a file named os2. And use cmp command to compare os and os'files.
Output differing bytes as characters.
Print the byte number (decimal) and the differing byte values (octal) for each
difference.
8
Prints nothing for differing files, return exit status only.
=e
Output differing bytes as characters.
Example:-
$ cat filet
memory
process
files
$cat>file2
memory
process
files mgmt
$ cmp filet filez
File1 file2 differ: char 21, line 3
The two files are compared byte by byte and the location of the first mismatch is
‘echoed to the screen. cmp doesn’t bother about possible subsequent mismatches.
vUnix Commands
25) _comm:- compare two sorted files line by line
Syntax:
somm [option]... FILE1 FILE2
Description :~
y
7
Compare sorted files FILE1 and FILE2 line by line.
Requirestwosorted files and listsdifferingentriesindifferentcolumns. produces
three text columns as output:
1Linesonlyinfilet.
2Linesonlyinfile2.
3Linesinbothfiles.
-1_[ suppress lines unique to FILET
-2_| suppress lines unique to FILE2
-3 | suppress lines that appear in both files
For example let's create two files named file and file2 with following data.
$ cat> filet
[Link]
chanchalsanghvi
[Link]
sumit [1] + Stopped
$ cat> file2
anilaggarwal
barunsengupta
[Link]
lalit
Now let's use comm. Command with these two files.
$commfilet file2
anilaggarwal
barunsengupta
[Link]
chanchalsanghvi
lalit
[Link]
sumit
Inthe above outputwe can see that first column contains two lines unique to the
first file and second column contains three lines unique tothe secondfile andthe
thirdcolumncontainstwolinescommontoboththefiles. Comm. CanproducetheUnix Commands
single column output using 3 options -1,-2 or -3. To drop a particular column,
simply use its column number as a prefix.
Example :-
$ cat filet
fle
fc
£3.
fac
15.c
$ cat file2
fic
3.c
fac
6.
fc
Now, When you run the comm command on these files, this is what you get:
$ comm filet file2
fle
fc
Be
fc
f5.c
f6.c
f7.c
The outputis splitin 3 columns. Columnt indicates files which are uniquein filet,
column 2 indicates files unique to file2. Column 3 indicates files common between
[Link] command provides some real good options with which you can filter
the outputbetter.
Now, say you want to find out only the list of files which were there in the older
version but not in the newer version:
$ comm -23 filet file2
fe
5.c
1 The option-23 indicates to remove the second and third columns fromthe comm
command output, and hence we are left with only the first column which is the
files unique infilet
Similarly, to find out the list of files which were not there in the old version, but
has been added in the new version:Unix Commands
$ comm -13 filet file2
f6.c
fle
As explained above, -13 option tells to remove the first and third columns from
the comm output.
Finally, to know the list of files which have been retained, or common inboth the
versions:
$ comm -12 filet file2
fc
B.c
fac
When you apply comm command on files, the files should be sorted. This
command works only on sorted files.
28) diff: Itis used to find differences between two files.
Syntax :- diff [options..] fileone filetwo
Deseri
iption :-
Diffis the third command that can be used to display file differences. Unlike its
fellowmembers cmp and comm. ,italso tells uswhich lines in one file have tobe
changed to make the two files identical
-b
Ignoreany changes which onlychangetheamountofwhitespace (suchas
spaces or tabs)
Ww
Ignore whitespace entirely.
B
y
ignore blank lines when calculating differences
Display output in two columns.
Ignore changes in [Link] upper- and lower-case letters equivalent,
Example:-
$ cat [Link]
aaa
bbb
ccc
ddd
eee
fff
ggg
$ cat [Link]
bbb
cc
ddd
eee
fffUnix Commands
ggg
hhh
$ diff [Link] [Link]
1d0
cc
Ta?
> hhh
Lines like "1d0" and "3c2" are the coordinates and types of the differences
between the two compared files, while lines like "< aaa" and "> hhh" are the
differences themselves.
diff change notation includes 2 numbers and a character between them
Characters tell you what kind of change was discovered:
+ d-alinewas deleted
© c-aline was changed
* a-alinewasadded
Numberto the left of the character gives you the line number in the original (first)
file, and the number to the right of the character tells you the line number in the
second file used in comparison.
So, looking at the two text files and the diff output above, you can see what
happened:
140
ee
And this means that the line number 3 has changed. You can see how this
confirms thattin the firs file the line was "ccc", and in the seconditnowis"cc"
Ta?
> hhh
Finally, this confirms that one new line appeared in the second file, i's "hhh" in
the line number 7.Unix Commands
27) chmod:-chmod command allows youto alter/ Change access rightsto files and
directories.
Syntax:- chmod [options] [MODE] FileName
> chmod command is used to set the permissions of one or more files for all three
categories of users (user,group and others). It can be run only by the user and
super user. Command can be used in two ways. Let's first take a look at the
abbreviations used by chmod command
Category | Operation Permission
u] User [+ | Assigns permission] r | Read permission
g| Group |- | Removes w | Wile permission
permission
0} Others |= | Assigns absolute |x | Execute permission
File Permission :
# | File Permission
0 | none
execute only
write only
write and execute
ead only
Tead and execute
Tead and write
7__[ set allpermissions
THT
o
Relative permissions
When changing permissions in a relative manner, chmod only changes the
permissions specified in the command line and leaves the other permissions
unchanged. In this mode it uses the following syntax:
> let's first check the permission of file shortlist. It shows read/write permission
Let's assign execute permission to this file for owner.
$is-l
-1w-t--—1 shortlist None 241 Feb 21 04:02
$ chmod u+x shortlist
$s -l
-rwxr-r~ 1 shortlist None 241 Feb 21 04:02
Here chmod uses expression u+xmeans — ushows user category thatis user, +
shows we need to assign the permission and x shows execute permission.
Sameway we can assign other permissions.
728)
28)
Unix Commands
Absolute permissions
> Sometimes youdon'tneedtoknowwhatafile'scurrentpermissionsare, butwant
tosetall nine permission bits explicitly. The expression used by chmod hereis a
string of three octal numbers. Each type of permission is assigned a number as
shown
Read permission-4
Write permission-2
Execute permission -1
For each category we add numbers that represent the assigned permission. For
instance , 6 represents read and write permission , and 7 represents all
permissions.
Example :
$ chmod 666 myfile or(chmod u=rw,g=rw,o=rwmyfile) shortlist
Shows read and wrie (4 +2) permissions for all three types of users.
chown:- Command for system V that changes the owner of file,
Syntax:-chown[options]newownerfilenameldirectoryname
Description:-
Change the permission on files thatare in the subdirectories ofthe directory that
you are currently in.
Change the permission for each file.
Prevents chown rom displaying errormessages when itisunabletochangethe
ownership of a file.
Example :-
$ Is 1 [Link]
-w-t=t~ 1 root root 0 Jan 31 05:48 demo. txt
$ chownvivek [Link]
-Iwet--t-- 1 vivek root 0 Jan 31 05:48 [Link]
chgrp:- chgrp commandis used to change the group of the file or directory. This is an
admin command. Root user only can change the group of the file or directory.
Syntax:- chgrp [options] newgroup filename/directoryname
Descriptio
R
Change the permission onfiles thatarein the subdirectories ofthe directory
that you are currently in.
-6
Change the permission for each file.
f
Force. Do not report errors.
Example =
$ Is -I [Link]
-1w-r—t- 1 root root 0 Jan 31 05:48 demo. txt30)
31)
32)
Unix Commands
$ chgrp vivek [Link]
-1w-t-t— 1 root vivek 0 Jan 31 05:48 [Link]
file:- file command tells you if the object you are looking at is a file or a directory.
Syntax:- file [options] directorynamerfilename
Description:-
File commandisusedto determine the type of file, especially ofan ordinary ile
We can use it with one or more filenames as arguments. For example we can use
file command to check the type of the os1 file that we have created.
$ file os1
os1: short english text
finger:- finger command displays the user's login name, real name, terminal name and
write status (as a "*" after the terminal name if write permission is denied), idle time,
login time, office location and office phone number.
Syntax:- finger [username]
Description :~
-I___| Force Tong output format
-s__| Force short output format
Example :-
$ finger rahul
Login:abe Name: (null)
Directory: /home/abe Shell: bin/bash
Onsince Mon Nov 1 18:45 (IST) on:0 (messages off)
Onsince Mon Nov 1 18:46 (IST) on pts/0from:0.0
Newmailreceived Thu Feb 7 10:33 2015 (IST)
Unreadsince MonFeb812:592016 (IST)
No Plan.
sleep:-Delay for a specified amount oftime
Syntax :- sleep NUMBER[SUFFIX]
Description:-
The sleep command pauses for an amount of time defined by NUMBER.
1 SUFFIXmaybe"s’ forseconds (the default), "m"forminutes, "h’ for hours, of
fordays.
Example :-
To sleep for 5 seconds, use:
$sleep 5
To sleep for 2 minutes, use:Unix Commands
$ sleep 2m
To sleep for 3 hours, use:
$ sleep 3h
1 Tosleep for 5 days, use:
$ sleep 5d
33) _kill:-kill command is used to kill the background process.
Syntax:- kill [options] pid
Description :-
34)
35)
The commandkillsends the specified signal to the specified process or process
group.
Ifno signalis specified, the TERM signalis sent. The TERM signal willkill processes
whichdo not catch thissignal.
For other processes, it may benecessary touse the KILL (9) signal, since this signal
cannot be caught.
pid. Specify the list of processes that kill should signal
s send the specified signal to the process
- [list all the available signals.
Force to kill a process.
users :- users command displays currently logged in users.
Syntax:- users
Output:
$ users
dietstaff dietstaff
ps:- Itis used to report the process status. ps is the short name for Process Status
Syntax:- ps [options]
Description :-
-a | Listinformationaboutall processes most frequently requested: allthose except
process group leaders and processes not associated with a terminal
-A_| List information for all processes. Identical to -e, below
~f_| Generate a full listing
-i_| Print session ID and process group ID.
-I_| Generate a long listing
Example =
$psUnix Commands
PIDTTY TIME CMD
291 console 0:00 bash
36) In--Incommandis used tocreate link toafile (or) directory. Ithelpsto provide soft ink
for desired files,
Syntax:- In [options] existingfile(or directory)name newfile(or directory)name
Description:-
What Is A Link?
Alinkis an entry in your file system which connectsa filename to the actual bytes
of data on the disk. More than one filename can"link"tothe samedata, Here'san
example. Let's create a file named file1 txt:
$ echo "This is a file." > [Link]
This command echoes the string "This is a file". Normally this would simply echo to
our terminal, but the > operator redirects the string's text to a file, in this case
file .txt
When this filewas created, the operating system wrote the bytes to allocation on
the diskand also linked that datatoa filename, file1 txtsothatwe can efertothe
file in commands and arguments.
If you rename the file, the contents of the file are not altered; only the
information that points to it
The filename and the file's data are two separate entities.
Filet txt
NU
This isa file’
Whatthe link command does is allow us to manually create a link to file data that
already exists,
So, let's use link to create our own linkto the file data we just created. Inessence,
we'll create another file name for the data that already exists.
$ link filet txt [Link]
The important thing to realize is that we did not make a copy of this data. Both
filenames pointto the same bytes of data on the disk. Here's anillustrationtohelp
you visualize it
[Link] [Link]
N74Unix Commands
“This is a file”
Ifwe change the contents of the data pointed to by either one of these files, the
otherfile's contents are changed as well. Let'sappenda line to one ofthem using
the >>operator:
$ echo "It points to data on the disk." >> [Link]
Now let's look at the contents of file1 txt:
$ cat [Link]
This is a file.
now let's look at the second file, the one we created with the link command.
§ cat [Link]
This is a file
In, by default, creates a hard link just like link does. So this In command
$ In filet txt [Link]
Itis the same as the following link command. Because, both commands createa
hard link named [Link] which links to the data offile1 txt.
$ link filet txt file. txt
However, we can also use In to create symbolic links with the -s option. So the
command:
$In-s [Link] [Link]
Itwill create a symbolic link tofile1 .txtnamed [Link]. In contrast to our hard link
‘example, here's an illustration to help you visualize our symboliclink:
[Link] «| [Link]
\
‘Thisis a file’
You should also be aware that, unlike hard links, removing the file (or directory)
thata symlink(symboliclink\) points towillbreak thelink. Soifwe create filet txt:
$ echo "This isa file." > [Link]
Now, create a symbolic link to it:
$In-s [Link] [Link]
we can cat either one of these to see the contents:37)
38)
Unix Commands
$ cat [Link]
This is a file
$ cat [Link]
This is a file.
But, ifwe remove filet txt:
$ rm [Link]
we can no longer access the data it contained with our symlink:
$ cat [Link]
cat: file2 txt: No such file or directory
3 Makes it so that it creates a symbolic link
f Ifthe destination file or files already exist, overwrite them. |
head:- head commands used to display the first ten lines of afile, and also specifies how
many lines todisplay.
Syntax:- head [options] filename
Description:-
Head command displaysthe top of thefile. When used withoutan option it
displays the first ten lines of the file.
n To specify how many lines you want to display.
The number option-argument must be a decimal integer whose
sign affects the location in the file, measured in lines.
The number option-argument must be a decimal integer whose
sign affects the location in the file, measured in bytes.
-n number
-c number|
Example :-
$ head [Link]
Display the first ten lines of [Link].
$ head -15 [Link]
Display the first fifteen lines of myfile. txt.
$ head -c 20 [Link]
Willoutputoniy the firsttwenty bytes (characters) of [Link], Newlinescountas
asingle character, so ifhead prints out anewline, itwill countitas a byte.
$ head -n 5K [Link]
Displays the first 5,000 lines of [Link].
tail:-tailcommandis used to display the last or bottom partof the ile. By defaultit
displays last 10 lines of a file.
Syntax :- tail [options] filename
Description:Unix Commands
A To specify the units of lines.
-b To specify the units of blocks
n To specify how many lines you want to display.
“¢number| Thenumberoption-argumentmustbeadecimalintegerwhose
sign affects the location in the file, measured in bytes.
Thenumberoption-argumentmustbeadecimalintegerwhose
-n number
sign affects the location in the file, measured in lines.
Example: -
$ tail [Link]
It displays the last 10 lines of ‘index. txt’
$ tail -2 [Link]
C Itdisplays the last 2 lines of [Link]’.
$ tail -n 5 [Link]
It displays the last lines of index. txt.
$ tail -c 5 [Link]
It displays the last 5 characters of ‘index. txt’
39) sort: Itis used to sort the lines in a text file.
Syntax:- sort [options] filename
-b
Ignores spaces at beginning of the line
Check whether inputis sorted; donot sort
Sorts in reverse order
Ifline is duplicated only display once
Example:-
Reverse the result of comparisons
$ cat > [Link]
apples
oranges
pears
kiwis
bananas
$[Link]
apples
bananas
kiwis
oranges
pears
Note that this command does not actually change the input file, [Link]. Ifyou
want to write the output to a new file, output txt, redirect the output like this:Unix Commands
$ sort [Link] > [Link]
it will not display any output, but will create the file [Link] with the same
sorted data from the previous command. To check the output, use the cat
command:
$ cat [Link]
apples
bananas
kiwis
oranges
pears
Youcanalsouse the built-in sort option -o, which allows you to specify an output
file
$ sort -o [Link] [Link]
Using the -0 option is functionally the same as redirecting the output to a file;
neither one has an advantage over the other.
Sorting In Reverse Order :
Youcanperformareverse-ordersort using the-rflag. For example, the following
command:
$ sort -r [Link]
pears
oranges
kiwis
bananas
apples
Checking For Sorted Order
If you just want to check to see if your input file is already sorted, use the -c
option:
$[Link]
Ifyour datais unsorted, you will receive an informational message reporting the
line number of the first unsorted data, and what the unsorted data is.
40) find:- Finds one or more files assuming that you know their approximate path
Syntax :- find [options] path
Findis one of the powerfulutlity of Unix(or Linux) used forsearching the filesina
directory hierarchy
path A path name of a starting point in the directory hierarchy
-maxdepth | Descend at mostlevels (a non-negative integer) levels of directories
below the command line arguments.
a ignore the case in the current directory and sub-directories,Unix Commands
-size Find file based on size
Example:-
41) unig:
$ find -name "[Link]:
Jokp/sum,java
/[Link]
$ find -iname "sumjava"
JSUM java
Jokp/sum,java
Jsum java
$ find -maxdepth 1 -name "[Link]"
/sum java
Find Files Under Home Directory
Find all the files under /home directory with name [Link].
$ find home -name [Link]
Jnome/[Link]
$find.-size10M
Display files whose size is exactly 10M
$ find . -size +10M
Display files larger than 10M size
$ find -newer "sum,java"
Display the files which are modified after the modification of a give file.
$ find . -perm 777
display the files based on the file permissions.
This will display the files which have read, write, and execute permissions. To
know the permissions of files and directories use the command "Is I".
$ find -name ™" -size +1000k
The system would search for any file in the list that is larger than 1000k.
-Reportorfilter out repeated ines inafile.
Syntax:- unig [option] filename
Description :
Precede each output line with a count of the number of times the line
occurred in the input
‘Suppress the writing of lines that are not repeated in the input
Print all duplicate lines
Avoid comparing first N fields
[Ignore case when comparing
‘Avoid comparing first N characters.
Prints only unique lines42)
Unix Commands
Ww ‘Compare no more than N characters in lines
Example:-
$ cat [Link]
Unix operating system
unix operating system
unix dedicated server
linux dedicated server
Thedefaultbehaviour ofthe uniqcommandistosuppress the duplicateline, Note
that, you have to pass sorted input to the unig, as it compares only successive
lines.
$ unig [Link]
unix operating system
unix dedicated server
linux dedicated server
The -coptionis used to find how many times each line occurs inthe file. Itprefixes
each line with the count.
$ uniq -c [Link]
2unix operating system
1 unix dedicated server
1 linux dedicated server
You can print only the lines that occur more than once in a file using the -d option.
$ uniq -[Link]
unixoperatingsystem
The -D option prints all the duplicate lines.
$ uniq -D [Link]
unix operating system
unix operatingsystem
tr:- Translate characters,
Syntax:- tr [options] sett [set2]
Description:-
~ Complement the set of characters specified by string?
~d Delete all occurrences ofinputcharacters thatare specifiedbysstringt
“3 replaces repeated characters listed in the string? with single occurrence|
Seti__| First string or character to be changed
set2__| Second string or character to change the string?
Example:
Convert lower case letters to upper case
The following tr command translates the lower case letters to capital letters in the43)
Unix Commands
give string
$ echo “linux dedicated server" | tr "[:lowe
LINUX DEDICATED SERVER
$echo ux dedicated server" | tr “[a-z]" "[A-Z]"
LINUX DEDICATED SERVER
The-coptionis used to replace the non-matching characters with another set of
characters.
$ echo "unix"
uaaa
You can squeeze more than one occurrence of continuous characters with single
occurrence. The following example squeezes two or more successive blank spaces
into a singlespace.
$echo"linux server" | tr-s
linux server
© The following examp!
$ echo "linuxserve
Server
[:upper:]"
tr-c
removes the word linux from the string
"| tr-d "linux"
history:-history command is used to list out the recently executed commandsin the
number line order.
Syntax:- history [options]
Description:
The history command performs one of several operations related to recently-
executed commands recorded in a history list. Each of these recorded commands
is referred to as an “event”
Example
To list the recently executed commands
$ history
This command is used to list the history.
To find specific command istory list:
$ history |grep cd
33 cd Pictures!
37 cd
39 cdDesktop/
61 cd/usr/bin/
68 cd
This command is used to list only ed commands from history list
To copy history list to file
clear the history list by deleting all of the entries.Unix Commands
$ history -a [Link]
This command is used to copy history list to history. txt file
To Clear all histo
$ history -c
1. This command can be used to clear all history from history list.
44) write:-Sendamessageto anotheruser.
Syntax:- write person [ttyname]
Description:-
The write utilty allows you to communicate with other users, by copying lines
from your terminal to theirs.
When yourun the write command, the user you are writing to gets a message of
the format:
Message from yourname@yourhost on yourtty at hh:mm
Any further lines you enter will be copied to the specified user's terminal. Ifthe
other user wants to reply, they must run write as well
> When youare done, type an end-of-file or interrupt character. The other user will
see the message ‘EOF’ indicating that the conversation is over
person | Ifyouwishtotalk to someone on your own machine, then personisjustthe
person's login name. If you wish to talk to a user on another host, then
person is of the form 'user@host’
ttyname | Ifyou wish to talk to a user who is logged in more than once, the tlyname
argument may be used to indicate the appropriate terminal name, where
ttyname is of the form 'ttyXX' or'pts/X’.
48) _grep:-Itselects and prints the lines froma file which matches a given string or pattern.
Syntax:- grep [options] pattern [file]
Description:-
This command searches the specified input fully for a match with the supplied
pattern and displaysit
While forming the patterns tobe searched we can use shell match characters, or
regular expressions.
Let us begin with the simplest example of usage of grep.
ai ignore case distinctions
-v__| Invert the sense of matching, to select non-matching lines.
-w__| Selectoniythoselinescontainingmatchesthatformwholewords.
Select only matches that exactly match the whole line.
print a count of matching lines for each input file.
Example46)
47)
Unix Commands
$ grep "Error" [Link]
This searches forthestring"Error"inthe log fileand printsallthelinesthathas
the word "Error"
$ grep "stri let file2
1 Searching for a string in multiple files.
$ grep i "UNix" [Link]
The -i option enables to search for a string case insensitively in the give file. It
$ grep -w "world" [Link]
Bydefault, grepmatches the given string/pattern even ifitfoundasa substringin
afile. The -w option to grep makes it match only the whole words.
$ grep -c "sting" [Link]
We can find the number of lines that matches the given string/pattern
$ grep 4 a" *
We can just display the files that contain the given string/pattern
$ grep -n “string” [Link]
Wecanmake the grep commandto display the position ofthelinewhich contains
the matched string in a file using the -n option
pwd:-Displaying your current directory name (Print working directory).
Syntax:-pwd [options]
Description:-
Atthe time of logging in useris placed in the specific directory of the file system,
You can move around from one directory to another, but any point of time, you
are locatedin only onedirectory. Thisdirectoryisknownas yourcurrentdirectory.
pwd command tells your current directory.
Example:-
$ pwd
/home/abc
we:- Word Count (wc) command counts and displays the number of lines, words,
character and number of bytes enclosed in a file.
Syntax: - we [options] [filename]
Description:-
> This command counts lines, words and characters depending on the options used.
It takes one or more filenames as its arguments and displays four-columnar
output. For example let's read our os! file, And we use we command with that
filename.
print the newline counts.
print the word counts. |Unix Commands
-6_| print the byte counts.
-m_| print the character counts.
-L_ | print the length of the longest
line.
Example :-
v
Scat [Link]
Red Hat
Centos
Fedora
Debian
Scientific Linux
OpenSuse
Ubuntu
Xubuntu
Linux Mint
Pearl Linux
Slackware
Mandriva
The ‘we' command without passing any parameter will display a basic result of
“[Link]' file, The three numbers shown below are 12 (number of lines), 16
(number of words) and 112 (number of bytes) of the file.
Swe [Link]
12 16 112 [Link]
To count number of newlines ina file use the option ‘-I, which prints the number
of lines from a given file. Say, the following command will display the count of
newlines inafile. Inthe output the firstfiled assigned as count and second fieldis
the name offile.
$we -I [Link]
12 [Link]
Using '-w' argumentwith ‘we' command prints the number of words inafile. Type
the following command to count the words in a file
$we -w [Link]
16 [Link]
When using options ‘=c' and-m' with ‘wc! command will print the total number of
bytes and characters respectively in a file
$we -c [Link]
112 [Link]
The ‘we'command allow an argument
‘,ittcan be used to print out the length of48)
43)
1)
Unix Commands
longest (number of characters) line in a file, So, we have the longest character line
(‘Scientific Linux’) in a file,
$we -L [Link]
16 [Link]
man:-man command whichis shortformanual, provides in depth information aboutthe
requested command (or) allows users to search for commands related to a particular
keyword.
Syntax:- man commandname [options]
Description :-
-a__| Print a one-line help message and exit.
-k_| Searches for keywords in all of the manuals available.
Example:-
$ man mkdir
Display the information about mkdir command
| (Pipeline command):- Used to combine more than one command. Takes output of 1*
command as input of 2" command.
Syntax:- commmand1] command).
Example:
SIs -I| grep "Feb"
-1 dietstaffdietstaff 336 Feb 19 14:[Link]
(1 dietstaffdietstaff 410 Feb 19 14:[Link]
drwxr-xr-x7 dietstaffdietstaff 4096 Feb 24 09:04 Desktop
drwxr-xr-x7 dietstaffdietstaff 12288Feb 26 07:44Downloads
drwxr-xr-x3 dietstaffdietstaff 4096 Feb 26 08:55 lab
drwxr-xr-x2dietstaffdietstaff 4096 Feb 24 08:00 sheliscript
-Mwer-r—1 dietstaffdietstaff 81 Feb 24 12:[Link]
Explain the basic system administration commands of unix
date :- Prints orsets the date and time.
Syntax :- date[options] [+format] [date]
Description :-
> Display the current date with current time, time zone
> The command can also be used with suitable format specifies as arguments, Each
format is preceded by a + symbol, followed by the % operator, and a single
character describing theformat.
Format
tha [Abbreviated weekday(Tue).Unix Commands
%A | Full weekday(Tuesday)
%b_| Abbreviated month name(Jan).
%8_| Full month name(January).
%o_| Country-specific date and time format
%D_| Date in the format %m/%di%y.
%j_| Julian day of year (001-366).
%p_| String to indicate a.m. or p.m.
%T_| Time in the format %H:%M:%S.
%ht_| Tab space.
%V_[Week number in year (01-52); start week on Monday.
Example:-
$date
Fri Feb 19 [Link] IST 2016
$ date +%m
02
$ date +%h
Feb
$ date +%y
16
$ date +"Date is %D %t Time is %T"
date is 19/02/16 Time is [Link]
To know the week number of the year,
$ date -V
4
> To set thedate,
$ date -s "10/08/2016 [Link]"
> The above command will print Wed Oct 08 [Link] IST 2016
2) wall:~send a message to everybody's terminal.
Syntax :- wall [ message ]
> Wall sends a message to everybody logged in with their mesg(1) permission set to
yes. The message canbe given as an argumentto wail, oritcan be sentto wall's,
standard input. When using the standard input from a terminal, the message
should be terminated with the EOF key (usually Control-D).
> The length of the message is limited to 20 lines.
Example : -
$sudo wall [Link]
> Using the sudo command to run wall as the superuser, sends the contents,
ofmessage txt to allusers.
v
ulimit : Setting limits on file size3)
4
Unix Commands
Syntax: - ulimit [mit]
Description :~
> The ulimit command imposes a restriction on the maximum size of the file that a
users permitted to create , so that there is less wastage of disk space.
passwd:-Itis used to change your password.
Syntax:- passwd
Description :-
> Passwd changes the password or shell associated with the user given by name or
the current user if name is omitted.
> First user has to insert current password. Then new password will be asked
followed by confirm new password field.
> passwd command canalsobeusedtochangethehomedirectory wherethepath
stands for the home directory.
suid : - set user id.
Description :-
> suid (Set owner UserID up on execution) is a special type of fle permissions given
toafile,
> Normallyin Linux/Unixwhenaprogramruns, itinherits access permissions from
the logged inuser.
> suid is defined as giving temporary permissions to a user to run a program/file
with the permissions of the file owner rather that the user who runs it.
> Insimple words users will get file owner's permissions as well as owner UID and
GID when executing a file/program/command
Example:-
$ chmod uts [Link]
$1s-laout
-twsr-xr-rw 1 dietstaff dietstaff 121 Feb 21 11:18 [Link]1)
2)
Unix Shell Scripts
Write a shell script to scans the name of the command and executes it.
Program :~
echo "enter command name"
read cmd
Somd
Output :-
enter commandname
cal
February 2016
Su Mo Tu We Th Fr Sa
12345 6
7 89 12
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29
Writea shell scriptWhich works like calculatorand performs below operations Addition
, Subtract ,Division Multiplication
lif statement
echo " Enter one no."
read nt
echo "Enter second no,”
read n2
echo “[Link]"
echo "[Link]"
echo "3 Multiplication"
echo "[Link]"
echo "Enter your choice
read ch
echo"Sum="$sum
elif[$ch="2"]
then
elif[$ch="3"]
then
1]sum='expr $n1 \* $n2°
echo "Mul = "sum
elif[$ch="4"]
then
su
fi
Output :-
Enter oneno.
32
Enter second no.
12
[Link]
[Link]
[Link]
4 Division
Enter your choice
2
Sub = 20
using while loop and switch statement
ie'y"
while [$i="y"]
do
echo"Enteroneno."
read nt
echo"Enter secondno.”
read n2
echo “[Link]"
echo "2. Subtraction"
echo "3 Multiplication"
echo "[Link]"
echo "Enter your choice”
read ch
case $ch in
4)sum="expr $n1 + $n2°
echo "Sub = "$sum;;
3)sum="expr $n4 \* $2"
Unix Shell Scripts
2]3)
Unix Shell Scripts
echo "Mul = "$sum;;
4)sum="expr$n1 /$n2°
echo "Div="$sum
*Jecho "Invalid choice”;
esac
echo "Douwantto continue ?y/n"
read i
if[ $i!="y"]
then
exit
Output :-
Enter oneno.
32
Enter second no.
22
[Link]
[Link]
[Link]
[Link]
Enter your choice
2
Sub = 10
Douwantto continue ? yin
N
Write a shell scriptto print the pyramid structure for the given number.
Program :-
echo"enterthenumber"
readn
printf "\n"
printt"s;"
done
printf "\n"
done
3]4)
5)
Unix Shell Scripts
Output :-
enterthenumber
4
1
12
123
1234
Write a shell scriptto find the largest among the 3 given numbers.
Program :-
clear
echo"Enterfirstnumber:"
reada
echo "Enter second number: "
read b
echo"Enterthird number:
readc
if[$a-ge $b-a$a-ge $c]
then
echo "Sais largest integer”
elif[ $b -ge $a -a $b -ge $c]
then
echo "Sb is largest integer"
elif [ $c -ge $a -a $c-ge $b]
then
echo "$c is largest integer"
fi
Output :~
Enter first number:
22
Entersecondnumber:
33
Enter third number:
42
44 is largest integer
Writeashellscriptto find factorialofgivennumbern.
Program :~
clear
4|6)
fact="
echo"Enternumbertofind factorial :”
readn
a=$n
#ifentervaluelessthanO
if[$n-le 0]
then
echo “invalid number"
exit
fi
#factorial logic
while [$n-ge 1]
do
fact="exprSfact\*$n’
n="expr$n-1"
done
echo "Factorial for $a is $fact"
Output :-
Enter numberto find factorial
5
Factorial for 5 is 120
Writea shell scriptto printall primenumbers from 1 ton.
Program :-
clear
echo"entertherange”
readn
echo"the primenoare:"
m=2
while [$m-le $n]
do
i-2
flag=0
while [$i-le “expr $m/2°]
do
if['exprsm% $i -eq0]
then
flag=1
break
fi
Unix Shell Scripts
5|7
iF'expr $i +1”
done
if[Sflag -eq 0]
then
echo $m
fi
m="expr$m+1"
done
Output :-
enter the range
10
theprimenoare
2
3
5
7
Write a shell scriptto reverse a number supplied by a user.
Program :-
if[ S#-eq1]
then
if[$1-gt0]
then
num=$1
sumi=0.
while [$num -ne 0}
do
Inum="expr $num % 10°
sumi="expr $sumi \* 10 + $Inum*
num="expr $num / 10°
done
echo"Reverseofdigitsis Ssumiof$1"
else
echo" Numberislessthan0"
fi
else
echo "Insert only one parameter"
fi
Unix Shell Scripts
6]8)
9)
Unix Shell Scripts
Output
bash [Link] 123
Reverse of digits is 321 of 123
WriteashellscripttofindfirstnFibonaccinumbers like:01,1,2,3,5,13,...
Program :-
clear
‘echo"Howmanynumberoftermstobegenerated ?"
readn
x0
y=
iz:
echo" Fibonacci Series up to $n terms:”
echo "Sx"
‘echo "$y"
while [ $i-It $n]
echo"$z"
xy
y=8z
done
Output :-
How many numbers of terms to be generated?
5
Fibonacci Series upto 5terms:
0
1
1
2
3
Write a shell script to check whether the given number is Perfect or not.
Program :-
echo Enter a number
read no
i=1
ans=0
while [ $i-le “expr Sno / 2°]
7|Unix Shell Scripts
do
if{’expr$no% $i -eq0]
then
ans="expr $ans + $i°
fi
i=’expr$it 1”
done
if[$no-eqSans]
then
echo $no is perfect
else
echo $noisNOT perfect
fi
Output :-
Enter anumber
6
6 is perfect
Enter anumber
10
10 is NOT perfect
10) Write a shell script which displays a list of a files in the current directory to which you
have read, write and execute permissions
Program :-
for File in*
do
if[-1$File-a-w$File-a-x$File]
then
echo $File
fi
done
Output
Desktop
Documents
Downloads
lab
Music
8|Unix Shell Scripts
Pictures
Public
shellscript
Templates
Videos
11) Writeashellscriptthatdeletesallthefiles inthecurrentdirectory whichareObytesin
length.
Program :-
clear
find -name"*"-size-1k—delete
echo “files deleted”
Output :-
files deleted
12) Write a shell scriptto check whether the given stringis Palindrome or not,
Program :-
clear
echo "Enter the string:"
read str
echo
len="echoSstr|we-c’
len="exprSien- 1"
=
jF'expr Slen / 2°
while test $i-le $)
do
k= echo $str | cut-c$i
I=echo$str| cut-c$len*
iftest $k = $1
then
echo "String is not palindrome”
exit
fi
iexpr i+ 1°
len="expr $len - 1"
done
echo "String is palindrome"
3]Unix Shell Scripts
Output :-
Enter the string:
abba
String is palindrome
Enter the string:
abe
String is not palindrome
13) Write a shell script o display the digits which are in odd position ina given 5 digit
number
Program :-
echo"EnteraSdigitnumber"
read num
n=1
while [$n-le5]
do
a="echo$num|cut-c$n"
echo $a
n="expr$n+2°
done
Output :-
Entera5digitnumber
12345
1
3
5
14) Write a shell script to check given year is leap year ornot.
Program :-
clear
echo"enter any year"
read num
if['exprSnum % 4° -eq0]
then
if{'expr$num % 100° -eq0-aexpr$num % 400° -ne0}
then
echo"Notaleap year"
else
echo "Leap year"
10]15)
16)
Unix Shell Scripts
fi
else
echo" Notaleap year"
fi
Output :-
enter any year
2016
Leap year
enter any year
2100
Not a leap year
Writea shell scriptto find the value of one number raised tothe power of another.
Program :-
echo "Input number"
read no
echo" Inputpower"
read power
counter=0
ans=1
while [Spower-ne counter]
do
ans="echo $ans \* $no | be”
counter="echo $counter +1 | be’
done
echo "Sno power of $power is Sans”
Output :-
Input number
5
Input power
3
5 power of 3 is 125
Writeashellscriptto display the following detailsin pay listPay slip details, House
rent allowance, Dearness allowance, Provident fund, HRA is to be calculated at the rate
0f20% ofbasic, DAattherate of 40% of basic andPF atthe rate of 10% ofbasic.
Program :-
11]Unix Shell Scripts
ity’
while [$i="
do
echo"Please enter your Basic:"
read basic
echo “PAY SLIP DETAILS"
echo "1. HOUSE RENT ALLOWANCE”
echo "2, DEARNESS ALLOWANCE"
echo "3. PROVIDENT FUND"
echo "your choice:"
read ch
case $ch in
1) hra=" expr Sbasic \* 20 / 100°
‘echo Your HOUSE RENT ALLOWANCE is Rs. $hrar;
2) da="expr Sbasic \* 40 / 100°
echo Your DEARNESS ALLOWANCE is Rs. $da;;
3) pf="expr Sbasic \* 10 / 100°
echo Your PPOVIDENT FUND is Rs. $pf;;
*Jecho"Notavalid choice";
esac
echo"Douwantto continue?"
read i
if[ $i!=
then
exit
fi
done
y']
Output :-
Please enter your Basic:
1000
PAY SLIP DETAILS
1, HOUSE RENT ALLOWANCE
2, DEARNESS ALLOWANCE
3. PROVIDENT FUND
your choice:
i
Your HOUSE RENT ALLOWANCE is Rs. 200
Do u want to continue ?
12]Unix Shell Scripts
17) Writeashellscripttofindsumofdigits ofanumber.
Program :-
clear
echo"enterthenumber"
readn
sum=0
a=$n
while(($n >0))
do
=" expr Sn % 10°
=" expr$sum+$x°
n="expr$n/10°
done
echo "the sum of $a is $sum"
Output :-
enterthenumber
3355
the sum of 3355 is 16
18) Write a shell script that greets the user by saying Good Morning, Good Afternoon, and
Good Evening according to the system time.
Program :-
clear
#hours="date|cut -c 12-13°
hours="date +%H"
if[ Shours-te 12]
then
echo "Good Morning”
elif [ Shours -le 16 ]
then
echo "Good Afternoon"
elif [ hours -le 20 ]
then
echo "Good Evening”
else
echo "Good Night”
fi
Output :~
Good Afternoon
13]19)
20)
Unix Shell Scripts
Write a shell script to generate mark sheet of a student. Take 3 subjects, calculate and
display total marks, percentage and Class obtained by the student.
Program :~
Clear
echo"Enterthe fivesubjectmarksforthestudent”
read s1s2s3
sum1="expr $s1 + $s2 + $s3"
echo "Sum ofS subjects are: "$sumt
per=‘expr Ssum1/3°
echo" Percentage: " Sper
if[ $per-ge 60]
then
echo "You get Distinction"
elif [ $per -ge 50]
then
echo A€ceYou get First classa€+
elif [ $per -ge 40]
then
‘echo "You get Second class’
else
echo "You get Fail"
fi
Output :-
Enterthe fivesubjectmarksforthestudent
78 88.92
Sum of 5 subjects are: 258
Percentage: 86
You get Distinction
Writeashellscriptthatfindstotaino, ofusersandfinds outhowmany ofthemare
currently logged in.
Program :~
cat /etc/passwd>[Link]
set ‘we -| [Link]”
log="who|we -I
echo "There are $1 users in network"
echo "There are $log user loged in right now"
Output :-
There are 49 users in network
Thereare2 userlogedinrightnow
14|