0% found this document useful (0 votes)
11 views6 pages

Shell Script Writing Guide

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

Shell Script Writing Guide

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

How to write shell script

Following steps are required to write shell script:


(1) Use any editor like vi or mcedit to write shell script.
(2) After writing shell script set execute permission for your script as follows
syntax:
chmod permission your-script-name
Examples:
Note: This will set read write execute(7) permission for owner, for group and other
permission is read and execute only(5).
(3) Execute your script as
syntax:
bash your-script-name
sh your-script-name
./your-script-name
Examples:
NOTE In the last syntax ./ means current directory, But only . (dot) means execute
given command file in current shell
without starting the new copy of shell, The syntax for . (dot) command is as
follows
Syntax:
. command-name
Example:
Now you are ready to write first shell script that will print "Knowledge is Power"
on screen. See the common vi command
list , if you are new to vi.
After saving the above script, you can run the script as follows:
LSST v1.05r3 > Chapter 2 > How to write shell script
[Link] (1 of 2) [7/29/2002 6:51:39 PM]
This will not run script since we have not set execute permission for our script
first; to do this type command
First screen will be clear, then Knowledge is Power is printed on screen.
Script Command(s) Meaning
$ vi first Start vi editor
#
# My first shell script
#
# followed by any text is considered as
comment. Comment gives more
information about script, logical
explanation about shell script.
Syntax:
# comment-text
clear clear the screen
echo "Knowledge is Power"
To print message or value of variables on
screen, we use echo command, general
form of echo command is as follows
syntax:
echo "Message"
How Shell Locates the file (My own bin directory to execute script)
Tip: For shell script file try to give file extension such as .sh, which can be
easily identified by you as shell script.
Exercise:
1)Write following shell script, save it, execute it and note down it's output.
Future Point: At the end why statement exit 0 is used? See exit status for more
information.
Prev Home Next
Getting started with Shell Programming Up Variables in Shell
[Advertisement]
[Get Cyberciti Domain for Just Rs.445 with 2 Free e-mail]
LSST v1.05r3 > Chapter 2 > How to write shell script
[Link] (2 of 2) [7/29/2002 6:51:39 PM]
Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev Chapter 2: Getting started with Shell Programming Next
Variables in Shell
To process our data/information, data must be kept in computers RAM memory. RAM
memory is
divided into small locations, and each location had unique number called memory
location/address,
which is used to hold our data. Programmer can give a unique name to this memory
location/address
called memory variable or variable (Its a named storage location that may take
different values, but only
one at a time).
In Linux (Shell), there are two types of variable:
(1) System variables - Created and maintained by Linux itself. This type of
variable defined in
CAPITAL LETTERS.
(2) User defined variables (UDV) - Created and maintained by user. This type of
variable defined in
lower letters.
You can see system variables by giving command like $ set, some of the important
System variables are:
System Variable Meaning
BASH=/bin/bash Our shell name
BASH_VERSION=1.14.7(1) Our shell version name
COLUMNS=80 No. of columns for our screen
HOME=/home/vivek Our home directory
LINES=25 No. of columns for our screen
LOGNAME=students students Our logging name
OSTYPE=Linux Our Os type
PATH=/usr/bin:/sbin:/bin:/usr/sbin Our path settings
PS1=[\u@\h \W]\$ Our prompt settings
PWD=/home/students/Common Our current working directory
SHELL=/bin/bash Our shell name
USERNAME=vivek User name who is currently login to this PC
NOTE that Some of the above settings can be different in your PC/Linux environment.
You can print any
of the above variables contains as follows:
Exercise:
1) If you want to print your home directory location then you give command:
a)
OR
LSST v1.05r3 > Chapter 2 > Variables in Shell
[Link] (1 of 2) [7/29/2002 6:51:42 PM]
(b)
Which of the above command is correct & why? Click here for answer.
Caution: Do not modify System variable this can some time create problems.
Prev Home Next
How to write shell script Up How to define User defined variables
(UDV)
LSST v1.05r3 > Chapter 2 > Variables in Shell
[Link] (2 of 2) [7/29/2002 6:51:42 PM]
Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev Chapter 2: Getting started with Shell Programming Next
How to define User defined variables
(UDV)
To define UDV use following syntax
Syntax:
variable name=value
'value' is assigned to given 'variable name' and Value must be on right side =
sign.
Example:
# this is ok
# Error, NOT Ok, Value must be on right side of = sign.
To define variable called 'vech' having value Bus
To define variable called n having value 10
Prev Home Next
Variables in shell Up Rules for Naming variable name (Both
UDV and System Variable)
LSST v1.05r3 > Chapter 2 > How to define User defined variables (UDV)
[Link] [7/29/2002 6:51:44 PM]
Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev Chapter 2: Getting started with Shell Programming Next
Rules for Naming variable name (Both
UDV and System Variable)
(1) Variable name must begin with Alphanumeric character or underscore character
(_), followed by one
or more Alphanumeric character. For e.g. Valid shell variable are as follows
HOME
SYSTEM_VERSION
vech
no
(2) Don't put spaces on either side of the equal sign when assigning value to
variable. For e.g. In
following variable declaration there will be no error
But there will be problem for any of the following variable declaration:
(3) Variables are case-sensitive, just like filename in Linux. For e.g.
Above all are different variable name, so to print value 20 we have to use $ echo
$NO and not any of the
following
# will print 10 but not 20
# will print 11 but not 20
# will print 2 but not 20
(4) You can define NULL variable as follows (NULL variable is variable which has no
value at the time
of definition) For e.g.
$ vech=
$ vech=""
Try to print it's value by issuing following command
Nothing will be shown because variable has no value i.e. NULL variable.
(5) Do not use ?,* etc, to name your variable names.
Prev Home Next
LSST v1.05r3 > Chapter 2 > Rules for Naming variable name (Both UDV and System
Variable)
[Link] (1 of 2) [7/29/2002 6:51:46 PM]
How to define User defined variables
(UDV)
Up How to print or access value of UDV
(User defined variables)
LSST v1.05r3 > Chapter 2 > Rules for Naming variable name (Both UDV and System
Variable)
[Link] (2 of 2) [7/29/2002 6:51:46 PM]
Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev Chapter 2: Getting started with Shell Programming Next
How to print or access value of UDV
(User defined variables)
To print or access UDV use following syntax
Syntax:
$variablename
Define variable vech and n as follows:
To print contains of variable 'vech' type
It will print 'Bus',To print contains of variable 'n' type command as follows
Caution: Do not try $ echo vech, as it will print vech instead its value 'Bus' and
$ echo n, as it will print
n instead its value '10', You must use $ followed by variable name.
Exercise
[Link] to Define variable x with value 10 and print it on screen.
[Link] to Define variable xn with value Rani and print it on screen
[Link] to print sum of two numbers, let's say 6 and 3?
[Link] to define two variable x=20, y=5 and then to print division of x and y
(i.e. x/y)
[Link] above and store division of x and y to variable called z
[Link] out error if any in following script
For Answers Click here
Prev Home Next
LSST v1.05r3 > Chapter 2 > How to print or access value of UDV (User defined
variables)
[Link] (1 of 2) [7/29/2002 6:51:48 PM]
Rules for Naming variable name (Both
UDV and System Variable)
Up echo Command
LSST v1.05r3 > Chapter 2 > How to print or access value of UDV (User defined
variables)
[Link] (2 of 2) [7/29/2002 6:51:48 PM]
Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev Chapter 2: Getting started with Shell Programming Next
echo Command
Use echo command to display text or value of variable.
echo [options] [string, variables...]
Displays text or variables value on screen.
Options
-n Do not output the trailing new line.
-e Enable interpretation of the following backslash escaped characters in the
strings:
\a alert (bell)
\b backspace
\c suppress trailing new line
\n new line
\r carriage return
\t horizontal tab
\\ backslash
For e.g. $ echo -e "An apple a day keeps away \a\t\tdoctor\n"
How to display colorful text on screen with bold or blink effects, how to print
text on any row, column
on screen, click here for more!
Prev Home Next
How to print or access value of UDV (User
defined variables)
Up Shell Arithmetic
LSST v1.05r3 > Chapter 2 > echo Command
[Link] [7/29/2002 6:51:50 PM]
Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev Chapter 2: Getting started with Shell Programming Next
Shell Arithmetic
Use to perform arithmetic operations.
Syntax:
expr op1 math-operator op2
Examples:
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.
For the last statement not the following points
(1) First, before expr keyword we used ` (back quote) sign not the (single quote
i.e. ') sign. Back quote is
generally found on the key under tilde (~) on PC keyboard OR to the above of TAB
key.
(2) Second, expr is also end with ` i.e. back quote.
(3) Here expr 6 + 3 is evaluated to 9, then echo command prints 9 as sum
(4) Here if you use double quote or single quote, it will NOT work
For e.g.
$ echo "expr 6 + 3" # It will print expr 6 + 3
$ echo 'expr 6 + 3' # It will print expr 6 + 3
See Parameter substitution - To save your time.
Prev Home Next
echo Command Up More about Quotes
LSST v1.05r3 > Chapter 2 > Shell Arithmetic
[Link] [7/29/2002 6:51:52 PM]
Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev Chapter 2: Getting started with Shell Programming Next
More about Quotes
There are three types of quotes
Quotes Name Meaning
" Double Quotes
"Double Quotes" - Anything enclose in double quotes removed meaning of that
characters (except \ and $).
' Single quotes 'Single quotes' - Enclosed in single quotes remains unchanged.
` Back quote
`Back quote` - To execute command
Example:
$ echo "Today is date"
Can't print message with today's date.
$ echo "Today is `date`".
It will print today's date as, Today is Tue Jan ....,Can you see that the `date`
statement uses back quote?
Prev Home Next
Shell Arithmetic Up Exit Status
LSST v1.05r3 > Chapter 2 > More about Quotes
[Link] [7/29/2002 6:51:53 PM]
Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev Chapter 2: Getting started with Shell Programming Next
Exit Status
By default in Linux if particular command/shell script is executed, it return two
type of values which is
used to see whether command or shell script executed is successful or not.
(1) If return value is zero (0), command is successful.
(2) If return value is nonzero, command is not successful or some sort of error
executing command/shell
script.
This value is know as Exit Status.
But how to find out exit status of command or shell script?
Simple, to determine this exit Status you can use $? special variable of shell.
For e.g. (This example assumes that unknow1file doest not exist on your hard drive)
$ rm unknow1file
It will show error as follows
rm: cannot remove `unkowm1file': No such file or directory
and after that if you give command
$ echo $?
it will print nonzero value to indicate error. Now give command
$ ls
$ echo $?
It will print 0 to indicate command is successful.
Exercise
Try the following commands and not down the exit status:
$? useful variable, want to know more such Linux variables click here to explore
them!
LSST v1.05r3 > Chapter 2 > Exit Status
[Link] (1 of 2) [7/29/2002 6:51:55 PM]
Prev Home Next
More about Quotes Up The read Statement
LSST v1.05r3 > Chapter 2 > Exit Status
[Link] (2 of 2) [7/29/2002 6:51:55 PM]
Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev Chapter 2: Getting started with Shell Programming Next
The read Statement
Use to get input (data from user) from keyboard and store (data) to variable.
Syntax:
read variable1, variable2,...variableN
Following script first ask user, name and then waits to enter name from the user
via keyboard. Then user
enters name from keyboard (after giving name you have to press ENTER key) and
entered name through
keyboard is stored (assigne

Common questions

Powered by AI

To write a shell script, first use an editor like vi or mcedit to create your script file. After writing the script, set execute permissions using chmod, e.g., chmod 755 your-script-name. Finally, execute the script using one of these commands: bash your-script-name, sh your-script-name, or ./your-script-name. The ./ syntax indicates the current directory, while . (dot) executes the command file in the current shell without starting a new shell instance .

The read command in shell scripting is used to capture user input from the keyboard and store it in variables. When executed, the script pauses to allow the user to input data, which is then assigned to the specified variable(s). Example usage: read name, where 'name' stores the input .

Variable names in shell scripting must begin with an alphanumeric character or an underscore (_), cannot contain spaces around the equal sign when assigning values, and are case-sensitive. Avoid using special characters like *, ?, etc. Following these rules ensures that variables function correctly without errors across different environments .

The echo command in shell scripting is used to display text or the value of variables on the screen. It can include options like -n to omit the trailing newline or -e to enable interpretation of escaped characters like for a new line, for a tab, or \ for a backslash. For instance, using echo -e "An apple a day keeps the doctor away \n" outputs the text with a new line at the end .

System variables are created and maintained by Linux itself and are typically defined in capital letters, while user-defined variables are created and maintained by the user and are defined in lowercase . System variables set essential environment settings, like PATH, HOME, and USER, whereas user variables can be defined by the user for custom operations, following specific naming conventions .

Arithmetic operations in shell scripts use the expr command with operators like +, -, *, and / for addition, subtraction, multiplication, and division. It's important to use back quotes around expressions for evaluation, e.g., `expr 6 + 3`. Note that the multiplication operator (*) must be escaped as \* to differentiate it from the wildcard. Avoid quotes around expressions within expr, as it prevents evaluation .

Variables in shell scripts are defined using the syntax variable_name=value, with no spaces on either side of the equal sign. To access a variable's content, prepend its name with a $, such as $variable. It's crucial to follow naming rules, such as beginning with an alphanumeric character or _, avoiding spaces around the equal sign, and respecting case sensitivity. Additionally, avoid special characters like ? or * in variable names .

Quotes in shell scripting alter the interpretation of strings and variables. Double quotes ("") allow variable expansion and interpretation of special characters (except \ and $), whereas single quotes ('') preserve the literal value, ignoring any special meaning of characters. Back quotes (`...`) execute the enclosed command and substitute its output. For instance, using `date` within echo `Today is \`date\`` executes the date command and returns the current date .

The exit status in Linux shell scripting signifies whether a command or script executed successfully, with a return value of 0 for success and a nonzero value indicating an error. To determine the exit status of a command, the special variable $? is used after the command execution. For example, if a command like rm is executed on a nonexistent file, $? returns a nonzero value indicating failure .

Path settings direct the shell on where to locate executable files. They influence script execution by specifying directories in the PATH variable. Optimizing involves ensuring the PATH includes directories with frequently used scripts and executables, allowing scripts to be run without specifying full paths. Customizing PATH can enhance performance by avoiding script execution delays due to incorrect paths .

You might also like