0% found this document useful (0 votes)
43 views51 pages

UNIT 2 Linux

Uploaded by

Charan baru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views51 pages

UNIT 2 Linux

Uploaded by

Charan baru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

What is Shell in Linux?

In general:
• Shell is a hard protective .
In Linux:
• A shell is a program which takes the command typed
by the user
and converts it into the machine’s understandable
format.
• Shell acts as an interpreter between user and the
operating system
• What is Shell in Linux?
When you log into the system you are given a default
shell.

• When the shell starts up it reads its startup files and may
set
environment variables, command search paths, and
command aliases,
and executes any commands specified in these.

• The following are the different types of shells :


Shell Responsibilities
• The shell is responsible for the execution of all
Program Execution
programs that
you request from your terminal.

• Each time you type in a line to the shell, the shell


analyzes the
line and then determines what to do

• The line that is typed to the shell is known more


formally as the command line

• The shell scans this command line and determines


the name of
the program to be executed and what arguments to
pass to the program.
• Multiple occurrences of whitespace characters are ignored by the
Shell Responsibilities
shell

• This means that when the shell processes this command line:

$ echo when do we eat?

it passes four arguments to the echo program: when, do, we, and
eat?

• Because echo takes its arguments and simply displays


them at the Execution of echo with four arguments.
terminal, separating each by a space character, the
output from the
following becomes easy to understand:
$ echo when do we eat?

when do we eat?
Shell Responsibilities
Variable and Filename Substitution
• Like any other programming language, the shell lets you
assign
values to variables.
•Whenever you specify one of these variables on the command
line,
preceded by a dollar sign, the shell substitutes the value
assigned
to the variable at that point.

variable=value
Displaying the values
echo $variable

• Shell also performs filename substitution on the command


line.
Shell Responsibilities
I/O Redirection
• It is the shell's responsibility to take care of input and output redirection on
the command line
• It scans the command line for the occurrence of the special redirection
characters <, >, or >>
• When you type the command

$ echo Remember to tape Law and Order > reminder

the shell recognizes the special output redirection character > and takes the
next word on the command line as the name of the file that the output is to
be redirected to. In this case, the file is reminder. If reminder already exists
and you have write access to it, the previous contents are lost (if you don't
have write access to it, the shell gives you an error message).
Shell Responsibilities
Pipeline Hookup
• A Unix pipe provides a one-way flow of data.

For example, if a Unix users issues the command

who | sort | lpr

then the Unix shell would create three processes with two
pipes between them:
Shell Responsibilities
Interpreted Programming Language
• The shell has its own built-in programming language.

• This language is interpreted, meaning that the shell


analyzes each statement in the language one line at a
time and then executes it.

• This differs from programming languages such as C and


FORTRAN,in which the programming statements are
typically compiled into a machine-executable form before
they are executed.

• Programs developed in interpreted programming


languages are
typically easier to debug and modify than compiled
ones.
Running a Shell Script
Making Scripts Executable
• After creating a script, we must make it executable.
• This is done with the chmod command.
Example:
$ chmod 744 script_file
$ chmod u+x script_file
Executing the Script
• After the script has been made executable, it is a
command and can be executed just like any other
command
• Two methods of executing a shell script: as an
independent
command or as an argument to a subshell command.
Independent Command
• To Execute a bash shell script we do not need to be in
Running a Shell Script
Child Shell Execution

• To ensure the script is properly executed, we can


create a child
shell and execute it in the new shell.

• This done by specifying the shell before the script name


as in the
following example:

$ bash script_name

• In this case, the interpreter designator line is not


needed, but the
user needs to know which shell the script requires.
The Shell as a Programming Language
• A shell script is a text file that contains executable
commands.
• Although we can execute virtually any command at the
shell
prompt, long sets of commands that are going to be
executed more
than once should be executed using script file

Creating a Script
• To create a shell script first use a text editor to create a
file
containing the commands.

