unit_3
unit_3
Shell Programming
A shell is an environment in which we can run our commands, programs, and shell scripts.
There are different flavors of shells, just as there are different flavors of operating systems.
Each flavor of shell has its own set of recognized commands and functions.
VI Editor - Introduction
There are many ways to edit files in Unix. Editing files using the screen-oriented text editor vi is
one of the best ways. This editor enables you to edit lines in context with other lines in the file.
An improved version of the vi editor which is called the VIM has also been made available
now. Here, VIM stands for Vi IMproved.
vi is generally considered the de facto standard in Unix editors because −
• It's usually available on all the flavors of Unix system.
• Its implementations are very similar across the board.
• It requires very few resources.
• It is more user-friendly than other editors such as the ed or the ex.
• You can use the vi editor to edit an existing file or to create a new file from scratch. You
can also use this editor to just read a text file.
o vi stands for Vim Improved.
o Vi uses number of internal commands to navigate to any point in a text file and edit text
there.
o It also allows us to copy and move the text within the file and also from one file to
another.
o We can use internal commands for editing work.
o It makes complete use of keyboard where practically every key has a function.
o To create any vi file,
$ vi <some text or filename>
o If file doesn’t exist, vi provides us a full screen with the filename shown at the bottom
with the qualifier [New File].
o The cursor is positioned at top and all remaining lines of the screen (Except last) show
a ~. We can’t take cursor there because they are nonexistent lines.
o The last line is reserved for commands that we can enter to act on the text. This line is
also used by the system to display the message.
1
General Command Information
As mentioned previously, vi uses letters as commands.
It is important to note that in general vi commands:
• are case sensitive - lowercase and uppercase command letters do different
things
• are not displayed on the screen when you type them
• Generally do not require a Return after you type the command.
You will see some commands which start with a colon (:). These commands are ex commands
which are used by the ex editor. Ex is the true editor which lies underneath vi -- in other words,
vi is the interface for the ex editor.
Limitations of VI editor
vi editor has weak environment s there are some disadvantages of it as below:
1. vi is case-sensitive.
2. It don't display error message when something is going wrong. At that moment, only
beep sound of speaker which informs you there is something wrong.
3. There is no online help available in vi.
4. It works on 3 different modes. Same keys can create different effect on each mode.
VI Editor - MODES
While working with the vi editor, we usually come across the following two modes −
• Command mode −
By default, any file open in vi is in command mode.
This is default mode of vi.
This mode enables you to perform administrative tasks such as saving the files,
executing the commands, moving the cursor, cutting (yanking) and pasting the lines
or words, as well as finding and replacing. In this mode, whatever you type is
interpreted as a command.
When user is in command mode and press Esc key then internal speaker of terminal
will beep.
This is a mode where we can pass commands to act on text, using keys of the keyboard.
Pressing a key doesn’t show it on screen but may perform a function like moving cursor
to the next line or deleting a line.
We can’t use Command Mode to enter or replace text.
• Insert mode −
This mode enables you to insert text into the file.
Everything that's typed in this mode is interpreted as input and placed in the file.
When you are in insert mode the same letters of the keyboard will type or edit text.
For text editing, vi uses 24 of the 25 lines that are normally available in a terminal.
2
To enter text, we must switch to Input Mode. First press key marked i and we are ready
to input text.
We can start inserting a few lines of text followed by [enter].
[Notes: vi always starts out in command mode.
When you wish to move between the two modes, keep these things in mind.
You can type i to enter the insert mode.
If you wish to leave insert mode and return to the command mode, hit the ESC key.
If you're not sure where you are, hit ESC a couple of times and that should put you back in
command mode.]
i - insert :q - quit
- cursor
h j k l - cursor a - append :q! - quit no save
CTL-f - forward screen A - append at EOL :w - write
CTL-b - backward screen O - open line :wq - write and quit
G - end of file r - replace character :num goto line num
x - delete character R - overwrite /str - find str
dw - delete word :set all - vi settings
dd - delete line :r file - import file
yy - copy line in buffer
D - delete to EOL
p - paste/put buffer
u - undo last command
CTL-r - redo last undo (linux/vim)
. - repeat last editing command
n - find next occurrence of string
cw - change word
# command - repeate command # times
3
• Last Line mode −
The last vi mode is known as vi last line mode.
After text entry is complete, the cursor is positioned on the last character of the last
line.
This is known as Current Line and the character is stationed is the Current Cursor
Position.
You can only get to last line mode from command mode, and you get into last line mode
by pressing the colon key, like this:
':'
After pressing this key, you'll see a colon character appear at the beginning of the last
line of your vi editor window, and your cursor will be moved to that position.
This indicates that vi is ready for you to type in a "last line command".
If you want to remove something then can use [Backspace] key.
If a word has been misspelled then use [Ctrl+w] to erase entire word.
Press [Esc] key to revert to Command Mode.
The text that you entered hasn’t been saved on disk yet. The entered text exists in some
temporary storage called Buffer.
To save the entered text, we must switch to the ex mode or Last Line Mode (3rd mode
of VI).
To invoke ex Mode from the Command Mode by entering a colon (:) which shows on
last line. Press x and then [Enter].
Now, the file is stored on the disk and vi returns shell prompt.
To modify this file, again write vi <some text or filename> again.
4
Inserting or Adding Text
The following commands allow you to insert and add text. Each of these commands puts
the vi editor into insert mode; thus, the <Esc> key must be pressed to terminate the
entry of text and to put the vi editor back into command mode.
5
file.
:sh It temporary exit from vi and return to shell prompt. type <ctrl+d> to return
back to URL.
Ctrl-z It suspends current session and escape to unix shell. type fg at shell prompt to
return back to URL.
VI Editor - OPERATORS
A user can operates various tasks like delete, copy, paste, and search and replace a text.
Operator is a single letter command that performs an action on the text described by the
object.
The operators (to be described below) are:
1. d deletion operator
2. c change operator
3. y yank (copy) operator
4. ! filter operator
Editing Commands:
A user can use above operators with commands to perform editing operations in a file that is
opened in an editor.
To edit the file, you need to be in the insert mode.
Command & Description
d^: Deletes from the current cursor position to the beginning of the line
dfch : it deletes character from cursor position to 1st occurrences of character 'ch'.
d/str: it delete characters from cursor position to 1st occurrences to string 'str' in
forward direction.
7
D?str: it delete characters from cursor position to 1st occurrences to string 'str' in
backward direction.
D or d$: Deletes character from the cursor position to the end of the current line
Cc: Removes the contents of the line, leaving you in insert mode.
Cw: Changes the word the cursor is on from the cursor to the lowercase w end of the
word.
c$ or C: it changes the character from the cursor position to the end of the current
line
r: Replaces the character under the cursor. vi returns to the command mode after the
replacement is entered.
R: Overwrites multiple characters beginning with the character currently under the
cursor. You must use Esc to stop the overwriting.
S: Replaces the current character with the character you type. Afterward, you are left in
the insert mode.
S: Deletes the line the cursor is on and replaces it with the new text. After the new text
is entered, vi remains in the insert mode.
Yw: Copies the current word from the character the lowercase w cursor is on, until
the end of the word.
Yfch: it yanks cursor position to 1st occurrences of character 'ch' in forward direction.
y/str: it yanks from cursor position to 1st occurrences to string 'str' in reverse
direction.
8
y?str: it delete characters from cursor position to 1st occurrences to string 'str' in
forward direction.
Customized VI Editor:
A user can customize environment of VI editor. For that last line mode commands are used.
Command & Description
10
:set ai/ :set autoindent -Sets auto indent
:set noai-Unsets autoindent
_ALI
TOKEN_A
VAR_1
VAR_2
Following are the examples of invalid variable names −
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
The reason you cannot use other characters such as !, *,&,$ or - is that these characters have a
special meaning for the shell.
1. User defined variables: A variable defined by user known as user defined variables.
11
Defining Variables :Variables are defined as follows −
variable_name=variable_value/expression/command
For example −:
By default any variable created in shell are of string type. so, the values are stored in ASCII
rather than binary.
variables created in shell are automatically removed as soon as shell is expired.
when shell reads the command line, it interprets any word preceded by $ as a variable and
replace the word by the value of the variable.
To display content , a user can use echo command:
$echo $myvar <enter>
ans: 1234
$
VAR1="Zara Ali"
VAR2=100
Accessing Values
To access the value stored in a variable, prefix its name with the dollar sign ($) −
For example, the following script will access the value of defined variable NAME and print it on
STDOUT −
#!/bin/sh
NAME="Zara Ali"
echo $NAME
Zara Ali
Read-only Variables
Shell provides a way to mark variables as read-only by using the read-only command. After a
variable is marked read-only, its value cannot be changed.
For example, the following script generates an error while trying to change the value of NAME
#!/bin/sh
12
NAME="Zara Ali"
readonly NAME
NAME="Qadiri"
1. PARSING: in this stage, the shell divides the command line into words, if it is not quoted
or escaped. The shell uses system variable IFS (internal field separator) to delimiter the
value of word delimiter, which is space and tab.
When shell encounters 2 or more spaces or tabs in the command line then they are
replaced with a single space.
for example, a=10
$echo value of variable a=$a <enter> //multiple spaces
parsing
$ echo value of variable a=$a //spaces are replaced.
2. Variable Evaluation: in this stage, the shell is looking for variable names.
for example, a=10
$echo value of variable a=$a <enter> //$a is consider as variable
variable evaluation
3. Command Substitution: Any Unix command enclosed within back quotes is executed by
the shell and its output is substituted as argument for another command into a
command line.
E.g.: echo "Today's date: 'date'" // date command is enclosed within back quote ' '
Command Substitution
4. Redirection: in this stage, shell scans for the characters >,< and >> and open a file
associated with this characters in a particular mode.
e.g.: wc <f1 here, shell opens a file instead of command and display number of lines,
words and character in file f1.
13
5. Wild-card interpretation: A number of characters are interpreted by the Unix shell
before any other action takes place.
These characters are known as wildcard characters.
Usually these characters are used in place of filenames or directory names.
* An asterisk matches any number of characters in a filename, including none.
? The question mark matches any single character.
[ ] Brackets enclose a set of characters, any one of which may match a single character at
that position.
- A hyphen used within [ ] denotes a range of characters.
~ A tilde at the beginning of a word expands to the name of your home directory. If you
append another user's login name to the character, it refers to that user's home
directory.
Here are some examples:
1. cat c* displays any file whose name begins with c including the file c, if it exists.
2. ls *.c lists all files that have a .c extension.
3. cp ../rmt?. copies every file in the parent directory that is four characters long and
begins with rmt to the working directory. (The names will remain the same.)
4. ls rmt[34567] lists every file that begins with rmt and has a 3, 4, 5, 6, or 7 at the end.
5. ls rmt[3-7] does exactly the same thing as the previous example.
6. ls ~ lists your home directory.
7. ls ~hessen lists the home directory of the guy1 with the user id hessen.
6. PATH evaluation: finally, it examine the system variable PATH to search a command into
the sequence of directories stored in it. If it is found then load an executable of
command into memory and then execute it otherwise it sows error message on
standard output.
expr prints the value of EXPRESSION to standard output. A blank line below separates
increasing precedence groups.
EXPRESSION may be:
ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2.
$x=3;y=5
$expr $x\|$y ans: 3
ARG1 & ARG2 ARG1 if neither argument is null or 0, otherwise 0.
ARG1 < ARG2 ARG1 is less than ARG2.
ARG1 <= ARG2 ARG1 is less than or equal to ARG2.
ARG1 = ARG2 ARG1 is equal to ARG2.
ARG1 != ARG2 ARG1 is unequal to ARG2.
ARG1 >= ARG2 ARG1 is greater than or equal to ARG2.
ARG1 > ARG2 ARG1 is greater than ARG2.
14
$x=3;y=5
$expr $x\>$y ans: 0
ARG1 + ARG2 arithmetic sum of ARG1 and ARG2.
$x=3;y=5
$expr $x + $y ans: 8
Example:
$ expr length "TYBCA" ans :5
$ expr substr "TYBCA" 3 2 ans:BCA
$ expr substr "TYBCAmkics" 0 6 // display nothing
$ expr substr "TYBCAmkics" 7 12 ans:kics
$ expr substr "TYBCAmkics" -1 6 // display nothing
$ expr index "TYBCAmkics" A ans:5
15
2. bc command: IT stands for basic calculator.
[1] Interactive mode : when you invoke bc without any option or argument, it display some
header lines and cursor keeps on blinking and nothing seems to happen. this is the interactive
mode of bc command.
$bc <enter>
#----------display some header lines---------
12 + 5 <enter>
17
<ctrl+d> or quit or halt
$
I. scale:
By default, bc performs integer division so that result will be integer, the
fractional part of the result is truncated.
To show a fraction part, a user has to set a special variable called scale.
scale=2 <enter>
17/7 <enetr>\
2.42
II. ibase (input base) :
bc is quit useful in converting numbers from one base to another, set ibase
before you provide the number.
ibase=2 <enter> #default input and output base is 10(decimal)
101 <enter> #input is binary number
5 #output is in decimal base
16
III. obase (output) :
it defines conversion base of output.
obase=2 <enter> #now output base is binary
5 <enter> #input base is decimal
101 #binary of decimal
IV. last :
it contains value of last printed number.
4+5 <enter>
9
last <enter>
9
• bc also supports in-built functions like sqrt, cosine, sine, tangent, exponent etc.
• To use these function in bc, a user has to pre-load a math library using –l option. i.e. bc -l.
• This library has default scale to 20. table shows the list of functions:
Table : math function
Function Meaning
$bc -l
sqrt(4)
2
sqrt(11)
3
e(l)
2.71828182845904523536
scale=2
sqrt(11)
3.31
[2] command line mode : A user can also execute bc command at command-line.
in this mode, argument file contains numbers or expressions. for example, consider an input file
is as follow:
$ cat num
s(45*3.14/180) //convert into degree
17
scale=2
4/3
sqrt(5)
e(l)
1.5+4
quit
$ bc -lq num
.70682518110536592374
1.33
2.33
2.71
5.5
$
$ a=`echo "scale=2;5/3"|bc`
$ echo $a //ans:1.66
A user can convert decimal number into octal at command line as follow:
$echo "obase=8;12" | bc
14 #converts to octal value
$
e.g.: $ factor
12 # takes std. input,until <ctrl+d>
12: 2 2 3
35
35: 5 7
18
42
42: 2 3 7
100
100: 2 2 5 5
13 10 # Takes 2 inputs at a time
13: 13
10: 2 5
Syntax: units[FROM-UNIT[TO-UNIT]]
• In absence of from unit and to unit, the program will use interactive mode.
• “units” command will not work in bash shell, as:
$ units
• -bash: units: command not found.
• Example:
$ units
you have:10 meter # at you have prompt, give input
you want:feet # at you want prompt gives wanting unit
*32.808399 #output shown in interactive mode
/0.03048
you have: # after output input prompt again will come
• if-then-fi statement
• if-then-else-fi statement
• if-then-elif-else-fi statement
Syntax : If control-command
then
statements
fi
Other forms,
Double decision:
if <condition>
then
### series of code if the condition is satisfied
else
### series of code if the condition is not satisfied
fi
example :
#script name :sh2
echo -e "Enter name of first file :\c"
read fname1
echo -e "Enter name of second file :\c"
read fname2
20
if cmp -s $fname1 $fname2
then
echo "file contents are similar"
else
echo "file contents are not similar"
fi
Multiple if condition:
if <condition1>
then
### series of code for condition1
elif <condition2>
then
### series of code for condition2
else
### series of code if the condition is not satisfied
fi
21
• After the first match, case terminates with the exit status of the last command that was
executed.
• If there is no match, exit status of case is zero.
example:
echo "enter no."
read num
case $num in
1) echo "one"
;;
2) echo "Two"
;;
...
9)echo "Nine"
;;
*) echo "please ,enter a number between 1 and 9"
;;
esac
a=0
while [ "$a" -le 10 ] # this is loop1
do
echo $n
n=`expr $n + 1`
done
Ans: by this you can display 1 to 10
22
Here the Shell command is evaluated. If the resulting value is false, given statement(s) are
executed. If the command is true then no statement will be executed and the program jumps to
the next line after the done statement.
Example
Here is a simple example that uses the until loop to display the numbers zero to nine −
n=1
until [ $n -gt 10 ]
do
echo $n
n=`expr $a + 1`
done
Answer:
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9
2.3. for loop : The for loop operates on lists of items. It repeats a set of commands for
every item in a list.
Syntax
for var/(control variables) in word1 word2 ... wordN
do
Statement(s) //to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words). Each time the for loop executes, the value of the variable
var is set to the next word in the list of words, word1 to wordN.
Example
Here is a simple example that uses the for loop to span through the given list of
numbers −
for i in 0 1 2 3 4
do
echo $i
done
Upon execution, you will receive the following result −
0
1
23
2
3
4
while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
3.2 Continue :
The continue statement is similar to the break command, except that it causes the current
iteration of the loop to exit, rather than the entire loop.
This statement is useful when an error has occurred but you want to try to execute the next
iteration of the loop.
Syntax
continue
Like with the break statement, an integer argument can be given to the continue command to
skip commands from nested loops.
continue n
Here n specifies the nth enclosing loop to continue from.
Example
The following loop makes use of the continue statement which returns from the continue
statement and starts processing the next statement −
24
NUMS="1 2 3 4 5 6 7"
Logical Operators
This operators are used to join conditions.
shell offers 3 types of logical operators.
1. -a (Logical AND) : used to join 2 or more conditions.
2. -0 (Logical OR) : also, used to join 2 or more conditions.
3. -! (Logical NOT) : negates the value of expression. i.e. : it makes non-zero to zero and vise-versa.
test Command
it is used to evaluate expression and returns either true or false exit status which is used by if
statement to make decision.
There are 3 major functionalities of test command.
1. compare 2 numbers
2. compare 2 strings or a single or null value
3. checks a file attributes
Examples:
25
test 1 -eq 2 && echo "yes" || echo "no"
(displays "no" to the screen because 1 does not equal 2)
2. String comparison:
If you are comparing elements that parse as strings you can use the following
comparison operators:
Examples:
test "string1" = "string2" && echo "yes" || echo "no"
(displays "no" to the screen because "string1" does not equal "string2")
26
(displays "yes" to the screen because "string1" does not equal "string2")
If you are comparing files you can use the following comparison operators:
• -ef - Do the files have the same device and inode numbers (are they the same file)
• -nt - the first file newer than the second file
• -ot - the first file older than the second file
• -b - The file exists and is block special
• -c - The file exists and is character special
• -d - The file exists and is a directory
• -e - The file exists
• -f - The file exists and is a regular file
• -g - The file exists and has the specified group number
• -G - The file exists and owner by the user's group
• -h - The file exists and is a symbolic link
• -k - The file exists and has its sticky bit set
• -L - The same as -h
• -O - The file exists you are the owner
• -p - The file exists and is a named pipe
• -r - The file exists and is readable
• -s - The file exists and has a size greater than zero
• -S - The file exists and is a socket
• -t - The file descriptor is opened on a terminal
• -u - The file exists and the set-user-id bit is set
• -w - The file exists and is writable
• -x - The file exists and is executable
Examples:
test /path/to/file1 -n /path/to/file2 && echo "yes"
(If file1 is newer than file2 then the word "yes" will be displayed)
27
test -e /path/to/file1 && echo "yes"
(if file1 exists the word "yes" will be displayed)
• When we make a copy of a file, we are having 2 different files with different names and same
content. In this file occupies separate space on a disk.
28
• But when we make a link of a file, we are having a single file, different names and same
contents. In this no separate space is occupied on a disk.
• In case of copy a new file new i-node number is created. But in case of link the files have the
same i-node number.
1. HARD-LINK:
• Create a hard link to a file f1 by giving the command as follows:
$ ln f1 f1.lnk<enter>
$
• Verify links as:
$ ls –i f1 f1.lnk
1733089 f1 1733089 f1.lnk
$
29
2. SYMBOLIC LINK(SOFT LINK):
• Symbolic link allows you to give a file, another name, but does not link the file by i-node.
• We can create Symbolic link to the file using ln with –s option as follows:
$ ln -s a1 a1.lnk
• It display nothing means you created a symbolic link named a1.lnk that points to the file a1.
• If ls –i is used the 2 files have different i-nodes.
$ ls -i a1 a1.lnk
309686 a1 309589 a1.lnk
• If you use ls –l ,you will see that the file a1.lnk is a symbolic link pointing to a1
The result shows that a symbolic link file a1.lnk will not use the permissions of input file a1.
• They always have the permission rwxrwxrwx.
• On the other hand permission of hard link is same as that of original file.
• Drawback of symbolic link is that if we remove source file, we lose the file containing the data.
• In this case, the link file points to a nonexistent file.
• So we call it dangling symbolic link.
different i-node
number in symbolic
link
same i-node
number in hard link
30
• A user can create a symbolic link to a file that does not exist. The same is not possible with hard-
links.
Find command
it searches files in the directory hierarchy.
Syntax:
3. Search for a file by the name abc in the current directory and its hierarchy
$ find -name abc
4. Search a file with specific name.
31
5. Find Files Using Name in Current Directory
32
Finding hidden directories
find -type d -name ".*"
-type l It selects linked files
-links n|-n|+n It selects file having n links(-n for less than n links and +n for
greater than n links)
inum n|-n|+n It selects file having i-node number n (-n for less than n number
and +n for greater than n number)
-size x|-x|+x It selects file if size equal to x blocks(-x for less than x blocks and +x
for greater than x blocks)
How to find files based on the size?
a. Finding files whose size is exactly 10M
find . -size 10M
33
find . -amin -60
-mtime x|-x|+x It selects file if modified in x days
(-x for less than x days and +x for greater than x days)
How to find the files which are modified after the modification of a
give file.
find -newer "sum.java"
This will display all the files which are modified after the file
"sum.java"
Display the files which are changed after the modification of a give
file.
find -cnewer "sum.java"
-perm nnn It selects file if octal permission is nnn
34
Action Significance
-exec cmd it executes unix command cmd followed by {} \;
35
-print it prints selected files on standard output(it is the default action)
Examples: you want to locate all files names file1 under current directory hierarchy, then
command is :
$find . –name f1 –print
./d1/d2/f1
./d1/f1
./f1
$
36
4) $find /user/b1 –name “f?” –print
In the first pass, it ignores character followed by backslash(\) and make a substitution if any.
It executes command in 2nd pass only.
In this example during the 1st pass $ symbol after \ remains as it is and $y replaces by 'x'.
where as in 2nd pass $x replaced by 5 and then echo command print on screen.
Eval command is useful when a user wish to create a command line inside a variables.
It is useful to assign a value of a variable to another variable as follow:
$a="hello"
$apte=a
$eval $aptr = "world"
$echo $a
$ c="ls|more"
$ eval $c
1
11
1cd
201403152214.45
22
a
……..output of more ahead
4) using pipe stored in a variable and this variable is used for executing commands
$ x="|"
38
$ls $x wc
ls: |: No such file or directory
ls: wc: No such file or directory
$ eval ls $x wc
79 79 395
5)$ ls f*
f1 f1234 f1copy f1h f1s f2 ft.sh
$ wc<f*
-bash: f*: ambiguous redirect
“ \<” this holds redirection which is to be executed first and executes it later with eval ,first
f* is executed which is to be executed to be second.
$ eval wc \< f*
0 0 0 f1234
1 1 5 f1copy
1 1 5 f1h
4 8 31 f1s
4 8 31 f2
8 40 154 ft.sh
18 58 226 total
6)$x=5
$ y=x
$ y=4
$ echo $x
5
assigns value of one variable to other variable.
$ x=5
$ y=x
$ eval $y=4
$ echo $x
4
7) $ x=5
$ y=x
$ eval echo \$$y
5
The three file permission attributes are read, write and execute.
These 3 are mapped to octal values as shown below:
read - 4
write - 2
execute - 1
The umask command is used to set this mask, or to show you its current value.
The system default settings for both file and directory is rw-rw-rw (i.e. Octal 666) and
rwxrwxrwx (i.e. Octal 777) respectively.
Say, the umask value is 0022. umask is by default displayed in Octal form, and hence the first 0
in the umask value is the indication for octal value. So, the actual umask is 022. This value
together with the default file value(666) decides the final permission to be given to the file.
Assume we create a file say "file1". The permissions given for this file will be the result coming
from the substraction of the umask from the default value :
Default: 666
umask : 022
---------------
Result : 644
644 is the permission to be given on the file "file1". 644 means read and write for the
User(644), read only for the group(644) and others(644).
What is umask?
umask is a number which defines the default permissions which are not to be given on a
file. A umask of 022 means not to give the write permission to the group(022) and
others(022) by default.
40
The option -S gives in more readable
format.
This means umask, at the
max, allows all permissions for the
user, read and execute alone for the
group and others.
Example:-
If user creates a regular file then the default permission is calculated as below:
Default Permission of regular file
= system’s default setting for regular file – user mask
= 666 – 002
= 664
So, Default Permission of regular file is assigned as 664(666 - 002) i.e. rw-rw-r--
If user creates a new directory then the default permission is calculated as below:
Default Permission of directory
= System’s default setting for directory – user mask
= 777- 002
= 775
So, default permission to new directory is assigned as 755 (777 – 002) i.e. rwxrwxr-x
You can change user mask settings as follows:
$umask 222
41
If mask value 1 means remove 1 from system’s default directory and file permission.
For directory, the default permission is 7 (i.e. 4+2+1), so we remove 1 then the result is
6 (4+2).
The default for a file is 6 (4+2), so we remove 1 then result is 6 (4+2).
Octal dump : od
Most of the unix commands dont display invisible characters such as tab, space, new line etc.
od is a program for displaying ("dumping") data in various human-readable output formats.
The name is an acronym for "octal dump" since it defaults to printing in the octal data format.
It can also display output in a variety of other formats, including hexadecimal, decimal,
and ASCII.
It is useful for visualizing data that is not in a human-readable format, like the executable code
of a program.
od syntax
od [OPTION]... [FILE]...
So we see that output was produced in octal format. The first column in the output of od
represents the byte offset in file.
byte offset is the number of character that exists counting from the beginning of a line. ... The byte offset is the
count of bytes starting at zero.
42
Display contents of file in character format using -c option
Display contents of file in character in octal format using -b option
This command is used to create the empty files in Unix system. The size of the file
created using touch command in UNIX will be 0 bytes. We will be able to add the
contents into the file using vi command.
43
There are three time stamps associated with UNIX file:
• Last modification date and time.---mtime
• Last access date and time.---atime
• Last inode change date and time. ---ctime
When user make changes in a file then modification time (mtime) is changed by the
kernel.
When we read, write and execute a file then access time (atime) of file is changed by the
kernel.
But ctime changes a few extra times. For example, it will change if you change the
owner or the permissions on the file.
A user can display last access time & date by: ls –lu as:
$ ls -lu y11
---x--x--x 1 neha neha 33 Jul 9 04:32 y11
A user can display last inode change time & date by: ls –lc as:
$ ls -lc y11
---x--x--x 1 neha neha 33 Jul 11 03:18 y11
• Touch command allows you to change modification and access time of file. The
general form of touch command is:
Syntax: Touch[option][expression]file(s)
• It updates the access and modification times of each file to the current time.
44
• When touch is used without option and expression, it changes both times of file
to current time. If file does not exist then it creates an empty file.
• Using touch command, you can update modification and access time of file f1 to
current time as follow:
$touch f1
The result shows that both the time of file f1 have been changed to the current
time.
• In the syntax of the touch command, an expression consists of the form
[[cc]yy]MMDDhhmm[.ss].
• The meaning of each symbol is given in table:
45
• Similarly, -m option is used to change only modification time of a file. Use –t
option with –m option you can suppress warning message.
$ touch -m -t 03171414 f2
$ ls -lu f2
-rw-rw-r-- 1 nidhi nidhi 0 Mar 17 14:14 f2
• Consider a file f2 , you can change modification time of file f2 to current time as :
$ touch –m f2
If a user doesn’t want to create an empty file if file does not exist then –c option is
used.
$ touch –c nofile1
$ ls nofile1
Ls : nofile1: no such file or directory
$
Result shows that there is no nofile1 in a directory. It means that touch command does
not create an empty file even though a file does not exist.
• Filename substitution : There are mainly 3 meta characters for file name substitution.
Item Description
* Matches any string, including the null string
? Matches any one character
[...] Matches any one of the characters enclosed in square brackets
1. Asterisk (*) : The asterisk is a wildcard that matches for zero or more of any character in
a filename.
Example
1 $ ls * abc abc1 abc122 abc123 abc2 file1 file1.bak file2 file2.bak
none nonsense noone nothing nowhere one
2 $ ls *.bak file1.bak file2.bak 3 $ print a*c abc
EXPLANATION
1. The asterisk expands to all of the files in the present working directory. All of the
files are passed to ls and displayed.
46
like $ls*
2. All files starting with zero or more characters and ending with .bak are matched
and listed.
3. All files starting with a , followed by zero or more characters, and ending in c are
matched and passed as arguments to the print command.
EXPLANATION
1. The files in the current directory are listed.
2. Filenames containing four characters are matched and listed if the filename
starts with an a , followed by a single character, followed by a c and a single
character.
3. Filenames containing exactly two characters are listed. There are none, so the
two question marks are treated as literal characters. Because there is no file in
the directory called ?? , the shell sends the message ?? not found .
4. Filenames containing six characters are matched and printed, starting
with abc and followed by exactly three of any character.
5. The ksh print function gets the two question marks as an argument. The shell
tries to match for any filenames with exactly two characters. There are no files in
the directory that contain exactly two characters. The shell treats the question
mark as a literal question mark if it cannot find a match. The two literal question
marks are passed as arguments to the print command.
3. Character class [..] : Brackets are used to match filenames containing one character
from a set or range of characters.
Example
47
1 $ ls abc abc1 abc122 abc123 abc2 file1 file1.bak file2 file2.bak none nonsense none
nothing nowhere one
2 $ ls abc[123] abc1 abc2
3 $ ls abc[13] abc1 abc2
4 $ ls [az][az][az] abc one
5 $ ls [!fz]??? abc1 abc2
6 $ ls abc12[2-3] abc122 abc123
EXPLANATION
1. All of the files in the present working directory are listed.
2. All four-character names are matched and listed if the filename starts with abc ,
followed by 1 , 2 , or 3 . Only one character from the set in the brackets is
matched for a filename.
3. All four-character filenames are matched and listed if the filename starts
with abc , and is followed by a number in the range from 1 to 3 .
4. All three-character filenames are matched and listed, if the filename contains
exactly three lowercase alphabetic characters.
5. All four-character files are listed if the first character is not a letter
between f and z , followed by three of any character ( ??? ).
6. Files are listed if the filenames contain abc12 , followed by 2 or 3 .
3.7 Redirection
• Redirection is a feature in unix such that when executing a command, you can change
the standard input/output devices.
• Most Unix system commands take input from your terminal and send the resulting
output back to your terminal.
• A command normally reads its input from the standard input, which happens to be your
terminal by default.
• Similarly, a command normally writes its output to standard output, which is again your
terminal by default.
• Every program you run from the shell opens three files:
o Standard input,
o standard output, and
o standard error.
• The files provide the primary means of communications between the programs, and
exist for as long as the process runs.
• With redirection, the above standard input/output can be changed.
Understanding I/O streams numbers: The Unix / Linux standard I/O streams with numbers:
Handle Name Description
48
0 stdin Standard input
1. Output Redirection:
The output from a command normally intended for standard output can be easily
diverted to a file instead.
This capability is known as output redirection.
If the notation > file is appended to any command that normally writes its output to
standard output, the output of that command will be written to file instead of your
terminal.
e.g.: $ cat file1 > file2 [A user can create a duplicate file using output redirection]
$ cat file1 > file2 #command using file descriptor for o/p
$wc f1 >> f2 #appends o/p in f2.
$ cat > newfile <enter> #output redirection creates a new file
This is new file <enter>
<ctrl+d>
$
If you want to override the option and replace the current file
Contents with new output, you must use the redirection override operator,
greater than bar(>|).
$ who >| exist_file
2. Input Redirection:
• Just as the output of a command can be redirected to a file, so can the input of a
command be redirected from a file.
• As the greater-than character > is used for output redirection,
49
• the less-than character < is used to redirect the input of a command.
• The commands that normally take their input from the standard input can have
their input redirected from a file in this manner.
• We can apply input from keyboard.
• For example, to count the number of lines in the file users generated above,
you can execute the command as follows −
$ wc -l users
2 users
$
• Upon execution, you will receive the following output.
• You can count the number of lines in the file by redirecting the standard input of
the wc command from the file users −
$ wc -l < users
2
$
3. Error Redirection:
• Standard error (“stderr”) is like standard output and standard input, but it’s the
place where error messages go.
• Error re-direction is one of the very popular features of Unix/Linux.
• Frequent UNIX users will reckon that many commands give you massive amounts of
errors.
• For instance, while searching for files, one typically gets permission denied errors.
These errors usually do not help the person searching for a particular file.
• While executing shell scripts, you often do NOT want error messages cluttering up
the normal program output.
Example 1
$ myprogram 2 > errorsfile
Above we are executing a program names myprogram.
The file descriptor for standard error is 2.
Using "2>" we re-direct the error output to a file named "errorfile"
Thus, program output is not cluttered with errors.
50
example:
To write an output of command or error message into a same file, we must use
redirection substitution operator(>&)
$ ls –l file1 file2 file3 1> out_file 2>&1
Here, Error file is same as output file
$ cat file1 file2 file3 2>err_file 1>&2
Here output file is same as error file.
Redirection Commands
Following is a complete list of commands which you can use for redirection −
Sr.No. Command & Description
4 n > file
Output from stream with descriptor n redirected to file
5 n >> file
Output from stream with descriptor n appended to file
6 n >& m
51
Merges output from stream n with stream m
7 n <& m
Merges input from stream n with stream m
8 << tag
Standard input comes from here through next tag at the start of line
9 |
Takes output from one program, or process, and sends it to another
Piping Mechanism:
• Piping connects the output of one process to the input of a second.
• Piping uses the symbol "|".
• Pipe is used to combine two or more command and in this the output of one command
act as input to another command and this command output may act as input to next
command and so on.
• It can also be visualized as a temporary connection between two or more commands/
programs/ processes.
• The command line programs that do the further processing are referred to as filters.
• A filter is a process which is between two pipes.
• It simply changes the information coming down the pipe.
• Standard input for a process can be drawn from the script file itself.
• This uses the special redirection symbol "<<".
• The name which follows the redirection symbol is a tag for the end of the input.
• The Unix/Linux systems allow stdout of a command to be connected to stdin of another
command.
• Syntax :
command_1 | command_2 | command_3 | .... | command_N
here the o/p of cat command can be used as standard i/p of wc command.
So, the result shows the no. of characters in a file f1.
52
Conditional Execution:
• There are 2 conditional execution meta characters : && and ||.
• These meta characters can execute a command depending on the screen or failure of
the previous command.
• The shell provides meta-character && which executes the second command only if the
first command succeeds.
Shell provides meta character || which executes second command only if the
first command fails.
Syntax : Command 1 || command 2
• $ grep 'the' y11 > y11.out || echo 'pattern not found'
pattern not found
• $ grep 'hello' y11 > y11.out || echo 'pattern not found'
$ #output
• $ grep 'the' y11 || echo 'pattern not found'
pattern not found
53
COMMAND GROUPING:
This feature allows shell to execute commands in different way on command line.
There are 4 different forms of this: Sequence command, Group of commands, Chain of
commands, Conditional commands.
Sequence of commands:
sometimes a user wants to execute one or more commands all together at shell prompt
in one hit then process execution metacharacter (;) is used.
cmd 1;cmd 2;…...;cmd N
• $ date;cat y11;who am i
54
Example:
• $ (date;cat y11;who am i) > y11.out
• $ cat y11.out
/dev/null file
sometime, user want to ignore un-necessary output and error messages generated by
any command or programs, and do not want to save this output/error messages, then
/dev/null file is used.
When we redirect any output to this file, its size always remains zero.
For example:
$ cat f123
cat: f123: No such file or directory #error message
$ cat f123 > f1234 2> /dev/null
$ cat /dev/null
$ #prompt will come means nothing stored in /dev/null
To protect special characters (including wild cards) so the shell is not able to interpret
• ESCAPING-provides a \(backslash) before the wild card to remove(or turn off) its
special meaning
• QUOTING-enclosing the wild card, or even entire pattern, within quotes.
ex: ’chap*’ (i.e. pairs of quotes ".." and '..')
$ cat > a* Hiii
55
$ cat > a1 hiii
hello hello
$ ls a* $ cat a\*
a* a1 hiii
$ cat a*
ESCAPING:
• rm chap\* #doesn't remove chap1,chap2
• ls chap0\[1-3\] # chap0[1-3]
• rm chap0\[1-3\]
• $ echo \\ #gives \ in output, in absence of escaping takes std. I/p
and display it in O/p.
$ echo \
> aaa
aaa
• Pass the -e parameter to enable interpretation of backslash escapes.
• Example:
$ echo -e "hello\nworld" $ echo -e "hello\tworld"
hello hello world
world
$ echo -e hello\\nworld
• $ echo "hello\nworld"
hello
hello\nworld
world
• $ echo -e hello\nworld
hellonworld
QUOTING:
• Escaping turns to be tedious when there are too many characters to protect. At that
time quoting will be used.
• Single quote protects all special characters
• Double quote also protect all except the $ and `(backquote)
• $ echo $SHELL
/bin/bash
• $ echo "$SHELL"
/bin/bash
• $ echo '$SHELL'
$SHELL
1 ${var}
Substitute the value of var.
2 ${var:-word}
If var is null or unset, word is substituted for var. The value of vardoes not change.
3 ${var:=word}
If var is null or unset, var is set to the value of word.
4 ${var:?message}
If var is null or unset, message is printed to standard error. This checks that variables
are set correctly.
5 ${var:+word}
If var is set, word is substituted for var. The value of var does not change.
COMMAND SUBSTITUTION:
Command substitution is the mechanism by which the shell performs a given set of commands
and then substitutes their output in the place of the commands.
Syntax
`command`
When performing the command substitution make sure that you use the backquote, not the
single quote character.
57
Example1:
Example2:
Command substitution is generally used to assign the output of a command to a variable.
Each of the following examples demonstrates the command substitution −
#!/bin/sh
DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"
UP=`date ; time`
echo "Uptime is $UP"
58