Shell Script
Shell Script
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 −
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
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
The basic export command will display all the exported environment variables of your system. It is
executed as follows:
1. export
To display all the exported environment variable of the current shell, execute the
command with -p option as follows:
1. export -p
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
1. export -f name
1. bash
To call the function, enter the function name:
1. name
1. function hello
2. > {
3. > echo hello, welcome to javatpoint
4. > }
1. export -f hello
The export command allows us to assign a value before exporting a function. Consider the
below command:
1. export name[=value]
1. a=5
1. export a
1. printenv a
Consider the below output:
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
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 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 provides a number of relational operators in addition to the logical operators mentioned
earlier. These can be used to compare numeric values.
then
<statements>
fi
then
<statements>
else
<statements>
fi
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 a in 1 2 3 4 5 6 7 8 9 10
do
if [ $a == 5 ]
then
break
fi
done