Unit - 4 LSP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

UNIT 4 : SHELL PROGRAMMING

Shell Script-Writing and Executing :


To write and execute a shell script in Linux, follow these steps:
1. Open a text editor like nano, vim or gedit.
2. Write your shell commands in the editor.
3. Save the file with a .sh extension. For example, myscript.sh.
4. Make the file executable with the chmod command. For example, chmod +x
myscript.sh.
5. Run the script with the ./ command followed by the script name. For example,
./myscript.sh.
Here is an example shell script that prints "Hello World!" to the terminal:
#!/bin/bash
echo "Hello World!"
Save the above script as hello.sh and make it executable with chmod +x hello.sh.
Then run it with ./hello.sh and you should see "Hello World!" printed to the
terminal.
There are several ways to execute a shell script in Linux :
1. Execute as a regular command: You can simply call the script as a command
from the terminal by typing the name of the script preceded by "./" (assuming
that the current directory is where the script is located). For example:
$ ./my_script.sh

2. Execute with explicit interpreter: You can explicitly specify which interpreter
to use to execute the script. This is useful if the script is not executable or if
you want to use a different interpreter than the default one. For example:
$ bash my_script.sh
$ sh my_script.sh
$ python my_script.py

3. Add execute permission and run as command: You can add the execute
permission to the script and then call it like a regular command. For example:
$ chmod +x my_script.sh
$ my_script.sh
4. Source the script: You can source the script to run its commands in the current
shell environment. This is useful when you want to modify environment
variables or define functions that will be used by other commands. For
example:
$ source my_script.sh
$ . my_script.sh # same as above

5. Run in the background: You can run the script in the background by appending
"&" to the command. For example:
$ ./my_script.sh &
Each of these ways of executing a shell script has its own advantages and
disadvantages depending on the situation.

Parameters and Variables :


Parameters and variables are essential components of shell scripting in Linux.
They allow you to create dynamic and flexible scripts that can handle different
inputs and conditions. Here are the details of each:
Parameters: Parameters are variables that are passed to a shell script when it is
executed. They allow you to customize the behavior of a script based on the input
provided. In Linux, there are two types of parameters:
1. Positional parameters: Positional parameters are a set of variables in shell
programming that hold arguments or values passed to the shell script or
function at the time of execution. These parameters are accessed using special
variables that start with the dollar sign ($).

The positional parameters are numbered from 1 to 9, and they correspond to


the arguments that are passed to the script or function. If there are more than
9 arguments, the remaining ones can be accessed using special syntax such as
${10}, ${11}, and so on.

For example, if we have a shell script named "myscript.sh" that accepts two
arguments, we can access them using the $1 and $2 variables within the script.
The following is an example of how to use positional parameters in a shell
script:
#!/bin/bash
echo "The first argument is $1"
echo "The second argument is $2"

Then, when we run the script with the arguments "hello" and "world", we will
get the following output:
$ ./myscript.sh hello world
The first argument is hello
The second argument is world

2. Special parameters: Special parameters in shell scripting are predefined


variables that hold special meanings and values in a script. These parameters
are useful for manipulating command-line arguments, exit codes, and other
important values in the script. Here are some of the most commonly used
special parameters:
1. $0: Holds the name of the script or shell itself.
2. $1, $2, $3...: Represent the command-line arguments passed to the script,
with $1 being the first argument, $2 the second, and so on.
3. $#: Represents the number of command-line arguments passed to the
script.
4. $*: Represents all the command-line arguments passed to the script as a
single string.
5. $@: Represents all the command-line arguments passed to the script as
separate strings.
6. $?: Holds the exit code of the last command executed in the script.

These special parameters can be used in shell scripts to perform various


operations and checks, such as conditional branching, error handling, and user
input validation. For example, to check the number of arguments passed to a
script, we can use the $# parameter and compare it against a desired value.
Similarly, to access the exit code of a previous command, we can use the $?
parameter and execute further commands based on its value.
Variables: Variables are used to store values that can be used throughout a shell
script. In Linux, variables are defined using the following syntax:
variable_name=value
Here are the different types of variables in Linux:
1. Local variables: Local variables are variables that are defined and used within
a shell script or a shell function. These variables are not available to other
scripts or functions that are called from the current script or function. Local
variables are created using the local command and are typically used to store
temporary data or intermediate results within a script.

