Module 2
File Attributes and Permissions and Knowing them
‱ ls command can be used to obtain a list of all filenames in the
current directory.
‱ -l option can be used to obtain a detailed list of attributes of all
files in the current directory.
‱ For example:
‱ The header includes the following attributes:
1) Type & Perm
‱ ‱ This represents the file-type and the permission given
on the file.
‱ File-Type
‱  The first character indicates type of the file as
shown below:
‱ i) hyphen (-) for regular file ii) d for Directory file
‱ iii) l for Symbolic link file iv) b for block special file v) c
for character special file
2) Link
‱ This indicates the number of file names maintained by the system.
‱ This does not mean that there are so many copies of the file. (Link
similar to pointer).
3) Owner
‱ This represents the owner of the file. This is the user who created this
file.
4) Group
‱ This represents the group of the owner.
‱ Each group member can access the file depending on the permission
assigned.
‱ The privileges of the group are set by the owner of the file and not by
the group members.
‱ When the system admin creates a user account, he has to assign these
parameters to the user:
i) The user-id (UID) and ii) The group-id (GID)
5) Size
‱ This represents the file size in bytes.
‱ It is the number of character in the file rather than the actual size
occupied on disk.
6) Date & Time
‱ This represents the last modification date and the time of the file.
‱ If you change only the permissions /ownership of the file, the modification
time remains unchanged.
‱ If at least one character is added/removed from the file then this field will
be updated.
7) File name
‱ This represents the file or the directory name.
ls
‱ This command can be used to list the files and directories stored in the
current directory.
Syntax:
ls [options] [argument]
For example:
$ ls
‱ bin lib users work
‱ With options it can provide information about the size, type of file,
permissions, dates of file creation, change and access.
‱ The mode field is given by the -l option and consists of 10 characters.
‱ The first character is one of the following:
‱ Designations are as follows:
r read permission
w write permission
x execute permission
- no permission
‱ Example:
Listing Directory Attributes
‱ $ls -d : can be used to list only names of directories,
not the files in the directory.
‱ However, this command will not list all subdirectories in
the current directory.
‱ For example:
‱ Directories are easily identified in the listing by the first
character(d) of the first column.
Changing File Permissions
‱A file is created with a default set of permission.
‱chmod command can be used to change
permission of a file.
‱This command can be used in two ways: 1)
Relative mode and 2) Absolute mode
1. Relative Permissions
‱ This command can be used to add/delete permission
for specific type of user (owner, group or others).
‱ This command can be used to
→ change only those permissions specified in the
command line and
→ leave the other permissions unchanged.
‱ Syntax:
‱ chmod category operation permission filename
‱ This command takes 4 arguments:
1) category can be
‱ u → user (owner)
‱ g → group o → others a → all (ugo)
2) operation can be
+ → assign
- → remove
= → absolute
3) permission can be
‱ r → read
‱ w → write
‱ x → execute
‱ ‱ This command can also accept multiple file names.
‱ ‱ Example:
‱ $ chmod u+x note1 note2 note3
Recursively Changing File Permissions
‱ chmod command can be used to change recursively permission of
all the files and subdirectories found in the current directory.
‱ Example:
chmod -R a+x c_progs // current directory c_progs
‱ Here, all files and subdirectories are made executable for all
users in current directory c_progs.
‱ Absolute Permissions
‱ ‱ This command can be used to add/delete permission for all type of users (owner, group
or others).
‱ ‱ This command can be used to change all permissions specified in the command line.
‱ ‱ Syntax:
‱ chmod octal_value filename
‱ ‱ This command takes 2 arguments:
‱ 1) octal value contains 3 octal digits to represent 3 type of users (owner, group or
others).
‱ 1) First digit is for user
‱ 2) Second digit is for group and
‱ 3) Third digit is for others
‱ Each digit represents a permission as shown below:
Binary octal permission significance
000 0 --- no permission
001 1 --x executable only
010 2 -w- writable only
011 3 -wx write and executable
100 4 r-- read only
101 5 r-x read and executable only
110 6 rw- readable and writable
111 7 rwx readable, writable and executable
‱ For ex: octal_value of 644(110 100 100) means
‱ → user can read & write only
‱ → group can read only
‱ → others can read only
‱ 2) Filename whose permission has to changed.
‱ ‱ Example:
‱ It is the directory permissions that determine whether a file
can be deleted or not.
‱ i) 777 signify all permissions for all categories, but still we can
prevent a file from being deleted.
‱ ii) 000 signifies absence of all permissions for all categories,
but still we can delete a file.
‱ ‱ The system administrator can change the file permissions of
every user.
‱ i) Only owner can change the file permissions.
‱ ii) User cannot change other user‘s file‘s permissions.
Changing File Ownership
‱ While creating an account on Unix, it assigns a owner ID and a group
ID to each user.
‱ ‱ The permissions are assigned to each user based on the Owner and
the Groups.
‱ ‱ Two commands are available to change the owner and the group of
files:
‱ 1) chown (change owner) is used to change the owner of a file.
‱ 2) chgrp (change group) is used to change the group of a file.
1 chown
‱ ‱ This command can be used to change the ownership of a file.
‱ ‱ Syntax:
‱ chown USERNAME FILENAME
‱ ‱ The value of the user can be the name or uid(user id) of a user on the
system.
‱ Now, new owner will have same file permissions as that of old owner.
‱ Old owner cannot edit "note" since there is no write privilege for group and
others.
‱ Old owner cannot get back the ownership.
‱ Only super user can change the ownership of any file.
‱ But normal users can change the ownership of only those files that they own
2 chgrp
‱ ‱ This command can be used to change the group-ownership of a file.
‱ ‱ Syntax:
‱ chgrp GROUPNAME FILENAME
‱ ‱ The value of the group can be the name or GID(group ID) of a group on the
system.
Directory Permissions
‱ ‱ The default permissions of a directory are: rwxr-xr-x (755).
‱ 1) Read directory permission grants the ability to view a file.
‱ 2) Write directory permission grants the ability to add, change or remove files
from the directory.
‱ 3) Execute directory permission grants the ability to list (ls) the directory
content or search (find) for files in the directory.
‱ A directory must never be writable by group and others .
Shells Interpretive Cycle
‱ The shell performs following activities in its interpretive-cycle:
1) The shell
→ issues the prompt ($) and
→ waits for user to enter a command (like ls chap*).
2) After a command is entered, the shell
→ scans the command-line for metacharacters (like 'ls chap*') and
→ expands the abbreviations to recreate a simplified command-line ('ls chap1 chap2').
3) Then, the shell
→ passes the command-line to the kernel for execution and
→ waits for the command to complete its task.
4) After the command is executed, the shell
→ issues the prompt ($) again and
→ waits for the user to enter a next command.
Wild Cards and Filename Generation
‱ The metacharacters that are used to construct the generalized pattern for matching
filenames belong to a category called wild-cards.
1. Metacharacters * and ?
‱ The metacharacter "*" matches any number of characters including none.
‱ Examples:
‱ When the shell encounters this command line, it identifies the * immediately as a
wild-card. It then looks in the current directory and recreates the command line as
below
‱ $ ls chap chap01 chap02 chap03 chap04 chapx chapy chapz
‱ The shell now hands over this command to the kernel which uses its process creation
facilities to run the command.
‱ The metacharacter ? matches a single character.
‱ Both * and ? operate with some restrictions.
‱ The * doesn’t match all filenames beginning with a dot (.) or forward slash(/).
2. Character Class
‱ The character class comprises a set of characters enclosed by the rectangular brackets, [ and ],.
‱ The character class matches a single character in the class.
‱ For example:
‱ This can be combined with any string or another wild-card expression.
‱ Example:
Negating the Character Class (!)
‱ Not operator (!) can be used to negate the character class.
‱ For example,
‱ $ls [!a-zA-Z]* //To match all filenames that don’t begin with an alphabetic character.
Matching Totally Dissimilar Patterns
Removing the Special Meanings of Wild Cards (Escaping and Quoting)
‱ Escaping is providing a  (backslash) before the wildcard to remove its special meaning.
‱ Example:
‱ Quoting is enclosing the wild-card within quotes to remove its special meaning.
‱ When a command argument is enclosed in quotes, the meanings of all enclosed special characters
are turned off.
‱ Example:
Redirection : Three Standard Files
‱ The shell associates three standard files with the terminal:
→ two for display and
→ one for the keyboard.
‱ When a user logs in, the shell makes available three standard files.
‱ Each standard file is associated with a default device:
1) Standard input: The file representing input which is connected to the
keyboard.
2) Standard output: The file representing output which is connected to the
display.
3) Standard error: The file representing error messages that come from
the command or shell.
‱ This file is also connected to the display.
Default three Standard Files
1. Standard Input
‱ The standard input can represent three input sources:
1) The keyboard, the default source.
2) A file using redirection with the < symbol.
3) Another program using a pipeline.
‱ By default, the shell directs standard input from the keyboard.
‱ Example:
‱ The redirect input symbol (<) instructs the shell to redirect a command’s input to come
from the specified file instead of from the keyboard.
Redirecting input
2. Standard Output
‱ The standard output can represent three possible destinations:
‱ 1) The terminal, the default destination.
‱ 2) A file using the redirection symbols > and >>.
‱ 3) As input to another program using a pipeline.
‱ By default, the shell directs standard output from a command to the screen.
‱ Example:
‱ The redirect output symbol (>) instructs the shell to redirect the output of a command to the
specified file instead of to the screen.
>> can be used to append to a existing file.
3. Standard Error
‱ By default, the shell directs standard error from a command to the screen.
‱ Example:
‱ The redirect output symbol (>) instructs the shell to redirect the error messages of a command to
the specified file instead of to the screen.
‱ Example:
Redirecting Output & Error
4. Filters: Using Both Standard Input and Standard Output
‱ UNIX commands can be grouped into four categories:
1) Directory-oriented commands like mkdir, rmdir and cd, and basic file
handling commands like cp, mv and rm use neither standard input nor
standard output.
2) Commands like ls, pwd, who etc. don’t read standard input but they
write to standard output.
3) Commands like lp(The lp command is used to print files on Unix and Linux
systems. The name "lp" stands for "line printer“) that read standard input but
don’t write to standard output.
4) Commands like cat, wc, cmp etc. that use both standard input and
standard output are called filters.
‱ Example:
$ cat calc.txt
(4*2)+2
$ bc < calc.txt > result.txt
$ cat result.txt
10
‱ Here, this command performs arithmetic calculations that are specified as expressions in
input file
"calc.txt" and redirect the output to a file "result.txt".
‱ Running 2 or more commands have following disadvantages:
1) The process is slow. The second command cant act unless the first has completed its
job.
2) You require an intermediate file that has to be removed after the first command has
completed its run.
3) When handling large files, temporary files can build up early and eat up disk space in
no time
Pipe : Connecting Commands
‱ Pipe is another form of output redirection.
‱ With piping, the output of a command can be used as input (piped) to a subsequent
command.
‱ ‱ Syntax:
‱ $ command1 | command2
‱ Here, Output from command1 is piped into input for command2.
‱ The symbol '|' denotes a pipe.
‱ Example:
‱ $ ls -l | lp
‱ Here pipe is used to send the output of ls to the lp to print a hard copy of the listing of
the current directory.
‱ Pipeline can be used with 2 or more commands. But the user should know the
behavioral properties of each commands to place them there.
‱ Example:
‱ $ls -l | wc -l | lp
When a Command Needs to be Ignorant of its Source
‱ If we wish to find total size of all C programs contained in the working
directory, we can use the command:
$ wc –c *.c
‱ However, it also shows the usage for each file(size of each file). We are
not interested in individual statistics.
‱ Solution: We must make wc ignorant of its input source. So, feed the
concatenated output stream of all the .c files to wc –c as its input:
‱ $ cat *.c | wc –c
tee : Splitting the Output
‱ This is an external command that handles a character stream by duplicating its input.
‱ This command
→ saves one copy in a file and
→ writes the other copy to standard output.
‱ This command is also a filter and hence can be placed anywhere in a pipeline.
‱ Example:
‱ $ who | tee users.lst //to display the output of who and save this output in a file users.lst
Command Substitution
‱ Command substitution allows to substitute the output of one command into a given command
line.
‱ ‱ Syntax:
‱ `command`
‱ ‱ Here, the command must be enclosed between backquotes.
‱ ‱ Example:
1.grep
‱ g/re/p means “globally search for a regular expression and print all lines containing it”.
‱ This command can be used to search a file(s) for lines that have a certain pattern.
‱ This command
→ scans the file for a pattern and
→ displays
i) lines containing the pattern or
ii) line numbers
‱ Syntax:
grep pattern file(s)
‱ Example:
grep “MH” student.lst // display lines containing "MH" from the file student.lst
‱ Patterns with and without quotes is possible.
‱ Quote is mandatory when pattern involves more than one word.
‱ Example:
‱ grep “My Document” student.lst // display lines containing "My Document" from student.lst
‱ This command can be used with multiple filenames.
Example:
‱ grep “MH” student.lst vtu.lst rank.lst
grep Options
‱ Linux supports below listed options:
‱ To understand the working of different options, let us consider we have following information in file
student.lst.
Ignores Case
‱ -i (ignore) option can be used to search all lines containing a pattern regardless of uppercase and
lowercase distinction.
Deleting Lines
‱ -v option can be used to print all lines that do not contain the specified pattern in a file.
‱ Example:
‱ Displaying Line Number
‱ ‱ -n (line number) option can be used to display line numbers containing the pattern.
‱ ‱ Example:
‱ Counting Lines Containing the Pattern
‱ -c (line count) option can be used to count number of lines containing the pattern.
‱ Example:
‱ grep -c ‘MH’ student.lst
‱ 2
‱ Displaying Filenames
‱ -l (list filename) option can be used to list out the files containing the pattern.
‱ Example:
‱ grep -l ‘MH’ *.lst
‱ Matching Multiple Pattern
‱ -e option can be used to match multiple pattern in a file.
‱ Example:
‱ grep -e ‘MH’ -e ‘VV’ student.lst
‱ Taking Pattern From File
‱ -f option can be used to place all matched pattern in a separate file, one pattern per
line.
Basic Regular Expression (BRE)
‱ grep uses an expression of a different type to match a group of similar patterns.
‱ This command
‱ → uses an elaborate metacharacter set and
‱ → can perform amazing matches.
‱ If an expression uses metacharacters, it is termed a regular expression.
‱ Regular expression can be classified as
1) BRE (Basic Regular Expression) and
2) ERE (Extended Regular Expression)
‱ grep supports
‱ → BRE by default and
‱ → ERE with the –E option.
‱ Character subset of BRE is listed below:
‱ Character Class
‱ The character class comprises a set of characters enclosed by the rectangular brackets, [ and ].
‱ The character class matches a single character in the class.
‱ When you use range, make sure that the character on the left of the hyphen has a lower ASCII
value than the one on the right.
‱ caret (^) can be used to negate the character class.
‱ For example:
‱ Example:
‱ $ grep -i "[Mm][Hh]" demo_file // matches all the words such as MH mH Mh mh
Asterisk (*)
‱ The asterisk (*) refers to the immediately preceding character.
‱ It indicates zero or more occurrences of the previous character.
‱ g* → nothing or g, gg, ggg, etc.
‱ lg* → l or lg, lgg, lggg, etc.
‱ Example:
‱ $ grep "isaa*c" demo_file // matches isac isaac or isaaac
Dot(.)
‱ A dot (.) matches a single character.
‱ Example:
‱ $ grep "2..." demo_file // matches all 4 character words
beginning with 2
‱ Regular expression ".*" → signifies any number of characters or
none
‱ Example:
‱ $ grep prog.c.* demo_file // matches all c and cpp extension
filenames
Specifying Pattern Locations (^ and $)
‱ Following two metacharcters can match a pattern at the beginning or end of a line.
‱ Anchoring a pattern is often necessary when it can occur in more than one place in a line, and we
are interested in its occurrence only at a particular location.
‱ Example:
‱ grep “^2” emp.lst //Selects lines starting with 2
‱ grep “7
$” emp.lst //Selects lines where salary between number b/w 7000 to 7999
‱ Extended Regular Expression (ERE) and egrep
‱ ERE can be used to match dissimilar patterns with a single expression.
‱ This uses some additional characters as listed below:
The + and ?
‱ The ERE set includes two special characters,+ and ?. They are often used in place of the * to
restrict the matching scope. They signify the following:
+Matches one or more occurrence of previous character
? Matches zero or one occurrence of the previous character
$grep –E “[aA]gg?arwal” chap01.txt
Matching Multiple Pattern(|,( and ))
‱ The | is the delimiter of multiple patterns. Using it we can locate both san and
vas from the file and without using –e option twice
$grep –E ‘sam|vas’ chap01.txt
The ERE thus handles the problem easily but offers an even better alternative.
The characters ( and ), let you group pattern
$grep –E ‘(sen|das)dupta’ chap01.txt
Ordinary(or Local) Variable
‱ A variable is a character string to which the user assigns a value.
‱ The value assigned can be a number, text, filename, device, or any other type of data.
‱ Syntax:
‱ variable = value // variable definition
‱ The value of variables are stored in the ASCII format.
‱ For example:
‱ $ x=50
‱ $ echo $x //displays 50
‱ In command line, all words that are preceded by a $ are identified and evaluated as variables.
‱ A variable can be removed with unset and protected from reassignment by readonly. Both are shell
internal commands.
‱ $ set count=5
‱ $ readonly size = 10
‱ The variables exist only for a short time during the execution of a shell script.
‱ The variables are local to the user’s shell environment.
‱ The variables are not available for the other scripts or processes.
‱ As the variables are defined and used by specific users, they are also called user-defined variables.
Environment Variable
‱ Environmental variables are used to provide information to the programs you use.
‱ These variables control the behavior of the system.
‱ They determine the environment in which the user works.
‱ If environment variables are not set properly, the users may not be able to use some
commands.
‱ Environment variables are so called because they are available in the user's total
environment
‱ i.e. the sub-shells that run shell scripts and mail commands and editors.
‱ Some variables are set by the system, others by the users, others by the shell programs.
env command can be used to display environment variables.
‱ For example:
1) HOME
‱ This variable indicates the home directory of the current user.
‱ This variable is set for a user by the system admin in /etc/passwd
2) IFS
‱ This variable contains a string of characters that are used as word separator in the command line.
‱ The string normally consists of the space, tab and newline characters.
3) LOGNAME
‱ This variable shows the username.
4) MAIL
‱ This variable specifies the path to user’s mailbox.
5) MAILCHECK
‱ This variable determines how often the shell checks the file for the arrival of new mail.
6) PATH
‱ This variable specifies the locations in which the shell should look for commands.
‱ Usually, the PATH variable can be set as follows:
‱ $PATH=/bin:/usr/bin
‱ 7) PS1 and PS2
‱ The shell has 2 prompts:
1) The primary prompt $ is the one the user normally sees on the monitor. $ is stored in PS1.
 The user can change the primary prompt as follows:
‱ $ PS1="C>"
‱ C> //similar to windows
2) The secondary prompt > is stored in PS2.
8) SHELL
‱ This variable specifies the current shell being used by the users.
‱ Different types of shells are:
1) Bourne shell /bin/sh 2) C-shell /bin/csh 3) Korn shell /bin/ksh
‱ This variable is set for a user by the system admin in /etc/passwd.
9) TERM
‱ This variable indicates the terminal type that is used.
‱ Every terminal has certain characteristics that are defined in a separate control file in the
terminfo directory.
‱ If TERM is not set correctly, vi will not work and the display will be faulty.
Uses of Local variables
1) Setting pathnames: If a pathname is used several times in a script, we can assign it to
a variable and use it as an argument to any command.
2) Using command substitution: We can assign the result of execution of a command to a
variable. The command to be executed must be enclosed in backquotes.
3) Concatenating variables and strings: Two variables can be concatenated to form a new
variable.
‱ Example: $ base=foo ; ext=.c
‱ $ file=$base$ext
‱ $ echo $file // prints foo.c
File .profile
‱ A profile file is a start-up file of an UNIX user.
‱ This file gets executed as soon as the user logs in.
‱ This file is a shell script that will be present in the home directory of each user.
‱ The system admin provides each user with a profile with a minimum working
environment.
‱ However, the user can customize the profile as per their requirement.
‱ i.e. The user can
‱ → assign suitable values to the environment variables.
‱ → add and modify statements in the profile file.
‱ ‱ This file can be any one of the two:
‱ 1) A specific file for each individual user with responsibility for the user environment.
‱ 2) A universal file for all users with responsibility for the general environment.
‱ ‱ The user can view his ".profile" as follows:
‱ $ cat .profile
‱ MAIL= /var/mail/kumar
‱ PATH=/bin:/usr/bin
‱ PS1='$'
‱ PS2='>'
‱ SHELL=/usr/bin/bash
‱ TERM= tty1
Command Line Arguments
‱ Shell scripts can accept arguments from the command line.
‱ Shell scripts can be run non-interactively and be used with redirection and pipelines.
‱ The arguments are assigned to special shell variables called shell parameters.
‱ The shell parameters are reserved for specific functions.
‱ Different shell parameters:
1) $#: Stores the number of command-line arguments.
2) $0, $1, $2, $3: These are called positional parameters which represent command line arguments.
‱ $0: Stores the filename of the current script.
‱ $1: Stores the first argument.
‱ $2: Stores the second argument
‱ $3: Stores the third argument
3) $*: Stores all the arguments entered on the command line ($1 $2 ...).
4) "$@": Stores all arguments entered on the command line, individually quoted ("$1" "$2")
5) $?: Stores the exit status of the last command that was executed.
6) $$: Stores Pid of the current shell.
7) $!: Stores PID of the last background job.
‱ Example: A shell script (program2.sh) to read and display
various shell parameters from the
command line.
#!/bin/sh
echo "Total Number of Parameters : $#"
echo "File Name: $0"
echo "First Parameter : $1"
echo "Second Parameter : $2"
echo "Quoted Values: $*"
echo "Quoted Values: $@"
$echo "Exit value: $?"
echo "PID of current shell: $$"
exit and Exit Status of a Command
‱ exit command can be used to terminate a program(or script).
‱ This command returns value which will be available to the script's parent
process.
‱ The $? variable contains exit status of the last command executed.
‱ Exit status is a numerical value returned by every command upon its
completion.
‱ A command returns an exit status of
1) zero (0) upon successful execution and
2) non-zero upon unsuccessful execution i.e. an error condition.
‱ Exit status can be used to devise program-logic that branches into
different paths depending on
success or failure of a command.
‱ Example: A shell script to find whether the number is equal or not.
#!/bin/usr
x=5
y=7
If [ $x -eq $y ]
then
echo “$x and $y are equal”
else
echo “$x and $y are not equal”
fi
Logical Operators for Conditional Execution
‱ Two logical operators can be used for conditional execution: 1) && and 2) ||
‱ 1) && Operator
‱ ‱ Syntax:
‱ cmd1 && cmd2
‱ ‱ Here, cmd2 gets executed only when cmd1 succeeds.
‱ 2) || Operator
‱ ‱ Syntax:
‱ cmd1 || cmd2
‱ ‱ Here, cmd2 gets executed only when cmd1 fails.
‱ ‱ Example: A script to illustrate the usage of && and ||.
test Command and its Shortcut
‱ Usually, if-construct cannot directly handle the true or false value returned by evaluation of an
expression.
‱ So, test command can be used to handle the true or false value returned by evaluation of an
expression.
‱ Test command
→ uses certain operators to evaluate the condition on its right and
→ returns either a true or false exit status.
‱ Then, if-construct uses the exit status for making decisions.
‱ Test command
→ does not display any output
→ sets the parameter $? (exit status).
‱ Test command works in 3 ways:
1) Compare two numbers.
2) Compares two strings or a single one for a null value.
3) Checks files attributes.
String Comparison
‱ Test command is also used for testing strings.
String program to find whether both strings
are equal or not
#!/bin/bash
a=“hello”
b=“hello”
If [ $a = $b ]
then
echo “equal”
else
echo “not equal”
fi
Write a small shell script that will show how to use logical OR ( || ) operator
between two conditions.
#!/bin/bash
read -p "Enter First Numeric Value: " first
read -p "Enter Second Numeric Value: " second
if [ $first -le 10 ] || [ $second -gt 20 ]
then
echo "Atleast one conditions is true"
else
echo "Both conditions are failed"
fi
Multiple logic in a single statement: sample shell script to take input a
number from the user Check if the number is between 10 - 20 Or number
is between 100 - 200
#!/bin/bash
read -p "Enter a number: " num
if ([ $num -ge 10 ] && [ $num -le 20 ]) || ([ $num -ge 100 ] && [ $num -le
200 ])
then
echo "Input number ($num) is between 10-20 or 100-200"
else
echo "Input number ($num) is neither between 10-20 nor 100-200"
fi
If statement
‱ The if...fi statement is the fundamental control statement that allows Shell to make
decisions and execute statements conditionally.
‱ Syntax
‱ The Shell expression is evaluated in the above syntax. If the resulting value is true,
given statement(s) are executed. If the expression is false then no statement would be executed. Most
of the times, comparison operators are used for making decisions.
if...else statements
‱ If else statements are useful decision-making statements which can be used to
select an option from a given set of options.
‱ Unix Shell supports following forms of if
else statement −
1. if...fi statement
2. if...else...fi statement
3. if...elif...else...fi statement
while statement
for Statement
‱ for loop can be used to iterate over all items(or strings) within a list.
‱ Syntax:
‱ Here, list consists of a set of items(or strings).
‱ Each item of the list is picked up and assigned to the "variable".
‱ The iteration continues until all items are picked from the array.
‱ Example: A script to display elements of an array.
‱ Possible Sources of List
‱ Possible sources of list are
1) List from variables
2) List from command substitution
3) List from wildcards and
4) List from positional parameters
1) List from Variables
‱ Example: A script to evaluate & display a set of variables using for-loop.
case Statement
‱ case statement is basically a “multi-way” decision statement.
‱ ‱ This is used when we must choose among many alternatives.
‱ ‱ This also handles string tests, but in a more efficient manner than if statement.
‱ ‱ Syntax:
Ai module
Ai module
Ai module
Ai module
Ai module
Ai module
Ai module
Ai module
Ai module

