PDF generated using the open source mwlib toolkit. Linux Shell Scripting Tutorial - A Beginner's handbook:About. 1. Chapter 1: Quick. The Advanced Bash Scripting Guide (PDF) shell scripting shell scripting tutorial Linux Shell Scripting Tutorial vr3 A Beginner's handbook. Advanced. Linux Shell Scripting Tutorial vr3 - A Beginner's handbook http://www. homeranking.info (2 of 5) [7/29/ PM] getopts command.
|Language:||English, Spanish, Hindi|
|Genre:||Politics & Laws|
|ePub File Size:||20.76 MB|
|PDF File Size:||18.10 MB|
|Distribution:||Free* [*Regsitration Required]|
Linux® Command Line and Shell Scripting Bible, Third Edition. Published by. John Wiley & Sons Shell Scripting EXPERT RECIPES FOR LINUX, BASH, AND. homeranking.info (1 of 5) [7/29/ PM]. Linux Shell Scripting Tutorial vr3 - A Beginner's handbook. Shell Arithmetic. Last time we saw ▻ Directories: pwd, cd, rm –r, mkdir, du -sh. ▻ Rights: ls –l, chown and chmod. ▻ Jobs: top, ps x, kill ▻ The manual pages: man.
Up How to Install Linux http: Version 2 Linux Shell Scripting Tutorial v1. As you know in Linux everything is considered as a file. The g option at the end instruct s command to perform replacement on all occurrences of the target pattern within a address line. This is good idea if our program takes some argument. I have used a hands-on approach in this tutorial. Created and maintained by user.
For more information on Linus Torvalds. In Linux is Open Source From the start of the day. Linus Torvalds studying Unix at the University. Prev Home Next What Linux is? Up How to get Linux?
Note that you can also obtained your Linux distribution with Linux books which you purchase from local book store. Linux distributions. Following are important Linux distributions. Linux available for download over the net. Various Linux distributions available.
India please visit our web site to obtained the Red Hat Linux or any other official Linux distribution. Prev Home Next Who developed the Linux? Up How to Install Linux http: Prev Home Next How to get Linux?
Up Where I can use Linux? Connect the expensive device like printer and share it. So Linux can be used as: But it is best suited for Server.
Server Os must be: You can put your web sever that run your web site or transmit the information on the internet. So you can use Linux for: It performance following task: Up What is Linux Shell? Kernel decides who will use this resource. It's Memory resident portion of Linux. For e. Facility to store data. It runs your programs or set up to execute binary files. Kernel is heart of Linux Os. Resources means facilities available in Linux. It manages resource of Linux Os.
So in Os there is special program called Shell. Computer understand the language of 0's and 1's called binary language. Shell is a user program or it's a environment provided for user interaction. Shell is not part of system kernel. This prompt is depend upon your shell and Environment that you set or by your System Administrator.
To find all available shells in your system type following command: Any of the above shell reads command from user via Keyboard or Mouse and tells Linux Os what users want. COM which is also used for same purpose. It's Freeware shell. Several shell available with Linux including: Shell is an command language interpreter that executes commands read from the standard input device keyboard or from a file.
In early days of computing. Shell accepts your instruction or commands in English mostly and if its a valid command. Up How to use Shell http: Up What is Shell Script?
See common Linux Command for syntax and example. Linux Shell basics Next How to use Shell To use shell You start to use your shell as soon as you log into your system you have to simply type commands. But if you use command one by one sequence of 'n' number of commands. This is know as shell script. It means shell accept command from you via keyboard and execute them. Normally shells are interactive. Shell script defined as: Up More on Shell. Available with almost all Linux Distributions.
All the scripts are also tested on Red Hat Linux version 7. By default bash is default shell for Red Hat Linux Distribution. Up Getting started with Shell Programming http: In this tutorial we are using bash shell. Up How to write shell script http: We will be getting started with writing small shell script. Getting started with Shell Programming Next Getting started with Shell Programming In this part of tutorial you are introduced to shell programming.
Getting started with Shell Programming Next How to write shell script Following steps are required to write shell script: But only. See the common vi command list. This will set read write execute 7 permission for owner. The syntax for. At the end why statement exit 0 is used? See exit status for more information.
Comment gives more information about script. For shell script file try to give file extension such as. Created and maintained by Linux itself. RAM memory is divided into small locations.
Created and maintained by user. You can print any of the above variables contains as follows: In Linux Shell. This type of variable defined in lower letters. Do not modify System variable this can some time create problems.
Click here for answer. NOT Ok. NULL variable. Prev Home Next http: How to print sum of two numbers. Exercise Q. Modify above and store division of x and y to variable called z Q. How to Define variable xn with value Rani and print it on screen Q. How to Define variable x with value 10 and print it on screen. Options -n Do not output the trailing new line.
Getting started with Shell Programming Next echo Command Use echo command to display text or value of variable.
LSST v For the last statement not the following points 1 First. To save your time. Remainder read as 20 mod 3 and remainder is 2. Enclosed in single quotes remains unchanged.
To execute command Example: It will print today's date as Today is Tue Jan. But how to find out exit status of command or shell script? It will print 0 to indicate command is successful. This value is know as Exit Status. Exercise Try the following commands and not down the exit status: Lets be friend! Getting started with Shell Programming Next The read Statement Use to get input data from user from keyboard and store data to variable.
Then user enters name from keyboard after giving name you have to press ENTER key and entered name through keyboard is stored assigned to variable fname. Matches any single character.. No such file or directory. Now it creates one more question What are commands? The first word on command line is. Everything else on command line is taken as arguments to this command.
So we are doing one way communication with our command by specifying filename. Also you can pass command line arguments to your script to make it more users friendly. So what we do is we write command as follows: But how we access command line argument in our script. This way you tail rm command which file you would like to remove. For shell script. Let's take rm command. And actual argument i. Also note that you can't assigne the new value to command line arguments i.
Output redirection http: So following all statements in shell script are invalid: I am not going to show you all of the above command s for rest of Tutorial. After this. Output redirection Mostly all commands give output on screen or take input from keyboard. Note that if file exist. And if file is not exist. Note that if file already exist.
Try one more example to clear your idea: Future Point: Try following command and find out most important point: It take input from sname file. Now issue following command. Pipe Defined as: Getting started with Shell Programming Next Pipes A pipe is a way to connect the output of one program to the input of another program without any temporary file.
Pipes are used to run more than two commands Multiple commands from same command line. Getting started with Shell Programming Next Filter If a Linux command accepts its input from the standard input and produces its output on standard output is know as a filter.
A filter performs some kind of process on the input and gives output. Suppose you have file called 'hotel. And from 'hotel. PID starts from 0 to It is a process. Process defined as: In Linux when you start process. To find how many files do you have on your system you may give command like: It means you can run more than two process simultaneously if you wish. NOTE that you can only kill process which are created by yourself. Regarding this situation. You are working on your Linux workstation might be learning LSST or some other work like sending mails.
But some process can not be killed. Note that to exit from top updates. Turn off Speakers 2. And how you will verify this?
Is it True or False?. None of the above Click here for answers. Kill the MP3 playing process 4. What computer know is 0 zero and 1 that is Yes or No. Your answer will be no which is indicated by bc by showing 0 Zero. If I ask same question to you. Is 5 is greater then 2. Linux calculator program. Is 5 is less than 2?. Remember in bc. This chapter introduces to the bash's structured language constructs such as: Well real life decision are quite complicated to all of us and computers even don't have that much power to understand our real life decisions.
To make this idea clear. Shells bash structured Language Constructs Next if condition if condition which is used for decision making in shell script. Write shell script as http: If given condition is true then command1 is executed. The cat command return zero 0 i.
Expreession is defined as: Then shell compare it as follows: B If bar file not present on your disk and you give command. For Answer click here.
Exercise Write shell script as follows: A foo file exists on your disk and you give command. Detailed explanation if cat command finds foo file and if its successfully shown on screen.
Character strings http: Following script determine whether given argument number is positive. If it is true 0 then test will return 0 and output will printed as 5 number is positive but for argument there is no output because our condition is not true 0 no is not greater than 0 hence echo statement is skipped.
Shells bash structured Language Constructs Next test command or [ expr ] test command or [ expr ] is used to see if an expression is true. File types 3. And for last statement we have not supplied any argument hence error.
Integer Number without decimal point 2. Write Script as follows: Shells bash structured Language Constructs Next if. Linux Red Hat " echo -n "Select your os choice [1 or 2]? This is called the nesting of ifs.
The echo command i. Nested if-else-fi You can write the entire if-else construct within either the body of the if statement of the body of an else statement.
Unix Sun Os " echo " If it is false as well the final else statement is executed. Unix Sun Os 2. Linux Red Hat Select you os choice [1 or 2]?
Note that Second if-else constuct is nested in the first else statement.. If the condition in the first if statement is false the the condition in the second if statement is checked You can use the nested ifs as follows also: Prev Home Next if. A group of instruction that is executed repeatedly is called a loop. Prev Home Next Multilevel if-then-else Up for loop http: To make you idea more clear try following script: This is usually know as iteration This process will continue until all the items in the list were not finished.
The shell execute echo statement for each assignment of i. Number missing form command line argument" echo "Syntax: Hence script is showing Error message. This is usually used to initialize variables for the loop.. Syntax and usage of our script. This is good idea if our program takes some argument. AFTER each iteration of the loop. Note that to terminate our script we used 'exit 1' command which takes 1 as argument 1 indicates error and therefore script is terminated Even you can use following syntax: Second expression is condition i.
This is usually use to increment a loop counter. Number missing form command line argument Syntax: To understand the nesting of for loop see the following shell script.
You can nest the for loop. Following script is quite intresting. The inner for loop terminates when the value of j exceeds 5. This statements are responsible to fi print entier chess board on screen with alternet colours. Above shell script cab be explained as follows: The inner for loop terminates when the value of j exceeds 9. Exercise Try to understand the shell scripts for loops shown in exercise chapter. Above for loop program shown in last section of for loop can be written using while loop as: Shells bash structured Language Constructs Next while loop Syntax: Here each time value of variable n is multiply be i.
E infinite times Loop stops here if i is not less than 10 i. Hence loop is terminated. Increment i by 1 and store result to i. It enable you to match several values against one variable.. Its easier to read and write. Shells bash structured Language Constructs Next The case Statement The case statement is good alternative to Multilevel if-then-else-fi statement..
The shell then executes all the statements up to the two semicolons that are next to each other. See the one more example of case statement in chapter 4 of section shift command. And for last run. Prev Home Next while loop Up How to de-bug the shell script? Note that esac is always required to indicate end of case statement. I can not gat a Maruti for you". For first test run its match with van and it will show output "For van Rs. General syntax is as follows: Shells bash structured Language Constructs Next How to de-bug the shell script?
While programming shell sometimes you need to find the errors bugs in shell script and correct the errors remove errors. For this purpose you can use -v and -x option with sh or bash command to debug the shell script. Up program http: See the file system tutorial for more information on Linux disk.
The files in this directory mostly represent peripheral devices such disks like floppy disk. Local variable can be used in same shell. The syntax for AND list is as follows Syntax: The syntax for OR list as follows Syntax: You can use both as follows Syntax: In Linux And in C programming Language your keyboard. Following are name of such files http: This is called input redirection.
If you wish to take input from file for sort command give command as follows: This is called output redirection. To clear your idea onsider another example by writing shell script as follows: Number are not supplied" echo "Usage: Now if we try to redirect this error-output to file.
You can redirect the output from a file descriptor directly to file with following syntax Syntax: No such file or directory Above command gives error as output. The last file stderr numbered as 2 is used by our program to print error on screen. The use of first two files i.
To overcome this problem you have to use following command: Number are not supplied Usage: For second sample run. It means we have to print our error message on stderr not on stdout. To overcome this problem replace above echo statements as follows echo "Error: What all this mean is you can't perform all of life's task alone. To overcome this problem and to add you own function to automate some of the day today life task.
Have nice computing. This way you can call function.
It means whenever programs gets complicated. First logon as root or if you already logon with your name your login is not root.. The above logic also applies to computer program shell script. A return statement will terminate the function. They work together to perform all of life's task. Note that after restarting your computer you will loss this SayHello function..
Function performs particular activity in shell i. When program gets complex we need to use divide and conquer technique. To add function to this file you must logon as root. To define function use following syntax: Putting PS1 here ensures that it gets loaded every time. If you want to add particular http: Press a key. I want to show message Buy! Then open your. Open file. Life never be the same. If you want to show some message or want to perform some action when you logout.
When ever I logout. Passing parameters to User define function. Vivek Your age please: Even you can create menus to interact with user. Write script as: You can accomplish this as follows: Please select choice 1. Statement Explanation Start infinite loop.
But there is one utility supplied with Red Hat Linux version 6. If menu item 3 cal. Input box etc. Take appropriate action according echo "Press a key. Next section shows you how to use dialog utility.. In Linux shell i. For Red Hat Linux 6. Before understanding the syntax of dialog utility try the following script: Press any key.
Here 7 and 50 are height-of-box and width-of-box respectively. Use dialog utility to Display dialog boxes from shell scripts. The title of box is specified by --title option and infobox with --infobox "Message" with this option..
The answer is exit status. After asking question how do we know.. Get exit status of dialog utility http: In this example we are taking Name of user as input. But where we are going to store http: For input box's exit status refer the following table: Calendar cal. Putting it all together Its time to write script to create menus using dialog utility.
Editor vi. Editor and Editor "To start vi editor " description for menu item called as item3 i. The only problem with dialog utility is it work slowly. Calendar and description for menu item called as item2 i. Putting it all together --menu option is used of dialog utility to create menus.
As you see. Prev Home Next Input inputbox using dialog utility Up trap command http: Next this menu-item is retrieved from temporary file and following case statement compare the menu-item and takes appropriate step according to selected menu item. When such signal occurs its send to all process currently running in your system. Now consider following shell script: Then one infinite loop begins. You can view your database file by using cat command. To achieve this we have to first detect Signal using trap command.
Now problem is that while running this script. Our script get terminated. After that. Open above script in editor and modify it so that at the end it will look like as follows: Putting Up The shift command it all together http: Write the following shell script to clear you idea: For example consider the following simple shell script: The following command would shift the positional parameters two places: You can use shift command to parse the command line args option.
Advanced Shell Scripting Commands Next The shift Command The shift command moves the current values stored in the positional parameters command line args to the left one position. For example. It use -n and -b as command line option which means: First three sample run converts the number -n to respectively 1F4 hexadecimal number i. Last sample run shows that command line options can given different ways i.
Because the base system 4 is unknown to our script.
This is done using case statement.. Once first two command line options args are read. As you can see shift command can use to parse the command line args option. This is useful if you have limited number of command line option. If command line options are too many then this approach works slowly as well as complex to write and maintained.
You need to use another shell built in command - getopts. Next section shows the use of getopts command. You still need the shift command in conjunction with getopts for other shell scripting work.
Prev Home Next trap command Up getopts command. Advanced Shell Scripting Commands Next. Usually used in while loop. As defined in man pages: Each time it is invoked, getopts places the next option in the shell variable variable1, When an option requires an argument, getopts places that argument into the variable OPTARG.
On errors getopts diagnostic messages are printed when illegal options or missing option arguments are encountered. If an illegal option is seen, getopts places?
We have script called ani which has syntax as ani -n -a -s -w -d Options: These are optional argument -n name of animal -a age of animal -s sex of animal -w weight of animal -d demo values if any of the above options are used their values are not taken Above ani script is as follows: These are optional argument" echo " -n name of animal" echo " -a age of animal" echo " -s sex of animal ".
See because of getopts, we can pass command line argument in different style. Essential Utilities for Power User Next. Introduction Linux contains powerful utility programs. Following section introduce you to some of the essential utilities as well as expression. While programming shell you need to use these essential utilities.
After the quick introduction to utilities, you will learn the expression. Essential Utilities for Power User Next Prepering for Quick Tour of essential utilities For this part of tutorial create sname and smark data files as follows Using text editor of your choice Note Each data block is separated from the other by TAB character i.
In this example -f1 its 1 i. Essential Utilities for Power User Next Selecting portion of a file using cut utility Suppose from sname file you wish to print name of student on-screen. To select Sr. Selecting portion of a file. To clear your idea try following command at shell prompt: General Syntax of paste utility: Putting lines together. Can you note down basic difference between cut and paste utility?
Prev Home Next Translating range of characters using tr Putting lines together using paste utility Up utility http: Note that join will only work. Notice that Sr. General Syntax of join utility: The join utility joins. I came to know my mistake that entire paragraph must be in lowercase characters. After typing following paragraph. Essential Utilities for Power User Next Translateing range of characters using tr utility Type the following command at shell prompt: To translate range of characters into other range of characters.
Now try the following and note down its output. Use of awk utility: To manipulate data. Essential Utilities for Power User Next Data manipulation using awk utility Before learning more about awk create data file using any text editor or simply vi: Prev Home Next Translating range of characters using tr Up sed utility.
Editing file without using utility editor http: Editing file without using editor For this part of tutorial create data file as follows teaormilk India's milk is good. Essential Utilities for Power User Next sed utility. Prev Home Next Removing duplicate lines using uniq Data manipulation using awk utility Up utility http: Steam line editor which uses 'ex' editors command for editing text files without starting ex. But if you examine output of uniq. Because the uniq utility compare only adjacent lines.
Essential Utilities for Power User Next Removing duplicate lines using uniq utility Create text file personame as follows: After creating file. Above command prints those lines which are unique. Editing file without using Up Finding matching pattern using grep editor utility http: So if this expression is found any where on line its printed.
Expression by grep is read as the letter t followed by o and so on. Learning expressions with ex Next Introduction In the chpater 5. If you use them with other tools. Pattern defined as: In the next part of LSST you will learn how to construct regular expression using ex editor. Metacharacters defined as: Learning expressions with ex What does "cat" mean to you?
One its the word cat. If same question is asked to computer not computer but to grep utility then grep will try to find all occurrence of "cat" word remember grep read word "cat" as the c letter followed by a and followed by t including cat. I know 'tom' cat. Pattern can be change from one to another. In rest part of tutorial we will learn more about patterns. Learning expressions with ex Next Getting started with ex You can start the ex editor by typeing ex at shell prompt: Type "visual" to go to Normal mode.
As you can see. Its time to open our demofile. I love linux. Learning expressions with ex Next Printing text on-screen First open the our demofile as follows: Printing lines using range Now if you want to print 1st line to next 5 line i.
Printing entire file on-screen Give command: This is vivek from Poona. It is different from all other Os http: Printing particular line To print 2nd line from our file give command: Now type 'p' in front of: I will stop.
NOTE By default p command will print current line. Here p stands print. If you don't want number you can turn off numbers by issuing following command: Printing line number with our text Give command: Learning expressions with ex Next Deleting lines Give command: You can even delete range of line by giving command as: NOTE Here 1. It is different from all other Os. It is different from all other Os My brother Vikrant also loves linux.
Do you know? DOT is special command of linux. He currently lerarns linux. Linux is cooool. Learning expressions with ex Next Copying lines Give command as follows: Rani my sister never uses Linux She only loves to play games and nothing else. Next year linux will be 11 year old. So it mean copy first four line to end of file.
You can delete this line as follows: Linux is now 10 years old. And p is print command of ex. Note In ex you can specify address line using number for various operation. It means g stands for 1. This is useful if you know the line number in advance. This instruct ex to find all occurrence of pattern. In previous example: Watch p is missing: Try following: If you want to print all occurrence of the word "linux" then you have to use g. Saving the file in ex Give command: Learning expressions with ex Next Searching the words a Give following command: Try following and note down difference Hint.
My brother Vikrant also loves linux. Quitting the ex Give command: Note use wq command to do save and exit from ex. Note Using above command.. Learning expressions with ex Next Find and Replace Substituting regular expression Give command as follows: Using above command.
Above command can be explained as follows: Command Explanation 8 Goto line 8. Command Explanation: Now in above line "also" word is occurred twice. Rani my sister always uses UNIX By default substitute command only substitute first occurrence of a pattern on a line. Try the following and watch the output very carefully. Note that above command can be also written as follows: Now try the following: Rani my sister always uses Linux: Its shortcut.
UNIX is now 10 years old. Let's take another example. The g option at the end instruct s command to perform replacement on all occurrences of the target pattern within a address line.
If you want to s command to work with all occurrences of pattern within a address line give command as follows: Type y to replace the word or n to not replace or a to replace all occurrence of word. Learning expressions with ex Next Replacing word with confirmation from user Give command as follows: To find the line which contain Linux pattern at the beginning give command: Shell script to gathered useful system information such as CPU, disks, Ram and your environment etc.
Integrating awk script with shell script: Appendix - A: Quick Introduction to LinuxNext.
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. I assumes you have at least working knowledge of Linux i. 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. 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. I have used a hands-on approach in this tutorial. The idea is very clear "do it yourself or learn by doing" i. Chapter 1 to 4 shows most of the useful and important shell scripting concepts. Chapter 6 and 7 is all about expression and expression mostly used by tools such as sed and awk.
Chapter 8 is loaded with tons of shell scripting examples divided into different categories. Chapter 9 gives more resources information which can be used while learning the shell scripting like information on Linux file system, common Linux command reference and other resources.
Chapter 1 introduces to basic concepts such as what is Linux, where Linux can used and continue explaning the shell, shell script and kernel etc. Chapter 2 shows how to write the shell script and execute them. It explains many basic concepts which requires to write shell script. LSST v1. Chapter 3 is all about making decision in shell scripting as well as loops in shell. It also shows you nesting concept for if and for loop statement and debugging of shell script.
Chapter 4 introduces the many advanced shell scripting concepts such as function, user interface, File Descriptors, signal handling, Multiple command line arguments etc. Chapter 5 introduces to powerful utility programs which can be used variety of purpose while programming the shell. Chapter 6 and 7 gives more information on patterns, filters, expressions, and off course sed and awk is covered in depth. Chapter 8 contains lot of example of shell scripting divided into various category such as logic development, system administration etc.
I hope you get as much pleasure reading this tutorial, as I had writing it. In , Linus Torvalds studying Unix at the University, where he used special educational experimental purpose operating system called Minix small version of Unix and used in Academic environment.
But Minix had it's own limitations. Linus felt he could do better than the Minix. So he developed his own version of Minix, which is now know as Linux. Linux is Open Source From the start of the day. For more information on Linus Torvalds, please visit his home page.