Script Components
• Interpreter Designator Line
• The first line of the script is the interpreter designator
The Shell as a Programming Language
Comments
• Comments are documentation we add in a script to help
us
understand it.
• The interpreter doesn’t use the at all; it simply skips over
them.
• Comments are identified with the pound sign token (#).

Recommended minimum documentation


SCRIPT
The Shell as a Programming Language
Commands
• The most important part of the script is its commands.
• We can use any of the commands available in UNIX.

Example for Shell script

Myfile.scr

Execute the above script


$ myscript.scr
The Shell as a Programming Language

Script Termination (exit command)


• There are 3 streams or standard files. The shell sets up
these 3 standard files and attaches them to user terminal
at the time of logging in.
•Standard i/p ----default source is the keyboard.
•Standard o/p ----default source is the terminal.
•Standard error ----default source is the terminal.
Each of the standard files has a number called a file
descriptor, which is used for identification.
0—standard i/p
1---standard o/p
2---standard error
Shell Metacharacters
• These are special characters that are recognized by the
shell
File Name Substitution
• File name substitution is a feature which allows special
characters and patterns to substituted with file names in
the current directory, or arguments to the case and [[...]]
? match any single character
commands.
* match zero or more characters,
including null
[abc] match any characters between
the brackets
[x–z] match any characters in the
range x to z
[a–ce–g] match any characters in the
range a to c, e to g
[!abc] match any characters not
between the brackets
[!x–z] match any characters not in the
range x to z
Shell Variables
Shell Variables
Accessing a Variable
• To access the value of a variable, the name of the
variable must be preceded
by a dollar sign.
• We use echo command to display the values.
Example:
$x=23
$ echo The variable x contains $x
The variable x contains 23.
To Remove a Variable
• Unset command is used to remove a variable from the
shell.
Example:
$ unset x
$ echo $x
$
Shell Variables
Special shell variables

Parameter Meaning
$0 Name of the current shell script
$1-$9 Positional parameters 1 through 9
$# The number of positional parameters
$* All positional parameters, “$*” is one string
$@ All positional parameters, “$@” is a set of strings
$? Return status of most recently executed command
$$ Process id of current process
Command Substitution
•When a Shell executes a command, the output is directed
to standard output( most of the time, standard output is
associated with monitor
• Shell allows the standard output of one command to be
used as an
argument of another command
• Some times we need to change the output to a string that
we can store in another string or a variable .
• Command substitutions provides the capability to convert
command
the result of a command to a string
Without command substitution
• The command substitution
$ operator that converts the
output of a command to a string is a dollar
(command sign and a set of
string
parentheses. )With command substitution
Shell Commands
• The commands used inside the shell for programming
tasks are
known as the shell commands, those are:
1)expr command
•The expr utility is used to evaluate arithmetic operations,
as shell doesn’t support arithmetic operators.
• Expression will be evaluated by expr utility and the
result is sent to
the standard output.
• Special symbols such as *,>,< must be preceded by a \,
otherwise the
shell treats it as a meta-character and yields wrong
results

Example: $ i = 10 ; j = 10
Shell Commands
2) who | sort
• who command displays who logged onto the system
and provides an account of all users
• It displays a three column output, the first column
displays the user-ids of users currently working on the
system.
• The second column displays the system name.
• The third column displays the date and time.
• Sort command sorts text files. It sorts all the lines from
the standard input.
• who | sort before displaying the who output on the
screen it is piped to sort.
• Sort receives the output of who as standard input, it the
sorts the output according to the first alphabet in each
line and displays it on screen
Shell Commands
3) ls | wc –l

• ls command lists all the files and directories on the


standard output.

• wc –l command counts the number of files it receives as


standard input

• ls command is piped to wc –l command where the


standard output of ls is given as standard input to wc
coomand.

• Thus, it displays the count of files and directories on the


standard output
Shell Commands
4) break
• Break statement causes the control to come out of the
loop instantly.
• It terminates the loop.
#!/bin/sh

a=0

