Professional Documents
Culture Documents
of
UNIX
• OS is a system software
• Portability
• Modularity
• File structure
• Security
... banner
ls
cp kernel sort
comp
sh
shell hardware
as
who
ld a.out
vi date
ed wc
grep
• The utilities and other application programs form the third layer
• Fourth layer is the one with which the user actually interacts.
• Virtual memory
• Swap area
• Demand paging
• Group
• UNIX allows user IDs to be grouped
• A single user ID can be member of multiple groups
UNIX Commands
• pwd
• Displays the current working directory.
• date
• Displays the current date and time
• who
• Displays the names of all the users who have
currently logged in
• who am i
• Displays the name of the current user.
• ls
Syntax :ls [options] [file….]
options: -l list in long format
-a list all files including those
beginning with a dot
-i list inode no of file in first column
-s reports disk blocks occupied by file
-R recursively list all sub directories
-F mark type of each file
-C display files in columns
total 6
-rwxr-xr-x 1 user1 projA 12373 Dec 15 14:45 a.out
drwxr-xr-x 2 user2 projD 4096 Dec 22 14:00 awkpro
-rw-r--r-- 1 user1 projA 12831 Dec 12 13:59 c
-rw------- 1 user1 projA 61440 Dec 15 11:16 core
-rw-r--r-- 1 user3 projC 255 Dec 20 14:29 cs
Syntax:
• man [options] command_name
Common Options
-k keyword list command synopsis line for all keyword matches
-M path path to man pages
-a show all matching man pages (SVR4)
• Permission Levels
• User (owner) (u)
• Permission Settings
• Read (r)
• Write (w)
• Execute (x)
• make a subdirectory
Octal Number
4 - for read
2 - for write
1 - for execution
Example:
$ mkdir project1
This creates a directory project1 under current directory
Copying a file cp
Moving a file mv
Removing a file rm
Example
cp file1 file2
Options to cp
• -p
• Copies the file and preserves the following attributes
• owner id
• group id
• permissions
• last modification time
• -r
• recursive copy; copy subdirectories under the directory if
any
• -i
• interactive; prompts for confirmation before overwriting
the target file, if it already exists
umask command is used to see the default mask for the file
permission
umask 022 will set a mask of 022 for the current session
– The file permission after setting this umask value will be
644
– And the directory permission will be 755
• “set user ID” bit can be set in one of the two ways:
• chmod u+s <filename>
• The leftmost octal number 4 indicates “set user ID” bit to be set, other
octal digits indicate regular file permissions. This is meaningful for
executable files only.
• The leftmost octal number 2 indicates “set group ID” bit to be set, other
octal digits indicate regular file permissions. This is meaningful for
executable files only.
$ vi filename
B
a
c
ks
p
ac
e S
p
a
ce
h j k l
t
heq
u
i
ckb
r
ow
nf
ox t
heq
u
i
ckb
r
ow
nf
ox
www $
t
heq
u
i
ckb
r
ow
nf
ox t
heq
u
i
ckb
r
ow
nf
ox
2w ^
t
heq
u
i
ckb
r
ow
nf
ox
b b b
• Deletion
UNIX Utilities
Syntax:
touch [options] file
• Options:
• -a to change the access time
• -m to change the modification time
• -c no create if not exists
• touch <file> will change the time of change of the file if the file exists
• If the file does not exist, it will create a file of zero byte size.
x=10
echo $x
10
• more
• Allows user to view one page-full of information at a time.
• file
• Used to display the type of the file
• tty
• Prints the terminal’s name
• wc
• A filter used to count the number of lines, words, and characters in a
disk file or from the standard input.
• -l - displays the number of lines
• -w - displays the number of words
• -c - displays the number of characters
• cmp
• Returns the offset and the line number of the first position where the
two files differ.
• comm
• col1 - unique lines of first file
• col2 - unique lines of second file
• col3 - common lines
• diff
• Indicate the differences between the files
• a Lines added
• d Lines deleted
• c Lines changed
lists all files with .c extension from the current dir & its subdirectories
find . –size 1000c lists all files that are exactly 1000 bytes in size
find . –size +1000c lists all files that are more than 1000 bytes in size
find . –size –1000c lists all files that are less than 1000 bytes in size
command is command to be applied on the matching files (does not prompt user)
Long listing of all files with .dat extension in the current and its subdirectories
• -ok command {} \;
Functionality is similar to –exec, but prompts user before applying the command
on the file matching the criteria.
• pr
• Used to display a file in a format to be printed.
• Breaks up a file into pages with a header, text and footer
area
• Options
• -l to alter the length of the file
• -h to set the header
• -t to suppress the header and the footer
• -n to set the line number
$ ls –l > outfile
• Filters are programs that takes its input from the standard
input file, process it, and sends it to the standard output file.
Sorts the contents of the given file based on the first char of
each line.
-n numeric sort (comparison made
according to strings numeric value)
-r reverse sort
-t specify delimiter for fields
+num specify sorting field numbers
+num [-num] to specify the range
$ head -3 file1
$ tail -3 file1
Can also specify the line number from which the data has to be
displayed till the end of file
$ tail +5 file1
Example :
tr [a-z] [A-Z] < filename
This converts standard input read from lower case to upper case.
• -s char
Squeeze multiple contiguous occurrences of the character into single char
• -d char
Remove the character
Example:
$ cat * | wc
• Example
• who | tee userlist
• cat - | tee file1 | wc -l
Option remark
-c used to extract characters
-d Delimiter for fields
-f Field no.
Examples
$ cut -c2-5 file1
$ cut -d “|” -f2,3 file1
-d Specify delimiter
telnet hostname
or
telnet <ip address>
• Syntax
$ ftp hostname
gzip,
Usage is very similar to compress and pack utilities in Unix:
gzip [-vc] filename
gunzip
gunzip can uncompress files originally compressed with compress.
Examples:
Create a new tar file containing all .dat files (assuming a.dat, b.dat and c.dat
exist)
$ tar –cf mytar *.dat
Process
As soon as the user logs in, a process is created which executes the login
shell.
• It fetches the pid, tty, time, and the command which has started the
process.
• -f lists the pid of the parent process also.
• -u lists the processes of a given user
• -a lists the processes of all the users
• -e lists all the processes including the system
processes
• nohup
– Lets processes to continue to run even after logout
– The output of the command is sent to nohup.out if not redirected
• wait command
– can be used when a process has to wait for the output of a
background process
– The wait command, can be used to let the shell wait for all
background processes terminate.
$ wait
– It is possible to wait for completion of one specific process as well.
• jobs
• List the background process
• fg % <job id>
• Runs a process in the foreground
• bg %<job id>
• Runs a process in the background
• nice
• Used to reduce the priority of jobs
• kill -9 (SIGKILL)
• Terminates the process abruptly
• Bourne shell sh
• C shell csh
• Displays the shell prompt and reads the command typed by the
user.
alias newname=command
• When the user enters a command string, the shell parses the string
into following components:
• Command (the first part of the string, till the first space char)
• Command arguments (the subsequent parts of the string)
$ ls a*
$ ls ??
Examples:
x=10
textline_1=‘This line was entered by $USER’
textline_2=“This line was entered by $USER”
allusers=`who`
usercount=`who | wc –l`
• Once variables are defined, one can use the echo command
to display the value of each variable:
echo $x
echo $textline_1
echo $textline_2
echo $allusers
echo $usercount
• Examples:
• $ x=10; export x
• $ allusers=`who` ; export allusers
• PATH • MAIL
• BASH_ENV • USER
• HOME • LOGNAME
• PWD • PS1
• SHELL • PS2
• TERM
sh script1.sh
./script1.sh
----------------------script2.sh--------------------------
echo “Total parameters entered: $#”
echo “First parameter is : $1”
echo “The parameters are: $*”
shift
echo “First parameter is : $1”
------------------------------------------------------------
• Execute the above script using the “script2.sh these are the
parameters” command.
• For example,
• Example,
x=10
y=5
number_1 = `expr $x + $y`
number_2 = `expr $x - $y`
number_3 = `expr $x / $y`
number_4 = `expr $x \* $y`
number_5 = `expr $x % $y`
test expression
• General syntax
test expression
or
[ expression ]
test ! expression _1
OR
[ ! expression _1 ]
if condition
then
command
fi
if condition_1
then
command
elif condition_2
then
command
else
command
fi
Fundamentals of UNIX Ver 1.0 146
Using for Loop
----------------------script.sh--------------------------
#! /bin/sh
usernames=`who | cut –d “ “ –f1`
echo “Total users logged in = $#usernames”
#
for user in ${usernames}
do
echo $user
done
------------------------------------------------------------
The Bash shell provides a while loop. The syntax of this loop
is:
while condition
do
command
…
command
done
#!/bin/bash
n=$1
if [ $n -eq 0 ]; then
fact=0
else
fact=1
while [ $n –ne 0 ]
do
fact=`expr $fact \* $n`
n=`expr $n – 1`
done
fi
echo $fact
#!/bin/bash (contd.)
echo enter 2 nos
read num1 case $choice in
read num2 1) res=`expr $num1 + $num2`
echo “enter 1 (for addition) or echo result is $res;;
2 (for subtraction) 1) res=`expr $num1 - $num2`
read choice echo result is $res;;
*) echo invalid input;;
esac
toupper()
{
tr “[a-z]” “[A-Z]”
}
$ bash –v script-file
$ bash –x script-file
Comparison between
• A solution in C
• A shell solution written like a C program
• A proper “shell/unix” solution
e.g:
The problem is to count the no of lines in a file ( the file is
called the_file)
Syntax:
– sed 's/old/new/' <file_ip >file_op
# substitute "foo" with "bar" ONLY for lines which contain "baz"
sed '/baz/s/foo/bar/g'
# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
sed '/baz/!s/foo/bar/g'
When the "-n" option is used, the "p" flag will cause the modified line to be
printed.
• sed –n ‘/root/p’ /etc/passwd (acts as grep)
With /w filename you can specify a file that will receive the modified data
• sed –n ‘1,4pw /tmp/op_file’ /in_file (copies first four lines from in_file to op_file)
sed –f scriptname:
Syntax: sed –f sedscript < ip_file
If you have (multiple) large number of sed commands you can create
sed command file and execute with –f option
Example: Edit a file “sedcmd” and add the lines below
s/red/RED/g
s/white/WHITE/g
and execute it as follows
sed –f sedcmd <test_ip >test_op
If you wanted to add a colon after the 80th character in each line,
you could type ( “.” for every character)
sed 's/./&:/80' <file >new
With “&” you can put the string you found in the replacement
string
sed -n 's/pattern/&/p' <file ( acts as grep )
Example2:
sed `/orange/ a\
ABOVE LINE HAS orange IN IT ‘ test
sed ‘3i\
Insert a line at line 3\
‘ test
• Awk patterns are good for selecting specific lines from the
input for further processing
• Selection by Comparison
– $2 >=5 { print }
• Selection by Computation
– $2 * $3 > 50 { printf(“%6.2f for %s\n”, $2 * $3, $1) }
• Selection by Text Content
– $1 == “Susie”
– /Susie/
• Combinations of Patterns
– $2 >= 4 || $3 >= 20
• Arithmetic
– sin, cos, atan, exp, int, log, rand, sqrt
• String
– length, substitution, find substrings, split strings
• Output
– print, printf, print and printf to file
• Special
– system - executes a Unix command
• system(“clear”) to clear the screen
• Note double quotes around the Unix command
– exit - stop reading input and go immediately to the END pattern-action pair if it
exists, otherwise exit the script
Function Description
split(s, a, fs) split s into array a on field separator fs, return number of
fields
sub(r, s) substitute s for the leftmost longest substring of $0
matched by r
sub(r, s, t) substitute s for the leftmost longest substring of t matched
by r
substr(s, p) return suffix of s starting at position p