Unix Command
Unix Command
LOGIN: Once the terminal is power on, the following message appears on the screen.
Login:
Every user has an identification name called the user name or login name, which he/she
has to enter at the login prompt.
After entering the login name, prompt for password appears on the screen.
Password:
In response to a valid user name followed by a valid password, the system display the
$ symbol on the screen. Any valid UNIX command can be entered at this stage.
To change password
$passwd
Old Password:
New Password:
Reenter Password:
$
When system will prompt for Old Password, user has to key in at this
prompt, it then prompt for new password twice, user has to key in
according to password naming rules applicable to the system. As
expected, the characters that are key in are not echoed to the terminal
COMMANDS
$date
Wed Feb 02 11:43:34 IST 1994
$
NITTTR, Kolkata 1
Unix Commands
$tty
/dev/ttti15
$
$cal 4 1993
April 1993
S M Tu W Th F S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30
$
$who
general tty01 Feb 02 12:35
subrata ttyi14 Feb 02 12:42
ranjan ttyi15 Feb 02 12:41
$
$who am i
general tty01 Feb 02 12:35
$
To create a file
$cat abc
Welcome to Unix system
NITTTR, Kolkata 2
Unix Commands
$
$ls
abc
xyz
$
NITTTR, Kolkata 3
Unix Commands
No. of Group Date & time of last
links modification
$ls -tl
total 4
-rw-r--r-- 1 general group 18 Feb 02 12:49 xyz
-rw-r--r-- 1 general group 23 Feb 02 12:48 abc
$
NITTTR, Kolkata 4
Unix Commands
No. of characters
$wc -c abc
23 abc
$
No. of words
$wc -w abc
4 abc
$
No. of lines
$wc -l abc
1 abc
$
NITTTR, Kolkata 5
Unix Commands
$cp abc arc
$cp xyz byz
$ls
abc
arc
byz
xyz
$
To Remove a file
$rm crp
$ls
abc
arc
xyz
$
$rm -i arc
arc: ? n
$ls
abc
arc
xyz
$
To explore various options under this feature of UNIX, create a file file5 containing
all lower case alphabet
NITTTR, Kolkata 6
Unix Commands
$head file5
a
b
c
d
e
f
g
h
i
j
$
$tail +5 file5
e
f
.
.
z
$
$tail -5 file5
v
.
.
z
$
NITTTR, Kolkata 7
Unix Commands
$pwd
/usr/general
$
$mkdir dir1
$ls -l
total 6
-rw-r--r-- 1 general group 23 Feb 02 12:48 abc
-rw-r--r-- 1 general group 23 Feb 02 14:48 arc
drwxr-xr-- 2 general group 32 Feb 02 15:28 dir1
-rw-r--r-- 1 general group 18 Feb 02 12:49 xyz
$
$cd dir1
$pwd
/usr/general/dir1
$
$cp /usr/general/abc .
$ls
abc
$
$cd dir1
$rm *
$ls
$cd
$pwd
/usr/general
$rmdir dir1
NITTTR, Kolkata 8
Unix Commands
$ls -l
total 5
-rw-r--r-- 1 general group 23 Feb 02 12:48 abc
-rw-r--r-- 1 general group 23 Feb 02 14:48 arc
-rw-r--r-- 1 general group 18 Feb 02 12:49 xyz
$
To display space consumed by the current directory as well as its sudirectories (in
blocks, block=512 bytes)
$du
48 ./bs
22 ./awk/awwk
150 ./awk
354 .
$
To display space consumed by the each file of the current directory as well as its subdirectories
$du -a
2 ./.profile
2 ./file1
2 ./file2
2 ./bs/b1
2 ./bs/b2
48 ./bs
2 ./awk/country
10 ./awk/t
150 ./awk
2 ./a
2 ./b
354 .
$
Comparing files
To explore various options under this feature of UNIX, create following files
NITTTR, Kolkata 9
Unix Commands
This command compare two files and display the first line number and character
number at which the two files differ
This command compare two files and list lines that are uniq to each files and lines that
are common to both file
To display all files in all the sub-directories begining from current directory (.)
NITTTR, Kolkata 10
Unix Commands
$find . -print
.
./.profile
./.lastlogin
./file1
./file2
./bs
./bs/b1
./bs/b2
./awk
./awk/country1
./awk/t
./awk/awk
./a
./b
$
To display only ordinary files in all directories begining from current directory
To display specific files using wild-card characters (wild-card character must be specified in
double quotes.)
NITTTR, Kolkata 11
Unix Commands
To perform file operations on the files that are located by the find command.
awk/a1
BEGIN {OFS=":"}
{print $1,$2,$3,$4}
awk/a2
BEGIN {w=0;c=0}
{w=w+NF
c=c+length($0)+1}
END {printf " %6d %6d %6d %s\n",NR,w,c,ARGV[1]}
$
To perform file operations on the files that are located by the find command after confirmation
BEGIN {OFS=":"}
{print $1,$2,$3,$4}
To display files that are created or updated on 15 days before the current date
To display files that are created or updated earlier than 15 days before the current date
NITTTR, Kolkata 12
Unix Commands
$find . -mtime +15 -print
./file1
./file2
$
To display files that are created or updated in the last 15 days before the current date
Sorting a file
To explore various options under this feature of UNIX, create following files
$sort file1
238
NITTTR, Kolkata 13
Unix Commands
345
Ln
cut
kill
ls
ps
$
$sort -f file1
238
345
cut
kill
Ln
ls
ps
$
$sort -r file1
ps
ls
kill
cut
Ln
345
238
$
$sort file2
1
100
234
NITTTR, Kolkata 14
Unix Commands
245
88
888
$
This is not a currect solution. Sort command generally compare two lines by ASCII value. To
perform numerical comparison
$sort -n file2
1
88
100
234
245
888
$
See the file file3. It has three fields and they are separated by a :. The : is called field delimeter.
To sort the file file3 on the basis of 2nd field
To explore various options under this feature of UNIX create a file as shown below
NITTTR, Kolkata 15
Unix Commands
To display total no. of lines that matched with the given pattern
NITTTR, Kolkata 16
Unix Commands
print out the lines in 'def'
that contain "to". There are
only three such lines.
$
To display all lines containing 'th' followed by any lower case alphabet
This command allows the examination of files one screenful at a time. Each screenful
is followed by a prompt :. If user press <Return> key, another page is displayed; other
possibilities are discussed below.
q quit
h help
l next line is displayed
-1 previous page is displayed
+1 next page is displayed
NITTTR, Kolkata 17
Unix Commands
number numbered page is displayed
$ last page is displayed
/pattern/ search forward for pattern
?pattern? search backward for pattern
p display previous file
n display next file
s flname save current file in flname
! <cmd> run UNIX command <cmd>
NITTTR, Kolkata 18
Unix Commands
:
.
.
(EOF):
$
$pg +5 file5
e
f
.
.
:
.
.
(EOF):
$
To display file page wise and prompting with a user mention string and page no
q quit
h or ? help
<return> display next line of text
s skip forward 1 line
f skip forward 1 screen
/<regular
expression> search for occurance of regular expression
n searches for occurance of last regular expression
' Go to place where previous seach started
= display current line number
v start up vi editor at current line
:f display current file name and line number
:p go to previous file
:n go to next file
NITTTR, Kolkata 19
Unix Commands
To display file named file5 one screen full at a time
$more file5
a
b
.
.
x
--More--(88%)
.
.
$
$more +5 file5
e
f
NITTTR, Kolkata 20
Unix Commands
.
.
:
.
.
$
To display file one screen full at a time and prompting with a message Hit space to continue,
Del to abort
$more -d file5
a
b
.
.
--More--[Hit space to continue, Del to abort]
.
.
$
Pipes:
A pipe is a way to connect the output of one program to the input of another program. A
pipeline is a connection of two or more programs through pipes. The vertical bar character | tells
the shell to set up a pipeline.
$who | sort
general tty01 Feb 02 12:35
subrata ttyi14 Feb 02 12:42
ranjan ttyi15 Feb 02 12:41
$
$ls | pg
abc
cdb
.
.
: Press any key to see next page
.
.
(EOF)
$
NITTTR, Kolkata 21
Unix Commands
To count in how many terminals subrata logged in
To print users list and also store them in a file named user
$cat user
general tty01 Feb 02 12:35
subrata ttyi14 Feb 02 12:42
ranjan ttyi15 Feb 02 12:41
$
To store user list in a file named user, as well as pipe to another process sort to print sorted list
of users
$who | tee user | sort
general tty01 Feb 02 12:35
ranjan ttyi15 Feb 02 12:41
subrata ttyi14 Feb 02 12:42
$
$cat user
general tty01 Feb 02 12:35
subrata ttyi14 Feb 02 12:42
ranjan ttyi15 Feb 02 12:41
$
$cat number
NITTTR, Kolkata 22
Unix Commands
100 200 300
200 300 100
300 100 200
100 200 300
300 100 200
$
$cat country
USSR:8650:262:Asia
Canada:3852:24:North_America
China:3692:866:Asia
USA:3615:219:North_America
Brazil:3286:116:South_America
Australia:2968:14:Australia
India:1269:637:Asia
Argentina:1072:26:South_America
Sudan:968:19:Africa
Algeria:920:18:Africa
$
NITTTR, Kolkata 23
Unix Commands
$cat num
100 200 300
200 300 100
NITTTR, Kolkata 24
Unix Commands
300 100 200
$
$cat a1
BEGIN {OFS=":"}
{print $1,$2,$3,$4}
$
$paste num a1
100 200 300 BEGIN {OFS=":"}
200 300 100 {print $1,$2,$3,$4}
300 100 200
$
Translating Characters
To squeeze multiple consecutive occurrences of its argument to a single character (to compress
multiple blank spaces to a single space
NITTTR, Kolkata 25
Unix Commands
Group Commands:
A command usually ends with the newline character at the end of the command.
However, several commands can also be grouped on one line by using a semi-colon (:) as a
command separator. The semicolon defines end of command. For example :
$date;who
Wed Feb 02 11:43:34 IST 1994
general tty01 Feb 02 12:35
subrata ttyi14 Feb 02 12:42
ranjan ttyi15 Feb 02 12:41
$
$(date;who) | wc -l
4
$
NITTTR, Kolkata 26
Unix Commands
Background Process:
$kill 969
$ps
PID TTY TIME COMMAND
894 01 0:01 sh
972 01 0:00 ps
$
$ls -l
total 7
-rw-r--r-- 1 general group 23 Feb 02 12:48 abc
-rw-r--r-- 1 general group 23 Feb 02 14:48 arc
-rw-r--r-- 1 general group 228 Feb 02 02:49 def
-rw-r--r-- 1 general group 52 Feb 02 04:48 file5
-rw-r--r-- 1 general group 18 Feb 02 12:49 xyz
$
NITTTR, Kolkata 27
Unix Commands
$rm cdb
$ls -l
total 7
-rw-r--r-- 1 general group 23 Feb 02 12:48 abc
-rw-r--r-- 1 general group 23 Feb 02 14:48 arc
-rw-r--r-- 1 general group 228 Feb 02 02:49 def
-rw-r--r-- 1 general group 52 Feb 02 04:48 file5
-rw-r--r-- 1 general group 18 Feb 02 12:49 xyz
$
$lp abc
request id is pr0-001 (1 file)
$
NITTTR, Kolkata 28
Unix Commands
$lpstat -s
system default destination: pr0
device for pr0: /dev/lp0
device for pr1: /dev/lp1
$
$lpstat -t
scheduler is running
system default destination: pr0
device for pr0: /dev/lp0
device for pr1: /dev/lp1
pr0 accepting requests since Thu Dec 23 14:31:39 1993
pr1 accepting requests since Fri Dec 24 10:30:00 1993
printer pr0 now printing pr0-002. enabled since Mon 14
12:09:34 1994. available.
printer pr1 is idle. enable since Mon 14 14:30:16 1994.
available.
pr0-002 general 75 Mar 15 12:24 on pr0
pr0-003 general 124 Mar 15 12:26
$
$cancel pr0
request "pr0-002" cancelled
$
$cancel pr0-003
request "pr0-003" cancelled
$
NITTTR, Kolkata 29
Unix Commands
To display ASCII octal value of any file contents (to see non-printable character)
$cat a1
sdlkf
^D^D^D^D^D
^D
$
$od -b a1
0000000 163 144 154 153 146 012 004 004 004 004 004 012 004 012
0000016
$
each displays sizteen bytes of data in ASCII octal format.
NITTTR, Kolkata 30
Unix Commands
Communication
This command is invoked by user to read message that is stored in a file in the directory
/usr/news. This messages can be stored by any user.
To store message
To read message
$news
mesg1 (subrata) Wed Feb 10:43:34 IST 1994
Hello everybody !!
$
To display only the filenames of those messages which have not been displayed
$news -n
news: mesg1 mesg2
$
$news mesg2
mesg2 (general) Wed Feb 10:49:34 IST 1994
Good Morning everybody !!
$
To lists out the number of news items which have still not been read
$news -s
2 news items
$
To displays the contents of all news items regardless of whether they have been read or not
$news -a
Hello everybody !!
NITTTR, Kolkata 31
Unix Commands
$
This command lets user has a two-way communication with any user who is currently
logged in. One user writes his message and then waits for the reply from the other. In this way it
is possible to continue a conversation until such time as one or both the users press ^d to
terminate it.
$write ranjan
Good Morning
write subrata
Morning
When subrata is logged in to more than one terminal, say on tty04 and tty07, then the command
write subrata
Morning
sends message to the terminal with the lowest number, i.e. tty04. But if user really want to send
message to the terminal tty07, then the command is
Suppose subrata is logged in to more than one terminal, say on tty04 and tty07. To
comminucate between these two terminals always mention the terminal_number with
login_name.
In terminal tty04
In terminal tty07
However, if ranjan is not logged in, then the system responds with an error message:
NITTTR, Kolkata 32
Unix Commands
Communication, single or two-way, can be disconnecting to a user who is presently busy with
his own job.
$mesg n
$mesg y
This command is the UNIX repertoire of electronic mail. Unlike write command, it
enables sending of mail to a user even if he is not logged in. It is mainly used for non-interactive
communication. It saves the message in a mailbox, which normally is placed in the directory
/usr/mail, and has the same name as the login name. For instance, /usr/mail/ranjan. In SCO
UNIX, the directory is /usr/spool/mail.
$mail subrata
Subject: Morning
Good Morning
How are you ?
^d
$
The message does not directly appear on the receiver's terminal either. When the
receiver next time log in the following message will be flashing in his/her terminal.
To receive a mail
$mail
>N 3 ranjan Wed Feb 02 11:55 10/260 Morning
N2 general Tue Feb 01 14:35 15/459 Meeting
U1 root Tue Feb 01 10:12 23/789 Notice
&
NITTTR, Kolkata 33
Unix Commands
&3
Message 3:
From ranjan Wed Feb 02 11:55:45 IST 1994
To: subrata
Subject: Morning
Good Morning
How are you ?
&
This command searches a text file calender in the current directory for lines containing
either today or tomorrow's date. It then displays the matched lines. This is a sort of an
engagement diary which consists of textual information.
$cat calendar
Principal visiting the department on Feb 03, 1994
Prof. S. Kar. take class on shell programming on 02/04/94
A practical class of shell programming on 02/05/94
Validiction on March 02
$
$date
Fri Feb 4 12:10:15 IST 1994
$
$calendar
NITTTR, Kolkata 34
Unix Commands
Prof. S. Kar. take class on shell programming on 02/04/94
A practical class of shell programming on 02/05/94
$
To format disks
To take backup, user must format the floppy disk using format command. In general,
catridge tapes do not need to be formatted. However, tapes that are to be used with mini
drives must be formatted.
$format /dev/rfd048ds9
$format /dev/rfd096ds9
$format /dev/rfd095ds15
$format /dev/rfd0135ds9
$format /dev/rfd0135ds18
The cpio (copy input output) can be used to copy files to and from a backup device. This
NITTTR, Kolkata 35
Unix Commands
backup device can be a magnetic or cartidge tape, a floppy disk, or even a disk file.
cpio uses the standard input to take the list of filenames. It then copies these files to the
standard output. Since it uses standard input and standard output, it is always used with the
shell's redirection and piping sysmbols.
To dumps the contents of the current directory except *.c files to the floppy disk
To dumps the contents of the current directory as well as its sub-directories to the floppy disk
To restore all files as well as sub-directories and all files from these sub-directories
To display the contents of the archive file [from device] without restoring the files
The tar (tape archive) command saves and restores files to and from an archive medium,
which is typically a floppy disk or tape.
NITTTR, Kolkata 36
Unix Commands
-c instructs tar command to create a new backup and
overwrite the old one if exists.
v (verbose) causes it to display the each file names it treats.
f indicates next argument as the name of the archive [device]
NITTTR, Kolkata 37
Unix Commands
As a System Administrator
$wall
The machine will be shut down today at 12:20 hrs.
^d
$
To create a file system on a floppy disk, it needs to be first formatted with format command and
after that, the mkfs (make file system) command can be used like follows
Once a file system has been created, it is needed to add it to the main file system. To do
that, user must indicate the branch of the main file system which is to be attached to the root
directory of new file system. This process is called mounting, and achieved with the mount
command.
#mkdir ownfs
#cd ownfs
#pwd
/ownfs
#mount /dev/fd048ds9 /ownfs
#mount
/ on /dev/root read/write on Fri Feb 04 14:34:55 1994
/ownfs on /dev/fd048ds9 read/write on Mon Feb 07 12:10:05 1994
After this device is mounted, its root directory now becomes the /ownfs.
#umount /ownfs
When a file is created, the user becomes the owner of the file, and the group to which
the user belongs becomes the group owner. If user is not the owner of a file, he simply can not
change the major file attributes. For instance, you can neither edit the file, nor change its
permissions.
NITTTR, Kolkata 38
Unix Commands
To change file owner of the file item
#ls -l item
-rwxrw---x 1 general group 10 Feb 01 10:30 item
#chown ranjan item
#ls -l item
-rwxrw---x 1 ranjan group 10 Feb 01 10:30 item
#ls -l
-rwxrw---x 1 ranjan group 10 Feb 01 10:30 item
#chgrp bin item
#ls -l item
-rwxrw---x 1 ranjan bin 10 Feb 01 10:30 item
#
Account Management
All user accounts are stored in the file called /etc/passwd. This file is very important and
if destroyed no one will be able to login to the system. Each line of the /etc/passwd file
corresponds to an account. The fields of the /etc/passwd file are as follows (delimited by :)
root:muZ:0:1:Superuser:/:
general:B09..,er:200:50:General Users:/usr/general:/bin/sh
ranjan:hoopK9:201:50:Ranjan Dasgupta:/usr/ranjan:/bin/sh
subrata:Y09oiu:202:50:Subrata Baguli:/usr/subrata:/bin/csh
Each user account in the UNIX system belongs to a group. This grouping facilitates the
collective ownership of files or processes. If the group permissions on a file are set then any ser
of the group can access the file. The /etc/passwd file defines the default group for each of its
accounts. The /etc/group file describes the groups in the system. Each line of the /etc/group file
corresponds to one group with the following fields delimited by a colon (:)
NITTTR, Kolkata 39
Unix Commands
) Group name Name of the group
) Password Password of the group in encrypted form. Normally it is left
as blank.
) Group id A unique integer less than 100 for system groups, 100 -
30000 for user groups
) User id's Account names that are belong to this group separated by
commas (,)
root::0:
other::1:root
bin::2:bin
group::50:general,ranjan,subrata
To add an account
) Add an entry in the /etc/passwd file giving appropriate values to each field
) Leave the second field (password) blank
) Save the /etc/passwd file
) Create the appropriate home directory for the new account.
) Change the owner of the directory to the account name
) Change the group of the directory to the account's group
) Add account name to the appropriate group entry in the /etc/group file
) Save the /etc/group file
) Copy the /etc/profile file into the home directory as .profile
) Change the owner and group of the .profile file.
To remove an account
Whenever any user logs in the shell program starts up and executes commands in the file
/etc/profile and those in a file called .profile in the accounts home directory. Every user can edit
the .profile file in his/her home directory to include any system requirement.
The following some of the shell environment variables that get initialised the moment
the user logs into the system
NITTTR, Kolkata 40
Unix Commands
HOME Home directory
MAIL Mailfile pathname
LOGNAME Account name
PATH Command seach path
PS1 Primary prompt string
PS2 Secondary prompt string
PATH=$PATH:$HOME
MAIL=/usr/spool/mail/`logname`
PS1='General> '
export PATH MAIL PS1
Thus using the variables and export (makes the environment of the parent process
available in the child process) command in the .profile file any user can customise his/her
working environment. The present values of various environment variables can seen by
either env or set command.
NITTTR, Kolkata 41
Unix Commands
Visual Editor
To invoke VI editor
:n Go to line number n
:+n To moves cursor n lines forward
:-n To moves cursor n lines backward
Delete commands
x Delete character
dw Delete word
dd Delete line
NITTTR, Kolkata 42
Unix Commands
Searching commands
Substitute text
Other Functions
NITTTR, Kolkata 43
Unix Commands
$cat b1
echo "The current date and time: \c" date
echo "The number of users: \c" who|wc -l
echo "Personal Status: \c" who am i
$
$sh b1
The current date and time: Thu Feb 10 13:27:05 IST 1994
The number of users: 1
Personal Status: general ttyi15 Feb 10 10:53
$
$cat b2
TIME="The current date and time: \c"
USERS="The number of users: \c"
ME="Personal Status: \c"
echo "$TIME"
date
echo "$USERS"
who|wc -l
echo "$ME"
who am i
$
$sh b2
The current date and time: Thu Feb 10 13:27:47 IST 1994
The number of users: 1
Personal Status: general ttyi15 Feb 10 10:53
$
$cat b3
echo "Enter a user name: \c"
read NAME
if grep "^$NAME:" /etc/passwd > /dev/null
then
echo "'$NAME' is a valid user"
else
echo "'$NAME' is not a valid user"
fi
Here, output of grep command will go to the '/dev/null' file │
NITTTR, Kolkata 44
Unix Commands
$
$sh b3
Enter a user name: sanjay
'sanjay' is not a valid user
$
$cat b4
if test $# -ne 1
'test' command is used to test then
for status of files and values
echo "Usage: $0 <user name>" of variables. The output of
exit 'test' command is always true
fi or false
$sh b4 subrata
'subrata' is a valid user
$sh b4 sanjay
'sanjay' is not a valid user
Enter a number as first argument and determine a grade for it according to following rule
Number Grade
------ -----
90 - 100 E+
80 - 089 E
70 - 079 A+
60 - 069 A
50 - 059 P
49 - 000 F
NITTTR, Kolkata 45
Unix Commands
$cat b5
if test $# -ne 1
then
echo "Usage: $0 <numbre>"
exit
fi
if test $1 -ge 90
then
gd="E+"
elif test $1 -ge 80
then
gd="E"
elif test $1 -ge 70
then
gd="A+"
elif test $1 -ge 60
then
gd="A"
elif test $1 -ge 50
then
gd="P"
else
gd="F"
fi
$sh b5 98
Grade is E+ (98 %)
$
$cat b6
if test $# != 1
then
echo "usage: $0 <file name>"
exit
fi
NITTTR, Kolkata 46
Unix Commands
if test -d $1
then
echo "directory file"
elif test -f $1
then
echo "ordiary file"
else
echo "$1 not found"
exit
fi
if test -r $1
then
echo "readable"
fi
if test -w $1
then
echo "writeable"
fi
if test -x $1
then
echo "executable"
fi
$
$sh b6 b6
ordiary file
readable
writeable
$ls -l b6
-rw-r--r-- 1 general group 348 Feb 10 11:24 b6
$
$cat b7
for name in $* ## $* returns all command line arguments do
if grep "^$name:" /etc/passwd > /dev/null then
echo "'$name' is a valid user"
else
echo "'$name' is not a valid user"
fi
done
$
NITTTR, Kolkata 47
Unix Commands
'ranjan' is a valid user
$
$cat b8
until test -z "$1" ## Continue until $1 is not blank
do
if grep "^$1:" /etc/passwd > /dev/null
then
echo "'$1' is a valid user"
else
echo "'$1' is not a valid user"
fi
shift ## shift $2 as $1, $3 as $2 and so on
done
$
$cat b9
for fl in `ls`
do
echo "$fl? \c"
read rl
if test "$rl" = y -o "$rl" = Y
then
cat $fl
fi
done
$
$sh b9
b1? y
echo "The current date and time: \c"
date
echo "The number of users: \c"
who|wc -l
echo "Personal Status: \c"
who am i
b10? n
$
NITTTR, Kolkata 48
Unix Commands
Validate a user after entering its name and the process is still continue until ^d or
del key is pressed
$cat b10
echo "User Name: \c"
$sh b10
User Name: subrata
'subrata' is a valid user
User Name: ^d
$
A user friendly version of chmod. The first argument should be r, w or x and second
argument is a file name
$cat b11
if test $# -ne 2
then
echo "Usage: $0 <permission> <file name>"
exit
fi
if test -f $2 -o -d $2
then
case $1 in
r)chmod u+r $2;;
w)chmod u+w $2;;
x)chmod u+x $2;;
*)echo "No such permission"
esac
else
echo "'$2' not found"
fi
$
$ls -l b11
NITTTR, Kolkata 49
Unix Commands
-rw-r--r-- 1 general group 331 Feb 10 12:16 b11
$sh b11 x b11
$ls -l b11
-rwxr--r-- 1 general group 331 Feb 10 12:16 b11
$
$cat b12
echo "Enter value of 'a': "
read a
echo "Enter value of 'b': "
read b
c=`expr $a + $b`
echo "'a + b' is equal to $c"
c=`expr $a - $b`
echo "'a - b' is equal to $c"
c=`expr $a \* $b`
echo "'a * b' is equal to $c"
c=`expr $a / $b`
echo "'a / b' is equal to $c"
$
$sh b12
Enter value of 'a': 7
Enter value of 'b': 3
'a + b' is equal to 10
'a - b' is equal to 4
'a * b' is equal to 21
'a / b' is equal to 2
$
$cat b13
while true
do
tput clear ## clear the screen
tput cup 10 30 ## position the cursor at 10th row
echo "System Status" ## 30th column
tput cup 12 30
echo "1. Todays date"
tput cup 13 30
echo "2. Total no. of users"
tput cup 14 30
echo "3. Personal Status"
tput cup 15 30
echo "4. Quit"
NITTTR, Kolkata 50
Unix Commands
tput cup 17 30
echo "Enter choice(1-4): \c"
read ch
tput clear
tput cup 12
case $ch in
1) echo "The current date and time: `date`" ;;
2) echo "Total number of users: `who|wc -l`" ;;
3) echo "Personal Status: `who am i`" ;;
4) break ;;
*) echo "Invalid Choice"
esac
sleep 5
done
$
$sh b13
System Status
1. Todays date
2. Total no. of users
3. Personal Status
4. Quit
Enter choice(1-4): 1
The current date and time: Thu Feb 10 13:39:44 IST 1994
.
.
System Status
1. Todays date
2. Total no. of users
3. Personal Status
4. Quit
Enter choice(1-4): 4
$
$cat b14
while true
do
tput clear ## clear the screen
tput cup 8 ## position the cursor at 8th row
## 1st column
cat << TS
System Status
NITTTR, Kolkata 51
Unix Commands
1. Todays date
2. Total no. of users
3. Personal Status
4. Quit
Enter choice(1-4):
TS
tput cup 15 47
read ch
tput clear
tput cup 12
case $ch in
1) echo "The current date and time: `date`" ;;
2) echo "Total number of users: `who|wc -l`" ;;
3) echo "Personal Status: `who am i`" ;;
4) break ;;
*) echo "Invalid Choice"
esac
$sh b14
.
System Status
1. Todays date
2. Total no. of users
3. Personal Status
4. Quit
Enter choice(1-4): 1
.
The current date and time: Thu Feb 10 13:39:44 IST 1994
.
.
System Status
1. Todays date
2. Total no. of users
3. Personal Status
4. Quit
Enter choice(1-4): 4
NITTTR, Kolkata 52
Unix Commands
$
$cat b15
for fl in `ls`
do if test -f $fl
then
echo "$fl? \c"
read rl
if test "$rl" = y -o "$rl" = Y
then
cat $fl
fi
fi
done
$
$sh b15
b1? y
echo "The current date and time: \c"
date
echo "The number of users: \c"
who|wc -l
echo "Personal Status: \c"
who am i
b10? n
$
Awk (Aho Weinberger Kernighan) filter reads from a file one record at a time. Records are
ended with a newline character and fields of any record are recognised by blank or tab character
(by default). This reading of file is sequential in nature and depending upon the program
associated with the awk filter, iit outputs the records (a part of records) which satisfy the
conditions mentioned in the program.
The program is
pattern {action}
...
Where filename represents the text file on which awk work and program represents the
condition which is to be checked with the records of the file and accordingly the output awk is
given. This program can be constituted in two ways - one by its own syntax (explained in
subsequent section) and also it accepts C language like format (i,e. printf, for loop, etc.)
NITTTR, Kolkata 53
Unix Commands
The fields of the records are represented by $1, $2,...etc. $0 represents the record as a whole.
Awk has its own set of operators, awk variables and switches explained later.
To explore awk programming create the country file, which contains information about the 10
largest countries in the world. Each record contains the name of country, its area in thousands of
square miles, its population in millions, and the continent on which it is found.
$cat country
USSR 8650 262 Asia
Canada 3852 24 North_America
China 3692 866 Asia
USA 3615 219 North_America
Brazil 3286 116 South_America
Australia 2968 14 Australia
India 1269 637 Asia
Argentina 1072 26 South_America
Sudan 968 19 Africa
Algeria 920 18 Africa
$
To print 1st & 3rd field of the country file according to specific format
NITTTR, Kolkata 54
Unix Commands
$
%10s indicate minimum of 10 characters string
%6d indicate minimum of 6 digits integer number
To print records in which the 4th field equals the string "Asia"
To print 1st & 3rd field of each records in which 4th field
equals the string "Asia"
To print records in which 4th field not equals the string "Asia"
NITTTR, Kolkata 55
Unix Commands
USSR 8650 262 Asia
Canada 3852 24 North_America
China 3692 866 Asia
USA 3615 219 North_America
Brazil 3286 116 South_America
$
To print records in which 1st field greater than the string "S"
To print records starting with the first record that contains the string "USA", up
through the next occurance of the string "Sudan"
To print records those are starting with string "A" and followed by any character
between "l" and "r"
NITTTR, Kolkata 56
Unix Commands
To print records in which 4th field does not contain the string
"America"
To print records in which 1st field end with the string "n"
To print records in which 4th field contains the string "Asia" or "America"
To print records in which 4th field equal to the string "Asia" or "America"
To print records in which 4th field equal to the string "Asia" and 3rd field greater
than 200
$awk '$4=="Asia" && $3>200' country
USSR 8650 262 Asia
China 3692 866 Asia
NITTTR, Kolkata 57
Unix Commands
India 1269 637 Asia
$
Awk also support to present the program to awk from a file
awk -f program_file filename ...
$cat a1
BEGIN { print "Countries of Asia"}
$4 ~/Asia/ { print " ", $1}
$
BEGIN is a special pattern, execute before first record is read
$awk -f a1 country
Countries of Asia
USSR
China
India
$
$cat a2
BEGIN { print "Countries of Asia"}
$4 !~/Asia/ { print " ", $1}
$
$awk -f a2 country
Countries of Asia
Canada
USA
Brazil
Australia
Argentina
Sudan
Algeria
$
$cat a3
{ printf "%4d %s\n", NR, $0 }
$
NR gives last record number
$awk -f a3 country
1 USSR 8650 262 Asia
2 Canada 3852 24 North_America
3 China 3692 866 Asia
4 USA 3615 219 North_America
NITTTR, Kolkata 58
Unix Commands
5 Brazil 3286 116 South_America
6 Australia 2968 14 Australia
7 India 1269 637 Asia
8 Argentina 1072 26 South_America
9 Sudan 968 19 Africa
10 Algeria 920 18 Africa
$
$cat a4
BEGIN {s=0}
{ s=s+$3 }
END {print "Total population is", s, "million"
print "Average population of", NR, "countries is", s/NR}
$
BEGIN and END pattern execute before the first record is read and after
the last record is processed.
's' is a user defined variable
$awk -f a4 country
Total population is 2201 million
Average population of 10 countries is 220.1
$
To print records with heading and also calculate and print total
area and population
$cat a5
BEGIN { area=0; popu=0
printf "\n%10s %6s %5s %s\n\n", "COUNTRY","AREA","POP","CONTINENT"}
{ printf "%10s %6d %5d %s\n",$1,$2,$3,$4
area=area+$2; popu=popu+$3}
END { printf "\n%10s %6d %5d\n","TOTAL",area,popu }
$
$awk -f a5 country
COUNTRY AREA POP CONTINENT
NITTTR, Kolkata 59
Unix Commands
TOTAL 30292 2201
$
$cat a6
BEGIN {w=0;c=0}
{w=w+NF
c=c+length($0)+1} # 1 is added for new line characer
END {printf " %6d %6d %6d %s\n",NR,w,c,ARGV[1]}
$
NF is a Built-in awk variable, it returns no. of fields in each record, NR in END pattern gives
last record number, length function returns no. of characters in a
string and ARGV[1] returns first argument in command line
$awk -f a6 country
10 40 395 country
$
$wc country
10 40 395 country
$
To change output field separator ( ":" instead of blank)
$cat a7
BEGIN {OFS=":"}
{print $1,$2,$3,$4}
$
$cat country1
USSR:8650:262:Asia
Canada:3852:24:North_America
China:3692:866:Asia
USA:3615:219:North_America
Brazil:3286:116:South_America
Australia:2968:14:Australia
India:1269:637:Asia
Argentina:1072:26:South_America
Sudan:968:19:Africa
Algeria:920:18:Africa
$
$cat a8
BEGIN {FS=":"}
{ if($4=="Asia")
pop[1]+=$3
NITTTR, Kolkata 60
Unix Commands
else if($4=="Africa")
pop[2]+=$3
else
pop[3]+=$3 }
END { print "Asian population in million is",pop[1]
print "Africal population in million is",pop[2]
print "Others population in million is",pop[3] }
$
Here, FS indicates input field separator and pop is an array
$awk -f a8 country1
Asian population in million is 1765
Africal population in million is 37
Others population in million is 399
$
$cat a9
BEGIN {FS=":"; coun[1]="Asian ";coun[2]="African";coun[3]="Others "}
{ if($4=="Asia")
pop[1]+=$3
else if($4=="Africa")
pop[2]+=$3
else
pop[3]+=$3 }
END { for(i=1;i<=3;i++)
printf "%s %s %d\n",coun[i],"population in million is",pop[i]
}
$
$awk -f a9 country1
Asian population in million is 1765
African population in million is 37
Others population in million is 399
$
1st method
$cat a10
BEGIN {FS=OFS=":"}
{ if(substr($4,7)=="America")
print $1,$2,$3,"America"
else
print $0 }
$
NITTTR, Kolkata 61
Unix Commands
$cat a11
BEGIN {FS=OFS=":"}
{ s = (substr($4,7)=="America") ?
sprintf("%s:%s:%s:%s",$1,$2,$3,"America"):$0
print s
}
$
$cat a12
{ i=1 ; hsum=0
while (i<=NF)
{
vsum[i]+=$i
hsum+=$i
printf "%7d ",$i
i++
}
printf "%7d\n",hsum
}
NITTTR, Kolkata 62
Unix Commands
END { print ; for(j=1;j<i;j++) printf "%7d ",vsum[j] ; print }
$
$cat num
100 200 300
200 300 100
300 100 200
$
$cat a13
function fact(n)
{
if(n<=1)
return 1
else
return n*fact(n-1)
}
$cat number
1
2
3
4
5
6
7
$
NITTTR, Kolkata 63
Unix Commands
$
Item Number
Item Description
Reorder Level
Quantity on Hand
Unit of the Item
Unit price in rupees
All the procedures (Add, Modify & Listing) can invoke through
a shell procedure called "menu".
$sh menu
Main Menu
~~~~~~~~~
<0> Quit
Enter Choice:
Add Items
~~~~~~~~~
Item No :
Item Description:
Quantity on Hand:
Reorder Level :
Unit :
NITTTR, Kolkata 64
Unix Commands
Unit Price(Rs.) :
$cat item
i001:Rice:40:25:kg:12
i003:fan:20:5::600
i002:Table:6:7::350
i004:chair:15:10::150
i005:cover file:40:25::25
$
Modify Items
~~~~~~~~~~~~
Item No :
Old Unit :
New Unit :
NITTTR, Kolkata 65
Unix Commands
tput cup 0 0
# Display a menu
cat << M
Main Menu
~~~~~~~~~
<0> Quit
Enter Choice:
M
tput cup 16 41
echo "$ch" # Display previous choice
tput cup 16 41
NITTTR, Kolkata 66
Unix Commands
read ch # Read the choice
done
tput clear
Add Items
~~~~~~~~~
Item No :
Item Description:
Quantity on Hand:
Reorder Level :
Unit :
Unit Price(Rs.) :
EOT
NITTTR, Kolkata 67
Unix Commands
tput smso ## to turn on reverse video mode
tput cup 24 40
echo "Press Enter at first field to quit\c"
tput cup 7 34
read itno
if test -z "$itno"
then
tput rmso ## to turn off reverse video mode
break
fi
tput cup 9 34
read itdes
tput cup 11 34
read qoh
tput cup 13 34
read rlvl
tput cup 15 34
read unit
tput cup 17 34
read price
if test -f item
then
if grep "^$itno:" item > /dev/null
then
tput cup 22
echo "Item# $itno already exist!!"
tput cup 24
echo "Press any key to continue....\c"
read wt
tput rmso ## to turn off reverse video mode
continue
fi
fi
echo "$itno:$itdes:$qoh:$rlvl:$unit:$price">>item
rec=`expr $rec + 1`
NITTTR, Kolkata 68
Unix Commands
rec=0
while true
do
tput clear
cat << EOT
Modify Items
~~~~~~~~~~~~
Item No :
Old Unit :
New Unit :
tput cup 24 40
echo "Press Enter at first field to quit\c"
tput cup 5 38
read itno
if test -z "$itno"
then
tput rmso ## to turn off reverse video mode
break
fi
if test -f item
then
it=`grep "^$itno:" item` ## store the searched record
if test -z "$it"
then
tput cup 22
echo "Item# $itno does not exist!!"
tput cup 23
echo "Press any key to continue....\c"
read wt
tput rmso ## to turn off reverse video mode
continue
fi
fi
NITTTR, Kolkata 69
Unix Commands
NITTTR, Kolkata 70
Unix Commands
{
if(line>19)
{
if(page!=1) # Page footer
{
for(i=1;i<80;i++)printf "-"
printf "\n"
system("tput cup 24 0")
printf ":"
system("tput cup 24 1")
system("read wt")
}
system("tput clear") # Page heading
system("tput cup 0")
printf "%35sITEM DETAILS%23sPage: %3d\n\n\n"," ", " ",page
printf "Item no%4sItem Description%10sQOH%5s Reorder_Level Unit
Unit_Price\n"," "," ",""
for(i=1;i<80;i++)printf "-"
printf "\n"
page+=1
line=5
}
NITTTR, Kolkata 71
Unix Commands
SED Commands
Using the sample input file, faculty, the following example uses the s command for substitution
to replace “HOD” with “HEAD”
The –e option is necessary only when you supply more then one instruction on the command line. It tells
sed to interpret the next argument as an instruction.
NITTTR, Kolkata 72
Unix Commands
Rajeev Chatterjee, Lect, Computer Science
D. Ray, HEAD, EE
S. Ray, HEAD, CE
Samiran Mandal, ASTT. PROF, ME
Use the multi line entry capabilities of the Bourne shell, press RETURN after entering a single quote and
a secondary prompt(>) will be displayed for multi line input.
$ sed ‘
> s/HOD/HEAD/
> s/CSE/Computer Science/
> s/Lect/Lecturer/
> s/EE/ Electrical Engineering/
> s/ME/ Mechanical Engineering/
> s/CE/ Continuing Education/
> s/ASTT. PROF./Assistant Professor,/ faculty
It is not practical to enter longer editing scripts on the command line. That is why it is usually best to
create a script file that contains the editing instructions. The editing script is simply a list of sed
commands that are executed in the order in which they appear. The form, using –f option , requires that
you specify the name of the script file on the command line.
NITTTR, Kolkata 73
Unix Commands
D. Ray, HEAD, Electrical Engineering
S. Ray, HEAD, Continuing Education
Samiran Mandal, Assistant Professor,Mechanical Engineering
The default operation of sed is to output every input line. The –n option suppresses the automatic
ouput. When specifying this option, each instruction intended to produce output must obtain a print
command, p.
NITTTR, Kolkata 74