while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
Shell Commands
6) Aliases
• An alias provides a means of creating customized
commands by assigning a name to a command.
• An alias is created by using the alias command. Its
format is
alias name=command-definition
Example :
Using alias to rename the list command
$ alias dir=ls
$ dir
alias of command with options
$alias dir=‘ls –l’
$ dir
Listing aliases
$alias
The Environment
Environmental Variables
• Environmental variables control the user environment.
• Environmental variables are set by the environment, the
operating system, during the startup of your shell.
• Reading environment variables same as shell variables.
For example :
an environment variable named HOME, you can
access the value of this variable by using the dollar($)
sign, for example $HOME
• The environmental variables are in uppercase.
• Commonly used environmental variables are:
• CDPATH, HISTFILE,
• HOME, LOGNAME,
Quoting
• Shell uses a selected set of metacharcters in commands.
• Metacharcters are characters that have a special
interpretation.
• For example the pipe (|) .
• In order to use them as a normal text we must tell the shell
interpreter that they should be interpreted differently.
Quote
• This is called quoting the metacharcters.
• To achieve quoting sthere are three metacharcters
collectively as quotes, Double Single
Backsla
Quote Quote
sh
s s
Quoting
Backslash
• The backslash metacharcter (\) is used to change the
interpretation of the character that follows it, i.e., it converts
a literal character into a special character and vice versa.
Example:
• The character n is interpreted as a literal character by the
shell to change its interpretation as a newline character we
use backslash before it (\n).
• Similarly the use of a greater than symbol (>) in a command
is interpreted as a special character (output redirection), to
change its interpretation as a literal text we use a backslash
before it (\>)

$echo My name is - \> Ramesh\n


My name is ->Ramesh
Quoting
Double Quotes
• Double quotes (“) are used to change the meaning of
several characters.
• They change the special interpretation of most
metacharcters like <,>,?,& and so on.
• These metacharcters are treated as literal characters.

Example:
$ echo “Metacharcters are : >,<,?,|,&“
Metacharcters are : >,<,?,|,&

• Double quotes cannot remove the special interpretation of a


dollar sign in front of a variable and single quotes.

$ echo a = 10
Quoting
Single Quotes

• Like double quotes, single quotes change the special


interpretation of metacharcters.
• It not only treats metacharcters like >,<,?,$ and so on as
literals but also the metacharcters dollar sign ($) and every
double quotes.

Example:
$ echo a = 10
$ echo ‘characters are < > “b” $a ? &’
characters are < > “b” $a ? &
TEST Command
• The test command is used to check file types and compare
values. Test is used in
conditional execution. It is used for:
• Numeric comparison
• File attributes comparisons
• Perform string comparisons.
test command syntax
test condition
OR
test condition && true-command
OR
test condition || false-command
OR
test condition && true-command || false-
command
TEST Command
Numeric comparison
• Numerical tests are implied when comparison between values of two
numbers is to be done.
• Different numerical operators are :
Numerical Comparison Operators Used by test
Operator Syntax Description

-eq INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2

-ge INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2

-gt INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2

-le INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2

-lt INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2

-ne INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2


TEST Command
String Comparisons
• String comparison can be done using test command itself.
• Condition Description

Str1 = Str2 True if str1 is equal to str2

Str1 != Str2 True if str1 is not equal to str2

Strg Ture if string strg is not null and is assigned

-n strg True if string strg is not a null (or empty string)

-z strg True if string strg is a null (or empty) string

Str1 == str2 True if string str1 is equal to str2


TEST Command
File attributes comparisons
• It checks all the file attributes. It checks whether a file is an
ordinary
Option
file, or Description
a directory, or it has read, write or executable
permissions
-f file True if file exists and is a regular file

-r file True if file exists and having a read permission

-w file True if file exists and have a write permission

-x file True if file exists and have a executable permission

-d file True if file exists and is a directory

-s file True if file exists and has a size greater than zero

-e file True if file exists

File1 –nt file2 True if file1 is newer than file2