Ai module

  • 1.
  • 2.
    File Attributes andPermissions and Knowing them ‱ ls command can be used to obtain a list of all filenames in the current directory. ‱ -l option can be used to obtain a detailed list of attributes of all files in the current directory. ‱ For example: ‱ The header includes the following attributes:
  • 3.
    1) Type &Perm ‱ ‱ This represents the file-type and the permission given on the file. ‱ File-Type ‱  The first character indicates type of the file as shown below: ‱ i) hyphen (-) for regular file ii) d for Directory file ‱ iii) l for Symbolic link file iv) b for block special file v) c for character special file
  • 4.
    2) Link ‱ Thisindicates the number of file names maintained by the system. ‱ This does not mean that there are so many copies of the file. (Link similar to pointer). 3) Owner ‱ This represents the owner of the file. This is the user who created this file. 4) Group ‱ This represents the group of the owner. ‱ Each group member can access the file depending on the permission assigned. ‱ The privileges of the group are set by the owner of the file and not by the group members. ‱ When the system admin creates a user account, he has to assign these parameters to the user: i) The user-id (UID) and ii) The group-id (GID)
  • 5.
    5) Size ‱ Thisrepresents the file size in bytes. ‱ It is the number of character in the file rather than the actual size occupied on disk. 6) Date & Time ‱ This represents the last modification date and the time of the file. ‱ If you change only the permissions /ownership of the file, the modification time remains unchanged. ‱ If at least one character is added/removed from the file then this field will be updated. 7) File name ‱ This represents the file or the directory name.
  • 6.
    ls ‱ This commandcan be used to list the files and directories stored in the current directory. Syntax: ls [options] [argument] For example: $ ls ‱ bin lib users work ‱ With options it can provide information about the size, type of file, permissions, dates of file creation, change and access.
  • 8.
    ‱ The modefield is given by the -l option and consists of 10 characters. ‱ The first character is one of the following:
  • 9.
    ‱ Designations areas follows: r read permission w write permission x execute permission - no permission ‱ Example:
  • 10.
    Listing Directory Attributes ‱$ls -d : can be used to list only names of directories, not the files in the directory. ‱ However, this command will not list all subdirectories in the current directory. ‱ For example: ‱ Directories are easily identified in the listing by the first character(d) of the first column.
  • 11.
    Changing File Permissions ‱Afile is created with a default set of permission. ‱chmod command can be used to change permission of a file. ‱This command can be used in two ways: 1) Relative mode and 2) Absolute mode
  • 12.
    1. Relative Permissions ‱This command can be used to add/delete permission for specific type of user (owner, group or others). ‱ This command can be used to → change only those permissions specified in the command line and → leave the other permissions unchanged.
  • 13.
    ‱ Syntax: ‱ chmodcategory operation permission filename ‱ This command takes 4 arguments: 1) category can be ‱ u → user (owner) ‱ g → group o → others a → all (ugo) 2) operation can be + → assign - → remove = → absolute 3) permission can be ‱ r → read ‱ w → write ‱ x → execute
  • 14.
    ‱ ‱ Thiscommand can also accept multiple file names. ‱ ‱ Example: ‱ $ chmod u+x note1 note2 note3
  • 15.
    Recursively Changing FilePermissions ‱ chmod command can be used to change recursively permission of all the files and subdirectories found in the current directory. ‱ Example: chmod -R a+x c_progs // current directory c_progs ‱ Here, all files and subdirectories are made executable for all users in current directory c_progs.
  • 16.
    ‱ Absolute Permissions ‱‱ This command can be used to add/delete permission for all type of users (owner, group or others). ‱ ‱ This command can be used to change all permissions specified in the command line. ‱ ‱ Syntax: ‱ chmod octal_value filename ‱ ‱ This command takes 2 arguments: ‱ 1) octal value contains 3 octal digits to represent 3 type of users (owner, group or others). ‱ 1) First digit is for user ‱ 2) Second digit is for group and ‱ 3) Third digit is for others ‱ Each digit represents a permission as shown below:
  • 17.
    Binary octal permissionsignificance 000 0 --- no permission 001 1 --x executable only 010 2 -w- writable only 011 3 -wx write and executable 100 4 r-- read only 101 5 r-x read and executable only 110 6 rw- readable and writable 111 7 rwx readable, writable and executable
  • 18.
    ‱ For ex:octal_value of 644(110 100 100) means ‱ → user can read & write only ‱ → group can read only ‱ → others can read only ‱ 2) Filename whose permission has to changed. ‱ ‱ Example:
  • 19.
    ‱ It isthe directory permissions that determine whether a file can be deleted or not. ‱ i) 777 signify all permissions for all categories, but still we can prevent a file from being deleted. ‱ ii) 000 signifies absence of all permissions for all categories, but still we can delete a file. ‱ ‱ The system administrator can change the file permissions of every user. ‱ i) Only owner can change the file permissions. ‱ ii) User cannot change other user‘s file‘s permissions.
  • 20.
    Changing File Ownership ‱While creating an account on Unix, it assigns a owner ID and a group ID to each user. ‱ ‱ The permissions are assigned to each user based on the Owner and the Groups. ‱ ‱ Two commands are available to change the owner and the group of files: ‱ 1) chown (change owner) is used to change the owner of a file. ‱ 2) chgrp (change group) is used to change the group of a file.
  • 21.
    1 chown ‱ ‱This command can be used to change the ownership of a file. ‱ ‱ Syntax: ‱ chown USERNAME FILENAME ‱ ‱ The value of the user can be the name or uid(user id) of a user on the system.
  • 22.
    ‱ Now, newowner will have same file permissions as that of old owner. ‱ Old owner cannot edit "note" since there is no write privilege for group and others. ‱ Old owner cannot get back the ownership. ‱ Only super user can change the ownership of any file. ‱ But normal users can change the ownership of only those files that they own
  • 23.
    2 chgrp ‱ ‱This command can be used to change the group-ownership of a file. ‱ ‱ Syntax: ‱ chgrp GROUPNAME FILENAME ‱ ‱ The value of the group can be the name or GID(group ID) of a group on the system.
  • 24.
    Directory Permissions ‱ ‱The default permissions of a directory are: rwxr-xr-x (755). ‱ 1) Read directory permission grants the ability to view a file. ‱ 2) Write directory permission grants the ability to add, change or remove files from the directory. ‱ 3) Execute directory permission grants the ability to list (ls) the directory content or search (find) for files in the directory. ‱ A directory must never be writable by group and others .
  • 25.
    Shells Interpretive Cycle ‱The shell performs following activities in its interpretive-cycle: 1) The shell → issues the prompt ($) and → waits for user to enter a command (like ls chap*). 2) After a command is entered, the shell → scans the command-line for metacharacters (like 'ls chap*') and → expands the abbreviations to recreate a simplified command-line ('ls chap1 chap2'). 3) Then, the shell → passes the command-line to the kernel for execution and → waits for the command to complete its task. 4) After the command is executed, the shell → issues the prompt ($) again and → waits for the user to enter a next command.
  • 26.
    Wild Cards andFilename Generation ‱ The metacharacters that are used to construct the generalized pattern for matching filenames belong to a category called wild-cards.
  • 27.
    1. Metacharacters *and ? ‱ The metacharacter "*" matches any number of characters including none. ‱ Examples: ‱ When the shell encounters this command line, it identifies the * immediately as a wild-card. It then looks in the current directory and recreates the command line as below ‱ $ ls chap chap01 chap02 chap03 chap04 chapx chapy chapz ‱ The shell now hands over this command to the kernel which uses its process creation facilities to run the command. ‱ The metacharacter ? matches a single character.
  • 28.
    ‱ Both *and ? operate with some restrictions. ‱ The * doesn’t match all filenames beginning with a dot (.) or forward slash(/).
  • 29.
    2. Character Class ‱The character class comprises a set of characters enclosed by the rectangular brackets, [ and ],. ‱ The character class matches a single character in the class. ‱ For example: ‱ This can be combined with any string or another wild-card expression. ‱ Example:
  • 30.
    Negating the CharacterClass (!) ‱ Not operator (!) can be used to negate the character class. ‱ For example, ‱ $ls [!a-zA-Z]* //To match all filenames that don’t begin with an alphabetic character. Matching Totally Dissimilar Patterns
  • 31.
    Removing the SpecialMeanings of Wild Cards (Escaping and Quoting) ‱ Escaping is providing a (backslash) before the wildcard to remove its special meaning. ‱ Example: ‱ Quoting is enclosing the wild-card within quotes to remove its special meaning. ‱ When a command argument is enclosed in quotes, the meanings of all enclosed special characters are turned off. ‱ Example:
  • 32.
    Redirection : ThreeStandard Files ‱ The shell associates three standard files with the terminal: → two for display and → one for the keyboard. ‱ When a user logs in, the shell makes available three standard files. ‱ Each standard file is associated with a default device: 1) Standard input: The file representing input which is connected to the keyboard. 2) Standard output: The file representing output which is connected to the display. 3) Standard error: The file representing error messages that come from the command or shell. ‱ This file is also connected to the display.
  • 33.
  • 34.
    1. Standard Input ‱The standard input can represent three input sources: 1) The keyboard, the default source. 2) A file using redirection with the < symbol. 3) Another program using a pipeline. ‱ By default, the shell directs standard input from the keyboard. ‱ Example: ‱ The redirect input symbol (<) instructs the shell to redirect a command’s input to come from the specified file instead of from the keyboard.
  • 35.
  • 36.
    2. Standard Output ‱The standard output can represent three possible destinations: ‱ 1) The terminal, the default destination. ‱ 2) A file using the redirection symbols > and >>. ‱ 3) As input to another program using a pipeline. ‱ By default, the shell directs standard output from a command to the screen. ‱ Example: ‱ The redirect output symbol (>) instructs the shell to redirect the output of a command to the specified file instead of to the screen.
  • 37.
    >> can beused to append to a existing file.
  • 38.
    3. Standard Error ‱By default, the shell directs standard error from a command to the screen. ‱ Example: ‱ The redirect output symbol (>) instructs the shell to redirect the error messages of a command to the specified file instead of to the screen. ‱ Example:
  • 39.
  • 40.
    4. Filters: UsingBoth Standard Input and Standard Output ‱ UNIX commands can be grouped into four categories: 1) Directory-oriented commands like mkdir, rmdir and cd, and basic file handling commands like cp, mv and rm use neither standard input nor standard output. 2) Commands like ls, pwd, who etc. don’t read standard input but they write to standard output. 3) Commands like lp(The lp command is used to print files on Unix and Linux systems. The name "lp" stands for "line printer“) that read standard input but don’t write to standard output. 4) Commands like cat, wc, cmp etc. that use both standard input and standard output are called filters.
  • 41.
    ‱ Example: $ catcalc.txt (4*2)+2 $ bc < calc.txt > result.txt $ cat result.txt 10 ‱ Here, this command performs arithmetic calculations that are specified as expressions in input file "calc.txt" and redirect the output to a file "result.txt". ‱ Running 2 or more commands have following disadvantages: 1) The process is slow. The second command cant act unless the first has completed its job. 2) You require an intermediate file that has to be removed after the first command has completed its run. 3) When handling large files, temporary files can build up early and eat up disk space in no time
  • 42.
    Pipe : ConnectingCommands ‱ Pipe is another form of output redirection. ‱ With piping, the output of a command can be used as input (piped) to a subsequent command. ‱ ‱ Syntax: ‱ $ command1 | command2 ‱ Here, Output from command1 is piped into input for command2. ‱ The symbol '|' denotes a pipe. ‱ Example: ‱ $ ls -l | lp ‱ Here pipe is used to send the output of ls to the lp to print a hard copy of the listing of the current directory. ‱ Pipeline can be used with 2 or more commands. But the user should know the behavioral properties of each commands to place them there. ‱ Example: ‱ $ls -l | wc -l | lp
  • 43.
    When a CommandNeeds to be Ignorant of its Source ‱ If we wish to find total size of all C programs contained in the working directory, we can use the command: $ wc –c *.c ‱ However, it also shows the usage for each file(size of each file). We are not interested in individual statistics. ‱ Solution: We must make wc ignorant of its input source. So, feed the concatenated output stream of all the .c files to wc –c as its input: ‱ $ cat *.c | wc –c
  • 44.
    tee : Splittingthe Output ‱ This is an external command that handles a character stream by duplicating its input. ‱ This command → saves one copy in a file and → writes the other copy to standard output. ‱ This command is also a filter and hence can be placed anywhere in a pipeline. ‱ Example: ‱ $ who | tee users.lst //to display the output of who and save this output in a file users.lst Command Substitution ‱ Command substitution allows to substitute the output of one command into a given command line. ‱ ‱ Syntax: ‱ `command` ‱ ‱ Here, the command must be enclosed between backquotes. ‱ ‱ Example:
  • 45.
    1.grep ‱ g/re/p means“globally search for a regular expression and print all lines containing it”. ‱ This command can be used to search a file(s) for lines that have a certain pattern. ‱ This command → scans the file for a pattern and → displays i) lines containing the pattern or ii) line numbers ‱ Syntax: grep pattern file(s) ‱ Example: grep “MH” student.lst // display lines containing "MH" from the file student.lst ‱ Patterns with and without quotes is possible. ‱ Quote is mandatory when pattern involves more than one word. ‱ Example: ‱ grep “My Document” student.lst // display lines containing "My Document" from student.lst
  • 46.
    ‱ This commandcan be used with multiple filenames. Example: ‱ grep “MH” student.lst vtu.lst rank.lst grep Options ‱ Linux supports below listed options:
  • 47.
    ‱ To understandthe working of different options, let us consider we have following information in file student.lst. Ignores Case ‱ -i (ignore) option can be used to search all lines containing a pattern regardless of uppercase and lowercase distinction.
  • 48.
    Deleting Lines ‱ -voption can be used to print all lines that do not contain the specified pattern in a file. ‱ Example: ‱ Displaying Line Number ‱ ‱ -n (line number) option can be used to display line numbers containing the pattern. ‱ ‱ Example:
  • 49.
    ‱ Counting LinesContaining the Pattern ‱ -c (line count) option can be used to count number of lines containing the pattern. ‱ Example: ‱ grep -c ‘MH’ student.lst ‱ 2 ‱ Displaying Filenames ‱ -l (list filename) option can be used to list out the files containing the pattern. ‱ Example: ‱ grep -l ‘MH’ *.lst ‱ Matching Multiple Pattern ‱ -e option can be used to match multiple pattern in a file. ‱ Example: ‱ grep -e ‘MH’ -e ‘VV’ student.lst ‱ Taking Pattern From File ‱ -f option can be used to place all matched pattern in a separate file, one pattern per line.
  • 50.
    Basic Regular Expression(BRE) ‱ grep uses an expression of a different type to match a group of similar patterns. ‱ This command ‱ → uses an elaborate metacharacter set and ‱ → can perform amazing matches. ‱ If an expression uses metacharacters, it is termed a regular expression. ‱ Regular expression can be classified as 1) BRE (Basic Regular Expression) and 2) ERE (Extended Regular Expression) ‱ grep supports ‱ → BRE by default and ‱ → ERE with the –E option. ‱ Character subset of BRE is listed below:
  • 52.
    ‱ Character Class ‱The character class comprises a set of characters enclosed by the rectangular brackets, [ and ]. ‱ The character class matches a single character in the class. ‱ When you use range, make sure that the character on the left of the hyphen has a lower ASCII value than the one on the right. ‱ caret (^) can be used to negate the character class. ‱ For example: ‱ Example: ‱ $ grep -i "[Mm][Hh]" demo_file // matches all the words such as MH mH Mh mh
  • 53.
    Asterisk (*) ‱ Theasterisk (*) refers to the immediately preceding character. ‱ It indicates zero or more occurrences of the previous character. ‱ g* → nothing or g, gg, ggg, etc. ‱ lg* → l or lg, lgg, lggg, etc. ‱ Example: ‱ $ grep "isaa*c" demo_file // matches isac isaac or isaaac
  • 54.
    Dot(.) ‱ A dot(.) matches a single character. ‱ Example: ‱ $ grep "2..." demo_file // matches all 4 character words beginning with 2 ‱ Regular expression ".*" → signifies any number of characters or none ‱ Example: ‱ $ grep prog.c.* demo_file // matches all c and cpp extension filenames
  • 55.
    Specifying Pattern Locations(^ and $) ‱ Following two metacharcters can match a pattern at the beginning or end of a line. ‱ Anchoring a pattern is often necessary when it can occur in more than one place in a line, and we are interested in its occurrence only at a particular location. ‱ Example: ‱ grep “^2” emp.lst //Selects lines starting with 2 ‱ grep “7
