0% found this document useful (0 votes)
4 views14 pages

Shell Script

The document provides an overview of shell programming in Unix, detailing the function and types of shells, including Bourne and C shells. It explains shell scripts, their structure, and the use of commands, variables, and control structures within scripts. Additionally, it covers shell parameters, the export command, and basic programming concepts such as conditional statements and loops.

Uploaded by

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

Shell Script

The document provides an overview of shell programming in Unix, detailing the function and types of shells, including Bourne and C shells. It explains shell scripts, their structure, and the use of commands, variables, and control structures within scripts. Additionally, it covers shell parameters, the export command, and basic programming concepts such as conditional statements and loops.

Uploaded by

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

SHELL PROGRAMMING

A Shell provides you with an interface to the Unix system. It gathers input from you and
executes programs based on that input. When a program finishes executing, it displays that
program's output.
Shell is an environment in which we can run our commands, programs, and shell scripts.
There are different flavors of a shell, just as there are different flavors of operating systems.
Each flavor of shell has its own set of recognized commands and functions.

Shell Prompt
The prompt, $, which is called the command prompt, is issued by the shell. While the
prompt is displayed, you can type a command.
Shell reads your input after you press Enter. It determines the command you want executed
by looking at the first word of your input. A word is an unbroken set of characters. Spaces
and tabs separate words.
Following is a simple example of the date command, which displays the current date and
time −
$date
Thu Jun 25 08:30:19 MST 2009
You can customize your command prompt using the environment variable PS1 explained in
the Environment tutorial.

Shell Types
In Unix, there are two major types of shells −
 Bourne shell − If you are using a Bourne-type shell, the $ character is the default
prompt.
 C shell − If you are using a C-type shell, the % character is the default prompt.
The Bourne Shell has the following subcategories −

 Bourne shell (sh)


 Korn shell (ksh)
 Bourne Again shell (bash)
 POSIX shell (sh)
The different C-type shells follow −

 C shell (csh)
 TENEX/TOPS C shell (tcsh)
The original Unix shell was written in the mid-1970s by Stephen R. Bourne while he was at
the AT&T Bell Labs in New Jersey.
Bourne shell was the first shell to appear on Unix systems, thus it is referred to as "the
shell".
Bourne shell is usually installed as /bin/sh on most versions of Unix. For this reason, it is
the shell of choice for writing scripts that can be used on different versions of Unix.
In this chapter, we are going to cover most of the Shell concepts that are based on the Borne
Shell.

Shell Scripts
The basic concept of a shell script is a list of commands, which are listed in the order of
execution. A good shell script will have comments, preceded by # sign, describing the steps.
There are conditional tests, such as value A is greater than value B, loops allowing us to go
through massive amounts of data, files to read and store data, and variables to read and store
data, and the script may include functions.
We are going to write many scripts in the next sections. It would be a simple text file in
which we would put all our commands and several other required constructs that tell the
shell environment what to do and when to do it.
Shell scripts and functions are both interpreted. This means they are not compiled.

Example Script
Assume we create a test.sh script. Note all the scripts would have the .sh extension. Before
you add anything else to your script, you need to alert the system that a shell script is being
started. This is done using the shebang construct. For example −
#!/bin/sh
This tells the system that the commands that follow are to be executed by the Bourne
shell. It's called a shebang because the # symbol is called a hash, and the ! symbol is called
a bang.
To create a script containing these commands, you put the shebang line first and then add
the commands −
#!/bin/bash
pwd
ls

Shell Comments
You can put your comments in your script as follows −
#!/bin/bash
# Script follows here:
pwd
ls
Save the above content and make the script executable −
$chmod +x test.sh
The shell script is now ready to be executed −
$./test.sh
Upon execution, you will receive the following result −
/home/amrood
index.htm unix-basic_utilities.htm unix-directories.htm
test.sh unix-communication.htm unix-environment.htm
Note − To execute a program available in the current directory, use ./program_name

Shell Parameters

Parameters Function

$1-$9 Represent positional parameters for arguments one to nine

${10}-${n} Represent positional parameters for arguments after nine

$0 Represent name of the script

$∗ Represent all the arguments as a single string

$@ Same as $∗, but differ when enclosed in (")

$# Represent total number of arguments

$$ PID of the script

$? Represent last return code

Extended Shell Scripts


Shell scripts have several required constructs that tell the shell environment what to do and
when to do it. Of course, most scripts are more complex than the above one.
The shell is, after all, a real programming language, complete with variables, control
structures, and so forth. No matter how complicated a script gets, it is still just a list of
commands executed sequentially.
The following script uses the read command which takes the input from the keyboard and
assigns it as the value of the variable PERSON and finally prints it on STDOUT.
#!/bin/sh
# Author : Zara Ali
# Copyright (c) Tutorialspoint.com
# Script follows here:

echo "What is your name?"


read PERSON
echo "Hello, $PERSON"

Here is a sample run of the script −


$./test.sh
What is your name?
Zara Ali
Hello, Zara Ali
$

The export command is a built-in utility of Linux Bash shell. It is used to ensure the
environment variables and functions to be passed to child processes. It does not
affect the existing environment variable.

Environment variables are set when we open a new shell session. At any time, if we
change any variable value, the shell has no way to select that change. The export
command allows us to update the current session about the changes that have been
made to the exported variable. We do not need to wait to start a new shell session.

Syntax:
1. export [-f] [-n] [name[=value] ...] or export -p

Let's have a look at various examples of the export command:

Example1: The export command without any argument

The basic export command will display all the exported environment variables of your system. It is
executed as follows:

1. export

Consider the below snap of output:


Example2: Display all exported variable on current shell

To display all the exported environment variable of the current shell, execute the
command with -p option as follows:

1. export -p

Consider the below snap of output:


Example3: Using export with functions

To use a function with the export command, use the -f option. If we do not use this option, it
will be considered as a variable, not function.

Syntax:

1. export -f function_name

We are exporting a function 'name' as follows:

1. name() { echo "Javatpoint";}

To export the above function, execute the command as follows:

1. export -f name

Now, invoke the bash shell to execute the function:

1. bash
To call the function, enter the function name:

1. name

Consider the below output:

let's create another function 'hello,' execute the command as follows:

1. function hello
2. > {
3. > echo hello, welcome to javatpoint
4. > }

To export the above function, execute the command as follows:

1. export -f hello

Consider the below output:

Example4: Assign a value before exporting a function or variable:

The export command allows us to assign a value before exporting a function. Consider the
below command:

1. export name[=value]

For example, assign a value to a variable as follows:

1. a=5

now export it as:

1. export a

we can verify the assignment by using the printenv command as follows:

1. printenv a
Consider the below output:

Example5: Set vim as default editor:

The vim editor is the most widely used text editor for the Linux systems. We can set the vim
as default text editor by using the export command.

To set the vim as a default text editor, execute the following command:

1. export EDITOR=/usr/bin/vim
2. export | grep EDITOR

The above commands will not show any confirmation. Consider the below output:

.profile file:
. profile file in Linux comes under the System startup files(defines user environment after
reading the initialization files that you have set up when you log in to shell). File like
/etc/profile controls variables for profile of all users of the system whereas, . profile allows
you to customize your own environment.

1.read command in Linux system is used to read from a file descriptor. Basically, this
command read up the total number of bytes from the specified file descriptor into the
buffer. If the number or count is zero then this command may detect the errors. But on
success, it returns the number of bytes read. Zero indicates the end of the file. If some
errors found then it returns -1.
Syntax:
read

2.Variable Names

The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the
underscore character ( _).
By convention, Unix shell variables will have their names in UPPERCASE.
The following examples are valid variable names −
_ALI
TOKEN_A
VAR_1
VAR_2
The reason you cannot use other characters such as !, *, or - is that these characters have a
special meaning for the shell.

Defining Variables

Variables are defined as follows −


variable_name=variable_value
For example −
NAME="Zara Ali"
The above example defines the variable NAME and assigns the value "Zara Ali" to it.
Variables of this type are called scalar variables. A scalar variable can hold only one value
at a time.

Positional parameters
A positional parameter is a variable within a shell program; its value is set from an argument
specified on the command line that invokes the program. Positional parameters are numbered
and are referred to with a preceding ``$'': $1, $2, $3, and so on.
shell.prog pp1 pp2 pp3 pp4 pp5 pp6 pp7 pp8 pp9
then positional parameter $1 within the program is assigned the value pp1, positional
parameter $2 within the program is assigned the value pp2, and so on, at the time the shell
program is invoked.

$?
The exit status of the last command executed.

Exit Status

 Every Linux command executed by the shell script or user, has an exit status.
 The exit status is an integer number.
 The Linux man pages stats the exit statuses of each command.
 0 exit status means the command was successful without any errors.
 A non-zero (1-255 values) exit status means command was failure.
 You can use special shell variable called $? to get the exit status of the previously
executed command. To print $? variable use the echo command:

echo $?
date # run date command
echo $? # print exit status
foobar123 # not a valid command
echo $? # print exit status

The set command assigns a value to a variable (or multiple values to multiple variables).

set command
If a value has spaces in it, it should be contained in quotes. If a list of values is desired,
parentheses () should be used for the assignment, while indivisual access is done via square
brackets [].

set
set value = 7
set new_val = "some number, like seven"
echo $new_val
set list_of_vals = ( 3 1 4 one five )
echo $list_of_vals
echo $list_of_vals[3]
set path = ( $path ~/abin )

Note

A single set command can be used to set many variables, but such a use is not recommended.
exit command in Linux is used to exit the shell where it is currently running. It takes one
more parameter as [N] and exits the shell with a return of status N. If n is not provided, then
it simply returns the status of last command that is executed.
Syntax:
exit [n]
Options for exit command –
 exit: Exit Without Parameter

After pressing enter, the terminal will simply close.


 exit [n] : Exit With Parameter


 After pressing enter, the terminal window will close and return a status of 110.
Return status is important because sometimes they can be mapped to tell error,
warnings and notifications. For example generally, return status –
“0” means the program has executed successfully.
“1” means the program has min nor errors.
 exit n : Using “sudo su” we are going to the root directory and then exit the root
directory with a return status of 5. After returning it will show how to display the
return status code.


 echo $? command is used to see the last return status.
 exit –help : It displays help information.

Branching control:

Unix Conditional Statements The if-elif-fi

Unix provides a number of relational operators in addition to the logical operators mentioned
earlier. These can be used to compare numeric values.

 -lt less than


 -le less than or equal to
 -gt greater than
 -ge greater than or equal to
 -eq equal to
 -ne not equal to
Unix provides a number of ways for conditionally executing the other commands.
These are covered below:
#1) The if statements
Example:
if <control command>

then

<statements>
fi

#2) The if…else statements


Example:
if <control command>

then

<statements>

else

<statements>

fi

#3) The if…elif…else…fi statement


Example:
if <control command>

then

<statements>

elif

then

<statements>

else

<statements

Fi

Looping Statements in Shell Scripting: There are total 3 looping statements which can be
used in bash programming
1. while statement
2. for statement
3. until statement
To alter the flow of loop statements, two commands are used they are,
1. break
2. continue
Their descriptions and syntax are as follows:
 while statement
Here command is evaluated and based on the result loop will executed, if
command raise to false then loop will be terminated
Syntax
 while command
 do
 Statement to be executed
done
 for statement
The for loop operate on lists of items. It repeats a set of commands for every
item in a list.
Here var is the name of a variable and word1 to wordN are sequences of
characters separated by spaces (words). Each time the for loop executes, the
value of the variable var is set to the next word in the list of words, word1 to
wordN.
Syntax

for var in word1 word2 ...wordn


do
Statement to be executed
done
 until statement
The until loop is executed as many as times the condition/command evaluates to
false. The loop terminates when the condition/command becomes true.
Syntax

until command

do

 Statement to be executed until command is true
done

Example Programs
Example 1:
Implementing for loop with break statement

#Start of for loop

for a in 1 2 3 4 5 6 7 8 9 10

do

# if a is equal to 5 break the loop

if [ $a == 5 ]
then

break

fi

# Print the value

echo "Iteration no $a"

done

NOTE: Break statement and continue statement,


expr,
eval.
exec,
sleep command,
debugging script,
here document,
real arthimetic shell for notes

You might also like