Here is an example of defining a local variable within a shell script:


#!/bin/bash
myfunc() {
local myvar="local value"
echo "Inside function: myvar is $myvar"
}
myvar="global value"
echo "Before function call: myvar is $myvar"
myfunc
echo "After function call: myvar is $myvar"

In this example, the myfunc function defines a local variable myvar and
assigns it the value "local value". The echo statement within the function
displays the value of myvar as "local value".
Outside the function, a global variable myvar is defined and assigned the
value "global value". When the script is executed, the value of myvar is
displayed before and after the function call. The output will be:
Before function call: myvar is global value
Inside function: myvar is local value
After function call: myvar is global value
As you can see, the value of myvar inside the function is different from the
value of myvar outside the function. This is because the local keyword was
used to define a local variable within the function. Any changes made to the
value of the local variable within the function do not affect the value of the
global variable outside the function.
2. Environment variables: Environment variables are variables that are set and
maintained by the operating system or user session and can be used by
processes running within that session. These variables contain information
that the operating system and other programs can use to customize behavior
and execution.
Here are some commonly used environment variables in Linux:
• PATH: Contains a list of directories that the shell searches when a
command is entered. If the command is not found in the current directory,
the directories listed in the PATH variable are searched in order.
• HOME: Points to the current user's home directory. This is where a user's
files and directories are stored by default.
• USER: Contains the name of the current user.
• SHELL: Specifies the default shell for the current user.
• PWD: Contains the current working directory.
• TERM: Specifies the terminal type.
• DISPLAY: Specifies the X server display to use.
• EDITOR: Specifies the default editor to use.
• LANG: Specifies the language and locale settings for the current user.
These environment variables can be accessed and modified using various shell
commands and programming constructs.
Environment variables are typically defined in the .bashrc or .bash_profile
files.
3. Shell variables: Shell variables are variables that are created and maintained
by the shell itself. These variables are used to customize the behavior of the
shell and to store temporary data.
Some common shell variables are:
$HOME: This variable contains the path to the current user's home directory.
$PATH: This variable contains a list of directories that the shell will search
when you enter a command.
$USER: This variable contains the name of the current user.
$SHELL: This variable contains the path to the shell that is currently running.
$PWD: This variable contains the path to the current working directory.
You can also create your own shell variables by assigning a value to a variable
name. For example, MYVAR="Hello World" creates a variable named
MYVAR with the value "Hello World". You can then access the value of the
variable by prefixing the variable name with a $ symbol, such as $MYVAR.
Shell variables are local to the current shell process by default, meaning they
are not accessible by other processes. However, you can also export a variable
to make it available to child processes by using the export command. For
example, export MYVAR exports the MYVAR variable to child processes.

4. Readonly variables:
Readonly variables in shell refer to variables whose values cannot be changed
or modified once they are assigned. They are used to create constant values
that remain the same throughout the execution of the shell script. Readonly
variables are useful in preventing unintentional modification of critical
variables in a script.
The syntax to declare a readonly variable is as follows:
readonly variable=value
Once declared, the value of the variable cannot be changed using the =
operator or any other means. Attempts to modify the value of a readonly
variable will result in an error.
For example, consider the following script that uses a readonly variable:
#!/bin/bash
readonly PI=3.14159
echo "The value of PI is: $PI"
# Trying to modify the value of PI
PI=3
echo "The new value of PI is: $PI"

When executed, the above script will produce the following output:
The value of PI is: 3.14159
./test.sh: line 7: PI: readonly variable
As can be seen from the output, the value of PI is displayed correctly in the
first echo statement, but the attempt to modify its value results in an error
because it is a readonly variable.
Keyword Variables :
In shell programming, a keyword is a reserved word that has a specific meaning
and purpose within the context of the shell script. These keywords are part of the
shell's syntax and cannot be used as variable names or other identifiers in the
script.
Some of the commonly used keywords in shell programming are:
1. if: used to test a condition and execute a set of commands if the condition
is true
Syntax:
if [ condition ]
then
commands
fi

2. else: used in conjunction with if to execute a set of commands if the


condition is false
Syntax:
if [ condition ]
then
commands1
else
commands2
fi

3. elif: used in conjunction with if to test additional conditions


Syntax:
if [ condition1 ]
then
commands1
elif [ condition2 ]
then
commands2
else
commands3
fi
4. for: used to execute a set of commands a specified number of times
Syntax:
for variable in list
do
commands
done

5. while: used to execute a set of commands as long as a condition is true


Syntax:
while [ condition ]
do
commands
done

6. until: used to execute a set of commands as long as a condition is false


Syntax:
until [ condition ]
do
commands
done

7. case: used to perform different actions based on different conditions


Syntax:
case variable in
pattern1)
commands1
;;
pattern2)
commands2
;;
*)
default commands
;;
esac
8. function: used to define a function that can be called later in the script
Syntax:
function_name () {
commands
}

# or

function function_name {
commands
}

9. return: used to return a value from a function


Syntax:
return value
10. echo: used to print a message to the terminal
Syntax:
echo message
11. read: used to read input from the user and store it in a variable
Syntax:
read variable_name
12. export: used to export a variable to the environment
Syntax:
export variable_name=value

13.typeset: used to define or change the properties of a variable


Syntax:
typeset -a variable

14.unset: used to delete a variable

syntax:

unset variable
Command Line Arguments :
Command line arguments refer to the values passed to a shell script or program
when it is executed in the command line. They are used to specify options,
parameters, or input data for the script or program to process.
Command line arguments are stored in special variables called positional
parameters. The first argument is stored in $1, the second argument in $2, and so
on. $0 stores the name of the script or program itself.
For example, consider the following script named my_script.sh:
#!/bin/bash
echo "The name of the script is: $0"
echo "The first argument is: $1"
echo "The second argument is: $2"
If we run the script with the command ./my_script.sh foo bar, it will produce the
following output:
The name of the script is: ./my_script.sh
The first argument is: foo
The second argument is: bar
We can also use special parameters like $# to get the number of arguments passed
to the script, $@ to get all arguments as a list, and $* to get all arguments as a
single string.
For example:
#!/bin/bash
echo "Number of arguments: $#"
echo "All arguments as a list: $@"
echo "All arguments as a single string: $*"
If we run the script with the command ./my_script.sh foo bar baz, it will produce
the following output:
Number of arguments: 3
All arguments as a list: foo bar baz
All arguments as a single string: foo bar baz
You can also use command line arguments to control how your script is executed.
For example, the following code uses the -v option to print the value of the
$VERBOSE variable:

if [ -n "$1" ] && [ "$1" == "-v" ]; then

echo "The VERBOSE variable is set"

fi

Exit and Exit Status of a Command:


In Linux, every command that is executed returns an exit status. The exit status
is an integer value that indicates whether the command has executed successfully
or encountered an error. The exit status can be checked using the $? variable in
the shell.
The exit status ranges from 0 to 255, with 0 indicating successful execution and
any non-zero value indicating an error. Some common exit statuses and their
meanings are:
0: Successful execution
1-127: Command encountered an error
128-255: Command encountered a fatal error
The exit command is used to terminate the execution of a shell script or a
command. The exit command takes an optional exit status as an argument. If no
exit status is provided, the exit status of the last executed command is used.
Here's an example of using the exit command with an exit status:
if [ "$EUID" -ne 0 ] #Check if the user is root
then echo "Please run as root"
exit 1
fi
echo "Performing some operation..."
exit 0 #Exit with status 0 (success)

In the above example, the script checks if the user running the script is the root
user using the $EUID environment variable. If the user is not the root user, an
error message is displayed and the script exits with an exit status of 1. If the user
is the root user, some operation is performed and the script exits with an exit
status of 0 (success).
Logical Operators for Conditional Execution:
In shell programming, logical operators are used for conditional execution of
commands. There are three logical operators commonly used:
1. AND (&&): The && operator is used to execute a command if the
previous command succeeds or returns a 0 exit status.

Syntax:
command1 && command2

Example:
ls file.txt && echo "File exists"
In the above example, the echo command will only be executed if the ls
command succeeds in finding the file.txt.
2. OR (||): The || operator is used to execute a command if the previous
command fails or returns a non-zero exit status.
Syntax:
command1 || command2
Example:
ls file.txt || echo "File not found"
In the above example, the echo command will only be executed if the ls
command fails in finding the file.txt.
3. NOT (!): The ! operator is used to negate the exit status of a command.
Syntax:
! command
Example:
! ls file.txt
In the above example, the ! operator will negate the exit status of the ls
command, i.e., if the file is not found, the exit status will be 0, and if the
file is found, the exit status will be non-zero.
The Set and Shift Command:
set:
The set command is a built-in command in the shell that allows you to set or
change the values of the positional parameters. It can also be used to set values
of shell options and positional parameters.
The syntax of the set command is as follows:
set [options] [arguments]
Some common options for the set command include:
-e: Exit immediately if a command exits with a non-zero status.
-u: Treat unset variables as an error.
-x: Print commands and their arguments as they are executed.

shift:
The shift command is another built-in command in the shell that allows you to
shift the positional parameters to the left. This means that the value of $2 becomes
the value of $1, the value of $3 becomes the value of $2, and so on. The syntax
of the shift command is as follows:
shift [n]
The optional argument n specifies the number of positions to shift. If n is not
specified, it defaults to 1.
Expanding NULL and UNSET Variables:
In shell scripting, it is common to encounter null or unset variables. In such cases,
the shell will try to expand the variable, and the behavior will depend on whether
the variable is null or unset.
A null variable is one that is defined, but has no value. In other words, it is an
empty variable. When a null variable is expanded, it is replaced with an empty
string. For example:
var=""
echo $var # Output: (nothing)

An unset variable, on the other hand, is one that has not been defined at all. When
an unset variable is expanded, it is replaced with an empty string as well, but the
shell also generates a warning. For example:
echo $var # Output: (nothing, plus a warning)
You can use the following syntax to expand a null or unset variable:
${parameter:-word}
Example:
//if color is not set then blue is used
echo "the sky is ${color:-"blue"}"
//Only print not assign to color
echo "the sky is ${color:="blue"}"
/print as well as assign it

//To display error message if value is not set


${parameter:?word}

echo "the sky is ${color:?"color not set"}"


bash: color: color not set

color="blue"
$ echo "the sky is ${color:?"color not set"}"
the sky is blue
In shell scripting, we can also test whether a variable is null or unset using the -z
and -n operators. The -z operator returns true if the variable is null or empty,
while the -n operator returns true if the variable is not null or empty. For example:
var=""
if [ -z "$var" ]; then
echo "Variable is null or empty"
fi

if [ -n "$var" ]; then
echo "Variable is not null or empty"
fi
Here, the first if statement will execute because the variable var is null. The
second if statement will not execute because the variable is empty.

Functions:
In shell programming, a function is a block of code that can be defined once and
called multiple times throughout the script. Functions are useful for code reuse
and for keeping the main body of the script organized and readable.
To define a function in shell, the syntax is as follows:
function_name() {
# function code here
}
Here, function_name is the name of the function, and the code to be executed is
enclosed in curly braces.
You can then call the function by simply typing its name in your script:
function_name
Functions can take parameters, just like scripts. The parameters are passed to the
function in the same way as they are passed to scripts:
function_name() {
parameter1=$1
parameter2=$2
# function code goes here
}

function_name value1 value2


We can also use the return statement to return a value from a function:
function_name() {
# function code goes here
return 5
}

function_name
echo $?

The above code will print 5 to the console, which is the value returned by the function.

Aliases:
In Linux, an alias is a way to create a short name for a command or a set of commands.
It helps to save time and typing effort by allowing users to execute long or complex
commands with a simple keyword.
Aliases are created using the alias command, followed by the short name (alias) and the
corresponding command(s) enclosed in quotes. The general syntax is as follows:
alias alias_name='command(s)'
For example, to create an alias for the ls -al command, we can use the following
command:
alias ll='ls -al'
Now, whenever we type ll in the terminal, it will be expanded to ls -al.
Aliases can be stored in the shell configuration files such as .bashrc or .bash_aliases.
These files are executed each time a new terminal is opened, and the aliases become
available.
Aliases can be listed using the alias command with no arguments, and they can be
removed using the unalias command followed by the alias name:
unalias alias_name

THE END
In case you want to know about me -

You might also like