File1 –ot file2 True if file1 is older than file2

File1 –ef file2 True if file1 is linked to file2


Control Structures
• Control structures alter the flow of the program

• Control Structures are: 1) conditional statements 2) control


statements

1. if
2.if –else
3.Nested if
4.case
Control Statements:
5. loops
a. for
b. While
c. Until
2. Handling of signals.
Control Structures
• THE SIMPLE IF STATEMENT

if [ condition ]; then
statements
fi

• Executes the statements only if condition is true


Control Structures
• THE IF-THEN-ELSE STATEMENT

if [ condition ]; then
statements-1
else
statements-2
fi

• executes statements-1 if condition is true


• executes statements-2 if condition is false
Control Structures
• THE NESTED IF

if [ condition ]; then
statements
elif [ condition ]; then
statement
else
statements
fi

• The word elif stands for “else if”


• It is part of the if statement and cannot be used
by itself
Control Structures
THE CASE STATEMENT
• use the case statement for a decision that is based on
multiple choices
Syntax:
case word in
pattern1) command-list1
;;
pattern2) command-list2
;;
patternN) command-listN
;;
esac
case pattern
• checked against word for match
may also contain:
*
?
Control Structures
THE WHILE LOOP

• Purpose:
To execute commands in “command-list” as long
as “expression” evaluates to true

Syntax:
while [ expression ]
do
command-list
done
Control Structures
THE UNTIL LOOP

• Purpose:
To execute commands in “command-list” as long
as “expression” evaluates to false

Syntax:
until [ expression ]
do
command-list
done
Control Structures
THE FOR LOOP

• Purpose:
To execute commands as many times as the
number of words in the “argument-list”

Syntax:
for variable in argument-list
do
commands
done
Control Structures
Signals on Linux
% kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX

^C is 2 - SIGINT
Arithmetic in Shell
Shell Arithmetic

• Use to perform arithmetic operations.

Syntax:
expr op1 math-operator op2

Examples:
$ expr 1 + 3
$ expr 2 - 1
$ expr 10 / 2
$ expr 20 % 3
$ expr 10 \* 3
$ echo `expr 6 + 3`
Note:
expr 20 %3 - Remainder read as 20 mod 3 and remainder is 2.
expr 10 \* 3 - Multiplication use \* and not * since its wild card.
Functions
• A shell function is similar to a shell script
• stores a series of commands for execution later
• shell stores functions in memory
• shell executes a shell function in the same shell that called it
• Where to define
• In .profile
• In your script
• Or on the command line
• Remove a function
• Use unset built-in
Functions
• must be defined before they can be referenced
• usually placed at the beginning of the script

Syntax:

function-name () {
statements
}
Functions
Function parameters

• Need not be declared


• Arguments provided via function call are accessible
inside function as $1, $2, $3, …

• $# reflects number of parameters


• $0 still contains name of script
(not name of function)
Functions
Local Variables in Functions
• Variables defined within functions are global, i.e. their

values are known throughout the entire shell program

• Keyword “local” inside a function definition makes


referenced variables “local” to that function
Debugging Shell Scripts
• Debugging is troubleshooting errors that may occur
during the
execution of a program/script
• The following two commands can help you debug a bash
shell script:
• echo
use explicit output statements to trace execution
• set
Debugging Shell Scripts
Debugging using “set”
• The “set” command is a shell built-in command
• has options to allow flow of execution
–v option prints each line as it is read
–x option displays the command and its arguments
–n checks for syntax errors
• options can turned on or off
To turn on the option: set -xv
To turn off the options: set +xv

• Options can also be set via she-bang line


#! /bin/bash -xv
Step 1: Run set -x

$set -x

Step 2 : write below code in any editor(gedit) and name file as set.sh

x=10

while [ $x -gt 0 ]; do

x=$[ $x-1 ]

echo $x

sleep 2

done

Step 3: make script executable

$chmod +x set.sh

Step 4 : Execute the Script

$./set.sh or bash set.sh

You might also like