$” emp.lst //Selects lines where salary between number b/w 7000 to 7999
  • 56.
    ‱ Extended RegularExpression (ERE) and egrep ‱ ERE can be used to match dissimilar patterns with a single expression. ‱ This uses some additional characters as listed below: The + and ? ‱ The ERE set includes two special characters,+ and ?. They are often used in place of the * to restrict the matching scope. They signify the following: +Matches one or more occurrence of previous character ? Matches zero or one occurrence of the previous character $grep –E “[aA]gg?arwal” chap01.txt
  • 57.
    Matching Multiple Pattern(|,(and )) ‱ The | is the delimiter of multiple patterns. Using it we can locate both san and vas from the file and without using –e option twice $grep –E ‘sam|vas’ chap01.txt The ERE thus handles the problem easily but offers an even better alternative. The characters ( and ), let you group pattern $grep –E ‘(sen|das)dupta’ chap01.txt
  • 58.
    Ordinary(or Local) Variable ‱A variable is a character string to which the user assigns a value. ‱ The value assigned can be a number, text, filename, device, or any other type of data. ‱ Syntax: ‱ variable = value // variable definition ‱ The value of variables are stored in the ASCII format. ‱ For example: ‱ $ x=50 ‱ $ echo $x //displays 50 ‱ In command line, all words that are preceded by a $ are identified and evaluated as variables. ‱ A variable can be removed with unset and protected from reassignment by readonly. Both are shell internal commands. ‱ $ set count=5 ‱ $ readonly size = 10 ‱ The variables exist only for a short time during the execution of a shell script. ‱ The variables are local to the user’s shell environment. ‱ The variables are not available for the other scripts or processes. ‱ As the variables are defined and used by specific users, they are also called user-defined variables.
  • 59.
    Environment Variable ‱ Environmentalvariables are used to provide information to the programs you use. ‱ These variables control the behavior of the system. ‱ They determine the environment in which the user works. ‱ If environment variables are not set properly, the users may not be able to use some commands. ‱ Environment variables are so called because they are available in the user's total environment ‱ i.e. the sub-shells that run shell scripts and mail commands and editors. ‱ Some variables are set by the system, others by the users, others by the shell programs. env command can be used to display environment variables. ‱ For example:
  • 60.
    1) HOME ‱ Thisvariable indicates the home directory of the current user. ‱ This variable is set for a user by the system admin in /etc/passwd 2) IFS ‱ This variable contains a string of characters that are used as word separator in the command line. ‱ The string normally consists of the space, tab and newline characters.
  • 61.
    3) LOGNAME ‱ Thisvariable shows the username. 4) MAIL ‱ This variable specifies the path to user’s mailbox. 5) MAILCHECK ‱ This variable determines how often the shell checks the file for the arrival of new mail. 6) PATH ‱ This variable specifies the locations in which the shell should look for commands. ‱ Usually, the PATH variable can be set as follows: ‱ $PATH=/bin:/usr/bin ‱ 7) PS1 and PS2 ‱ The shell has 2 prompts: 1) The primary prompt $ is the one the user normally sees on the monitor. $ is stored in PS1.  The user can change the primary prompt as follows: ‱ $ PS1="C>" ‱ C> //similar to windows 2) The secondary prompt > is stored in PS2.
  • 62.
    8) SHELL ‱ Thisvariable specifies the current shell being used by the users. ‱ Different types of shells are: 1) Bourne shell /bin/sh 2) C-shell /bin/csh 3) Korn shell /bin/ksh ‱ This variable is set for a user by the system admin in /etc/passwd. 9) TERM ‱ This variable indicates the terminal type that is used. ‱ Every terminal has certain characteristics that are defined in a separate control file in the terminfo directory. ‱ If TERM is not set correctly, vi will not work and the display will be faulty.
  • 63.
    Uses of Localvariables 1) Setting pathnames: If a pathname is used several times in a script, we can assign it to a variable and use it as an argument to any command. 2) Using command substitution: We can assign the result of execution of a command to a variable. The command to be executed must be enclosed in backquotes. 3) Concatenating variables and strings: Two variables can be concatenated to form a new variable. ‱ Example: $ base=foo ; ext=.c ‱ $ file=$base$ext ‱ $ echo $file // prints foo.c
  • 64.
    File .profile ‱ Aprofile file is a start-up file of an UNIX user. ‱ This file gets executed as soon as the user logs in. ‱ This file is a shell script that will be present in the home directory of each user. ‱ The system admin provides each user with a profile with a minimum working environment. ‱ However, the user can customize the profile as per their requirement. ‱ i.e. The user can ‱ → assign suitable values to the environment variables. ‱ → add and modify statements in the profile file. ‱ ‱ This file can be any one of the two: ‱ 1) A specific file for each individual user with responsibility for the user environment. ‱ 2) A universal file for all users with responsibility for the general environment. ‱ ‱ The user can view his ".profile" as follows:
  • 65.
    ‱ $ cat.profile ‱ MAIL= /var/mail/kumar ‱ PATH=/bin:/usr/bin ‱ PS1='$' ‱ PS2='>' ‱ SHELL=/usr/bin/bash ‱ TERM= tty1
  • 66.
    Command Line Arguments ‱Shell scripts can accept arguments from the command line. ‱ Shell scripts can be run non-interactively and be used with redirection and pipelines. ‱ The arguments are assigned to special shell variables called shell parameters. ‱ The shell parameters are reserved for specific functions. ‱ Different shell parameters: 1) $#: Stores the number of command-line arguments. 2) $0, $1, $2, $3: These are called positional parameters which represent command line arguments. ‱ $0: Stores the filename of the current script. ‱ $1: Stores the first argument. ‱ $2: Stores the second argument ‱ $3: Stores the third argument 3) $*: Stores all the arguments entered on the command line ($1 $2 ...). 4) "$@": Stores all arguments entered on the command line, individually quoted ("$1" "$2") 5) $?: Stores the exit status of the last command that was executed. 6) $$: Stores Pid of the current shell. 7) $!: Stores PID of the last background job.
  • 67.
    ‱ Example: Ashell script (program2.sh) to read and display various shell parameters from the command line. #!/bin/sh echo "Total Number of Parameters : $#" echo "File Name: $0" echo "First Parameter : $1" echo "Second Parameter : $2" echo "Quoted Values: $*" echo "Quoted Values: $@" $echo "Exit value: $?" echo "PID of current shell: $$"
  • 68.
    exit and ExitStatus of a Command ‱ exit command can be used to terminate a program(or script). ‱ This command returns value which will be available to the script's parent process. ‱ The $? variable contains exit status of the last command executed. ‱ Exit status is a numerical value returned by every command upon its completion. ‱ A command returns an exit status of 1) zero (0) upon successful execution and 2) non-zero upon unsuccessful execution i.e. an error condition. ‱ Exit status can be used to devise program-logic that branches into different paths depending on success or failure of a command. ‱ Example: A shell script to find whether the number is equal or not.
  • 69.
    #!/bin/usr x=5 y=7 If [ $x-eq $y ] then echo “$x and $y are equal” else echo “$x and $y are not equal” fi
  • 70.
    Logical Operators forConditional Execution ‱ Two logical operators can be used for conditional execution: 1) && and 2) || ‱ 1) && Operator ‱ ‱ Syntax: ‱ cmd1 && cmd2 ‱ ‱ Here, cmd2 gets executed only when cmd1 succeeds. ‱ 2) || Operator ‱ ‱ Syntax: ‱ cmd1 || cmd2 ‱ ‱ Here, cmd2 gets executed only when cmd1 fails. ‱ ‱ Example: A script to illustrate the usage of && and ||.
  • 72.
    test Command andits Shortcut ‱ Usually, if-construct cannot directly handle the true or false value returned by evaluation of an expression. ‱ So, test command can be used to handle the true or false value returned by evaluation of an expression. ‱ Test command → uses certain operators to evaluate the condition on its right and → returns either a true or false exit status. ‱ Then, if-construct uses the exit status for making decisions. ‱ Test command → does not display any output → sets the parameter $? (exit status). ‱ Test command works in 3 ways: 1) Compare two numbers. 2) Compares two strings or a single one for a null value. 3) Checks files attributes.
  • 73.
    String Comparison ‱ Testcommand is also used for testing strings.
  • 74.
    String program tofind whether both strings are equal or not #!/bin/bash a=“hello” b=“hello” If [ $a = $b ] then echo “equal” else echo “not equal” fi
  • 75.
    Write a smallshell script that will show how to use logical OR ( || ) operator between two conditions. #!/bin/bash read -p "Enter First Numeric Value: " first read -p "Enter Second Numeric Value: " second if [ $first -le 10 ] || [ $second -gt 20 ] then echo "Atleast one conditions is true" else echo "Both conditions are failed" fi
  • 76.
    Multiple logic ina single statement: sample shell script to take input a number from the user Check if the number is between 10 - 20 Or number is between 100 - 200 #!/bin/bash read -p "Enter a number: " num if ([ $num -ge 10 ] && [ $num -le 20 ]) || ([ $num -ge 100 ] && [ $num -le 200 ]) then echo "Input number ($num) is between 10-20 or 100-200" else echo "Input number ($num) is neither between 10-20 nor 100-200" fi
  • 77.
    If statement ‱ Theif...fi statement is the fundamental control statement that allows Shell to make decisions and execute statements conditionally. ‱ Syntax ‱ The Shell expression is evaluated in the above syntax. If the resulting value is true, given statement(s) are executed. If the expression is false then no statement would be executed. Most of the times, comparison operators are used for making decisions.
  • 79.
    if...else statements ‱ Ifelse statements are useful decision-making statements which can be used to select an option from a given set of options. ‱ Unix Shell supports following forms of if
else statement − 1. if...fi statement 2. if...else...fi statement 3. if...elif...else...fi statement
  • 82.
  • 83.
    for Statement ‱ forloop can be used to iterate over all items(or strings) within a list. ‱ Syntax: ‱ Here, list consists of a set of items(or strings). ‱ Each item of the list is picked up and assigned to the "variable". ‱ The iteration continues until all items are picked from the array. ‱ Example: A script to display elements of an array.
  • 85.
    ‱ Possible Sourcesof List ‱ Possible sources of list are 1) List from variables 2) List from command substitution 3) List from wildcards and 4) List from positional parameters
  • 86.
    1) List fromVariables ‱ Example: A script to evaluate & display a set of variables using for-loop.
  • 90.
    case Statement ‱ casestatement is basically a “multi-way” decision statement. ‱ ‱ This is used when we must choose among many alternatives. ‱ ‱ This also handles string tests, but in a more efficient manner than if statement. ‱ ‱ Syntax: