Introduction
This tutorial is designed for beginners who wish to learn the basics of shell scripting/programming plus introduction to power tools such as awk, sed, etc. It is not help or manual for the shell; while reading this tutorial you can find manual quite useful (type man bash at $ prompt to see manual pages). Manual contains all necessary information you need, but it won't have that much examples, which makes idea more clear. For this reason, this tutorial contains examples rather than all the features of shell.
Audience for this tutorial
I assumes you have at least working knowledge of Linux i.e. basic commands like how to create, copy, remove files/directories etc or how to use editor like vi or mcedit and login to your system. But not expects any programming language experience. If you have access to Linux, this tutorial will provide you an easy-to-follow introduction to shell scripting.
What's different about this tutorial
Many other tutorial and books on Linux shell scripting are either too basic, or skips important intermediate steps. But this tutorial, maintained the balance between these two. It covers the many real life modern example of shell scripting which are almost missed by many other tutorials/documents/books. I have used a hands-on approach in this tutorial. The idea is very clear "do it yourself or learn by doing" i.e. trying things yourself is the best way to learn, so examples are presented as complete working shell scripts, which can be typed in and executed.
What Linux is?
- Free : Linux is free. First ,It's available free of cost (You don't have to pay to use this OS, other OSes like MS-Windows or Commercial version of Unix may cost you money)Second free means freedom to use Linux, i.e. when you get Linux you will also get source code of Linux, so you can modify OS (Yes OS! Linux OS!!) according to your taste.It also offers many Free Software applications, programming languages, and development tools etc. Most of the Program/Software/OS are under GNU General Public License (GPL).
- Unix Like: Unix is almost 35 year old Os.In 1964 OS called MULTICS (Multiplexed Information and Computing System) was developed by Bell Labs, MIT & General Electric. But this OS was not the successful one.
Then Ken Thompson (System programmer of Bell Labs) thinks he could do better (In 1991, Linus Torvalds felt he could do better than Minix - History repeats itself.). So Ken Thompson wrote OS on PDP - 7 Computer, assembler and few utilities, this is know as Unix (1969). But this version of Unix is not portable. Then Unix was rewrote in C. Because Unix written in 'C', it is portable. It means Unix can run on verity of Hardware platform (1970-71).At the same time Unix was started to distribute to Universities. There students and professor started more experiments on Unix. Because of this Unix gain more popularity, also several new features are added to Unix. Then US govt. & military uses Unix for there inter-network (now it is know as INTERNET).So Unix is Multi-user, Multitasking, Internet-aware Network OS. Linux almost had same Unix Like feature for e.g. - Like Unix, Linux is also written is C.
- Like Unix, Linux is also the Multi-user/Multitasking/32 or 64 bit Network OS.
- Like Unix, Linux is rich in Development/Programming environment.
- Like Unix, Linux runs on different hardware platform; for e.g.
- Intel x86 processor (Celeron/PII/PIII/PIV/Old-Pentiums/80386/80486)
- Macintosh PC's
- Cyrix processor
- AMD processor
- Sun Microsystems Sparc processor
- Alpha Processor (Compaq)
- Open Source: Linux is developed under the GNU Public License. This is sometimes referred to as a "copyleft", to distinguish it from a copyright.Under GPL the source code is available to anyone who wants it, and can be freely modified, developed, and so forth. There are only a few restrictions on the use of the code. If you make changes to the programs , you have to make those changes available to everyone. This basically means you can't take the Linux source code, make a few changes, and then sell your modified version without making the source code available.
- Network operating system:
Common vi editor command list
For this Purpose | Use this vi Command Syntax |
To insert new text | esc + i ( You have to press 'escape' key then 'i') |
To save file | esc + : + w (Press 'escape' key then 'colon' and finally 'w') |
To save file with file name (save as) | esc + : + w "filename" |
To quit the vi editor | esc + : + q |
To quit without saving | esc + : + q! |
To save and quit vi editor | esc + : + wq |
To search for specified word in forward direction | esc + /word (Press 'escape' key, type /word-to-find, for e.g. to find word 'shri', type as /shri) |
To continue with search | n |
To search for specified word in backward direction | esc + ?word (Press 'escape' key, type word-to-find) |
To copy the line where cursor is located | esc + yy |
To paste the text just deleted or copied at the cursor | esc + p |
To delete entire line where cursor is located | esc + dd |
To delete word from cursor position | esc + dw |
To Find all occurrence of given word and Replace then globally without confirmation | esc + :$s/word-to-find/word-to-replace/gFor. e.g. :$s/mumbai/pune/g Here word "mumbai" is replace with "pune" |
To Find all occurrence of given word and Replace then globally with confirmation | esc + :$s/word-to-find/word-to-replace/cg |
To run shell command like ls, cp or date etc within vi | esc + :!shell-command For e.g. :!pwd |
How Shell Locates the file
To run script, you need to have in the same directory where you created your script, if you are in different directory your script will not run (because of path settings), For e.g.. Your home directory is ( use $ pwd to see current working directory) /home/vivek. Then you created one script called 'first', after creation of this script you moved to some other directory lets say /home/vivek/Letters/Personal, Now if you try to execute your script it will not run, since script 'first' is in /home/vivek directory, to overcome this problem there are two ways first, specify complete path of your script when ever you want to run it from other directories like giving following command
$ /bin/sh /home/vivek/first
$ /bin/sh /home/vivek/first
Now every time you have to give all this detailed as you work in other directory, this take time and you have to remember complete path.
There is another way, if you notice that all of our programs (in form of executable files) are marked as executable and can be directly executed from prompt from any directory. (To see executables of our normal program give command $ ls -l /bin ) By typing commands like
$ bc
$ cc myprg.c
$ caletc, How its possible? All our executables files are installed in directory called /bin and /bin directory is set in your PATH setting, Now when you type name of any command at $ prompt, what shell do is it first look that command in its internal part (called as internal command, which is part of Shell itself, and always available to execute), if found as internal command shell will execute it, If not found It will look for current directory, if found shell will execute command from current directory, if not found, then Shell will Look PATH setting, and try to find our requested commands executable file in all of the directories mentioned in PATH settings, if found it will execute it, otherwise it will give message "bash: xxxx :command not found", Still there is one question remain can I run my shell script same as these executables?, Yes you can, for this purpose create bin directory in your home directory and then copy your tested version of shell script to this bin directory. After this you can run you script as executable file without using command like
$ /bin/sh /home/vivek/first
Command to create you own bin directory.
$ bc
$ cc myprg.c
$ caletc, How its possible? All our executables files are installed in directory called /bin and /bin directory is set in your PATH setting, Now when you type name of any command at $ prompt, what shell do is it first look that command in its internal part (called as internal command, which is part of Shell itself, and always available to execute), if found as internal command shell will execute it, If not found It will look for current directory, if found shell will execute command from current directory, if not found, then Shell will Look PATH setting, and try to find our requested commands executable file in all of the directories mentioned in PATH settings, if found it will execute it, otherwise it will give message "bash: xxxx :command not found", Still there is one question remain can I run my shell script same as these executables?, Yes you can, for this purpose create bin directory in your home directory and then copy your tested version of shell script to this bin directory. After this you can run you script as executable file without using command like
$ /bin/sh /home/vivek/first
Command to create you own bin directory.
$ cd $ mkdir bin $ cp first ~/bin $ first |
Each of above commands can be explained as follows:
Each of above command | Explanation |
$ cd | Go to your home directory |
$ mkdir bin | Now created bin directory, to install your own shell script, so that script can be run as independent program or can be accessed from any directory |
$ cp first ~/bin | copy your script 'first' to your bin directory |
$ first | Test whether script is running or not (It will run) |
Answer to Variable sections exercise
Q.1.How to Define variable x with value 10 and print it on screen.
$ x=10
$ echo $x
Q.2.How to Define variable xn with value Rani and print it on screen
For Ans. Click here
$ xn=Rani
$ echo $xn
Q.3.How to print sum of two numbers, let's say 6 and 3
$ echo 6 + 3This will print 6 + 3, not the sum 9, To do sum or math operations in shell use expr, syntax is as follows
Syntax: expr op1 operator op2Where, op1 and op2 are any Integer Number (Number without decimal point) and operator can be
+ Addition
- Subtraction
/ Division
% Modular, to find remainder For e.g. 20 / 3 = 6 , to find remainder 20 % 3 = 2, (Remember its integer calculation)
\* Multiplication
$ expr 6 + 3
Now It will print sum as 9 , But
$ expr 6+3
will not work because space is required between number and operator (See Shell Arithmetic)
Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y)
For Ans. Click here
$x=20
$ y=5
$ expr x / y
Q.5.Modify above and store division of x and y to variable called z
For Ans. Click here
$ x=20
$ y=5
$ z=`expr x / y`
$ echo $z
$ x=10
$ echo $x
Q.2.How to Define variable xn with value Rani and print it on screen
For Ans. Click here
$ xn=Rani
$ echo $xn
Q.3.How to print sum of two numbers, let's say 6 and 3
$ echo 6 + 3This will print 6 + 3, not the sum 9, To do sum or math operations in shell use expr, syntax is as follows
Syntax: expr op1 operator op2Where, op1 and op2 are any Integer Number (Number without decimal point) and operator can be
+ Addition
- Subtraction
/ Division
% Modular, to find remainder For e.g. 20 / 3 = 6 , to find remainder 20 % 3 = 2, (Remember its integer calculation)
\* Multiplication
$ expr 6 + 3
Now It will print sum as 9 , But
$ expr 6+3
will not work because space is required between number and operator (See Shell Arithmetic)
Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y)
For Ans. Click here
$x=20
$ y=5
$ expr x / y
Q.5.Modify above and store division of x and y to variable called z
For Ans. Click here
$ x=20
$ y=5
$ z=`expr x / y`
$ echo $z
Q.6.Point out error if any in following script
$ vi variscript # # # Script to test MY knolwdge about variables! # myname=Vivek myos = TroubleOS -----> ERROR 1myno=5 echo "My name is $myname" echo "My os is $myos" echo "My number is myno, can you see this number" ----> ERROR 2 |
Read the following for ERROR 1 and ERROR 2 :
To print or access UDV use following syntax
Syntax:
$variablename
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
$ vech=Bus
$ n=10
To print contains of variable 'vech' type
$ echo $vech
It will print 'Bus',To print contains of variable 'n' type command as follows
$ echo $n
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.
Following script should work now, after bug fix!
Future Point: What is difference between following two command?
$cp /mnt/cdrom/lsoft/samba*.rmp `pwd`
A N D
$cp /mnt/cdrom/lsoft/samba*.rmp .
Try to note down output of following Parameter substitution.
$ vi variscript # # # Script to test MY knolwdge about variables! # myname=Vivek myos=TroubleOSmyno=5 echo "My name is $myname" echo "My os is $myos" echo "My number is $myno, can you see this number" |
Parameter substitution.
Now consider following command
$($ echo 'expr 6 + 3')
$($ echo 'expr 6 + 3')
The command ($ echo 'expr 6 + 3') is know as Parameter substitution. When a command is enclosed in backquotes, the command get executed and we will get output. Mostly this is used in conjunction with other commands. For e.g.
$pwd $cp /mnt/cdrom/lsoft/samba*.rmp `pwd` |
Now suppose we are working in directory called "/home/vivek/soft/artical/linux/lsst" and I want to copy some samba files from "/mnt/cdrom/lsoft" to my current working directory, then my command will be something like
$cp /mnt/cdrom/lsoft/samba*.rmp /home/vivek/soft/artical/linux/lsst
Instead of giving above command I can give command as follows
$cp /mnt/cdrom/lsoft/samba*.rmp `pwd`
Here file is copied to your working directory. See the last Parameter substitution of `pwd` command, expand it self to /home/vivek/soft/artical/linux/lsst. This will save my time.
$cp /mnt/cdrom/lsoft/samba*.rmp `pwd`
$cp /mnt/cdrom/lsoft/samba*.rmp `pwd`
Future Point: What is difference between following two command?
$cp /mnt/cdrom/lsoft/samba*.rmp `pwd`
A N D
$cp /mnt/cdrom/lsoft/samba*.rmp .
Try to note down output of following Parameter substitution.
$echo "Today date is `date`" $cal > menuchoice.temp.$$ $dialog --backtitle "Linux Shell Tutorial" --title "Calender" --infobox "`cat menuchoice.temp.$$`" 9 25 ; read |