Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas

linux - shell scripting tutorial - a beginner's handbook, Notas de estudo de Matemática

linux - shell scripting tutorial - a beginner's handbook

Tipologia: Notas de estudo

Antes de 2010
Em oferta
50 Pontos
Discount

Oferta por tempo limitado


Compartilhado em 13/10/2009

rodrigo-viana-10
rodrigo-viana-10 🇧🇷

4.8

(4)

5 documentos

Pré-visualização parcial do texto

Baixe linux - shell scripting tutorial - a beginner's handbook e outras Notas de estudo em PDF para Matemática, somente na Docsity! Written by Vivek G. Gite. Cyberciti Computers & nixCraft, Pune, INDIA. This Document is Copyright (C) 1999-2002, Vivek G. Gite. Linux Shell Scripting Tutorial v1.05r3 A Beginner's handbook Copyright © 1999-2002 by Vivek G. Gite <vivek@nixcraft.com> (Formally know as www.vivek-tech.com) Table of Contents Chapter 1: Quick Introduction to Linux What Linux is? Who developed the Linux? How to get Linux? How to Install Linux Where I can use Linux? What Kernel Is? What is Linux Shell? How to use Shell What is Shell Script ? Why to Write Shell Script ? More on Shell... Chapter 2: Getting started with Shell Programming How to write shell script Variables in shell How to define User defined variables (UDV) Rules for Naming variable name (Both UDV and System Variable) How to print or access value of UDV (User defined variables) echo Command Linux Shell Scripting Tutorial v1.05r3 - A Beginner's handbook http://www.cyberciti.biz/pdf/lsst/index.html (1 of 5) [7/29/2002 6:50:01 PM] Logic Development: Shell script to print given numbers sum of all digit Shell script to print contains of file from given line number to next given number of lines Shell script to say Good morning/Afternoon/Evening as you log in to system Shell script to find whether entered year is Leap or not Sort the given five number in ascending order (use of array) Command line (args) handling: Adding 2 nos. suppiled as command line args Calculating average of given numbers on command line args Finding out biggest number from given three nos suppiled as command line args Shell script to implement getopts statement. Basic math Calculator (case statement) Loops using while & for loop: Print nos. as 5,4,3,2,1 using while loop Printing the patterns using for loop. Arithmetic in shell scripting: Performing real number calculation in shell script Converting decimal number to hexadecimal number Calculating factorial of given number File handling: Shell script to determine whether given file exist or not. Screen handling/echo command with escape sequence code: Shell script to print "Hello World" message, in Bold, Blink effect, and in different colors like red, brown etc. Background process implementation: Digital clock using shell script User interface and Functions in shell script: Shell script to implements menu based system. System Administration: Getting more information about your working environment through shell script Shell script to gathered useful system information such as CPU, disks, Ram and your environment etc. Shell script to add DNS Entery to BIND Database with default Nameservers, Mail Servers (MX) and host Integrating awk script with shell script: Script to convert file names from UPPERCASE to lowercase file names or vice versa. Chapter 9: Other Resources Appendix - A : Linux File Server Tutorial (LFST) version b0.1 Rev. 2 Appendix - B : Linux Command Reference (LCR) About the author About this Document Linux Shell Scripting Tutorial v1.05r3 - A Beginner's handbook http://www.cyberciti.biz/pdf/lsst/index.html (4 of 5) [7/29/2002 6:50:01 PM] Home Next Up Quick Introduction to Linux ( Cyeberciti Computers & nixCraft has years of experince in Linux / Unix / FreeBSD. If you need any assistance, education, support for Linux / Unix, write to sales@cyberciti.biz ) Linux Shell Scripting Tutorial v1.05r3 - A Beginner's handbook http://www.cyberciti.biz/pdf/lsst/index.html (5 of 5) [7/29/2002 6:50:01 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 1: Introduction: Quick Introduction to Linux Next 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 Chapter Organization Chapter 1 to 4 shows most of the useful and important shell scripting concepts. Chapter 5 introduction to tools & utilities which can be used while programming the Linux shell smartly. 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.05r3 > Chapter 1 > Quick Introduction to Linux http://www.cyberciti.biz/pdf/lsst/ch01.html (1 of 2) [7/29/2002 6:50:59 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 1: Introduction: Quick Introduction to Linux Next Who developed the Linux? In 1991, 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. Prev Home Next What Linux is? Up How to get Linux? LSST v1.05r3 > Chapter 1 > Who developed the Linux? http://www.cyberciti.biz/pdf/lsst/ch01sec02.html [7/29/2002 6:51:08 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 1: Introduction: Quick Introduction to Linux Next How to get Linux? Linux available for download over the net, this is useful if your internet connection is fast. Another way is order the CD-ROMs which saves time, and the installation from CD-ROM is fast/automatic. Various Linux distributions available. Following are important Linux distributions. Linux distributions. Website/Logo Red Hat Linux: http://www.redhat.com/ SuSE Linux: http://www.suse.com/ Mandrake Linux: http://www.mandrakesoft.com/ Caldera Linux: http://www.calderasystems.com/ Debian GNU/Linux: http://www.debian.org/ Slackware Linux: http://www.slackware.com/ Note: If you are in India then you can get Linux Distribution from the Leading Computer magazine such as PC Quest (Even PCQuest has got its own Linux flavour) or if you are in Pune, India please visit our web site to obtained the Red Hat Linux or any other official Linux distribution. Note that you can also obtained your Linux distribution with Linux books which you purchase from local book store. LSST v1.05 > Chapter 1 > How to get Linux? http://www.cyberciti.biz/pdf/lsst/ch01sec03.html (1 of 2) [7/29/2002 6:51:11 PM] Prev Home Next Who developed the Linux? Up How to Install Linux LSST v1.05 > Chapter 1 > How to get Linux? http://www.cyberciti.biz/pdf/lsst/ch01sec03.html (2 of 2) [7/29/2002 6:51:11 PM] Linux Server can act as Proxy/Mail/WWW/Router Server etc. So you can use Linux for: Personal Work● Web Server● Software Development Workstation● Workgroup Server● In Data Center for various server activities such as FTP, Telnet, SSH, Web, Mail, Proxy, Proxy Cache Appliance etc ● See the LESSBS project for more information on Linux Essential Services (as mentioned above) and how to implement them in easy manner for you or your organization. Prev Home Next How to Install Linux Up What Kernel Is? LSST v1.05 > Chapter 1 > Where I can use Linux? http://www.cyberciti.biz/pdf/lsst/ch01sec05.html (2 of 2) [7/29/2002 6:51:26 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 1: Introduction : Linux Shell basics Next What Kernel Is? Kernel is heart of Linux Os. It manages resource of Linux Os. Resources means facilities available in Linux. For e.g. Facility to store data, print data on printer, memory, file management etc . Kernel decides who will use this resource, for how long and when. It runs your programs (or set up to execute binary files). The kernel acts as an intermediary between the computer hardware and various programs/application/shell. It's Memory resident portion of Linux. It performance following task :- I/O management● Process management● Device management● File management● Memory management● Prev Home Next Where I can use Linux? Up What is Linux Shell? LSST v1.05 > Chapter 1 > LSST v1.05 > Chapter 1 > http://www.cyberciti.biz/pdf/lsst/ch01sec06.html [7/29/2002 6:51:28 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 1: Introduction : Linux Shell basics Next What is Linux Shell ? Computer understand the language of 0's and 1's called binary language. In early days of computing, instruction are provided using binary language, which is difficult for all of us, to read and write. So in Os there is special program called Shell. Shell accepts your instruction or commands in English (mostly) and if its a valid command, it is passed to kernel. Shell is a user program or it's a environment provided for user interaction. Shell is an command language interpreter that executes commands read from the standard input device (keyboard) or from a file. Shell is not part of system kernel, but uses the system kernel to execute programs, create files etc. Several shell available with Linux including: Shell Name Developed by Where Remark BASH ( Bourne-Again SHell ) Brian Fox and Chet Ramey Free Software Foundation Most common shell in Linux. It's Freeware shell. CSH (C SHell) Bill Joy University of California (For BSD) The C shell's syntax and usage are very similar to the C programming language. KSH (Korn SHell) David Korn AT & T Bell Labs -- TCSH See the man page. Type $ man tcsh -- TCSH is an enhanced but completely compatible version of the Berkeley UNIX C shell (CSH). Tip: To find all available shells in your system type following command: $ cat /etc/shells Note that each shell does the same job, but each understand a different command syntax and provides different built-in functions. In MS-DOS, Shell name is COMMAND.COM which is also used for same purpose, but it's not as powerful as our Linux Shells are! Any of the above shell reads command from user (via Keyboard or Mouse) and tells Linux Os what users want. If we are giving commands from keyboard it is called command line interface ( Usually in-front of $ prompt. This prompt is depend upon your shell and Environment that you set or by your System Administrator, therefore you may get different prompt ). LSST v1.05 > Chapter 1 > What is Linux Shell ? http://www.cyberciti.biz/pdf/lsst/ch01sec07.html (1 of 2) [7/29/2002 6:51:30 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 1: Introduction : Linux Shell basics Next What is Shell Script ? Normally shells are interactive. It means shell accept command from you (via keyboard) and execute them. But if you use command one by one (sequence of 'n' number of commands) , the you can store this sequence of command to text file and tell the shell to execute this text file instead of entering the commands. This is know as shell script. Shell script defined as: "Shell Script is series of command written in plain text file. Shell script is just like batch file is MS-DOS but have more power than the MS-DOS batch file." Prev Home Next How to use Shell Up Why to Write Shell Script ? LSST v1.05 > Chapter 1 > What is Shell Script ? http://www.cyberciti.biz/pdf/lsst/ch01sec09.html [7/29/2002 6:51:33 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 1: Introduction : Linux Shell basics Next Why to Write Shell Script ? Shell script can take input from user, file and output them on screen.● Useful to create our own commands.● Save lots of time.● To automate some task of day today life.● System Administration part can be also automated.● Prev Home Next What is Shell Script ? Up More on Shell... LSST v1.05 > Chapter 1 > Why to Write Shell Script ? http://www.cyberciti.biz/pdf/lsst/ch01sec10.html [7/29/2002 6:51:34 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 1: Introduction : Linux Shell basics Next Which Shell We are using to write Shell Script ? In this tutorial we are using bash shell. Objective of this Tutorial (LSST v.1.5) Try to understand Linux Os Try to understand the basics of Linux shell Try to learn the Linux shell programming What I need to learn this Tutorial (LSST v.1.5) Linux OS ( I have used Red Hat Linux distribution Version 6.x+) Web Browse to read tutorial. (IE or Netscape) For PDF version you need PDF reader. Linux - bash shell. (Available with almost all Linux Distributions. By default bash is default shell for Red Hat Linux Distribution). All the scripts are also tested on Red Hat Linux version 7.2. Prev Home Next Why to Write Shell Script ? Up Getting started with Shell Programming LSST v1.05 > Chapter 1 > Linux Shell basics http://www.cyberciti.biz/pdf/lsst/ch01sec11.html [7/29/2002 6:51:36 PM] This will not run script since we have not set execute permission for our script first; to do this type command $ chmod 755 first $ ./first 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. $ vi ginfo # # # Script to print user information who currently login , current date & time # clear echo "Hello $USER" echo "Today is \c ";date echo "Number of user login : \c" ; who | wc -l echo "Calendar" cal exit 0 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 http://www.cyberciti.biz/pdf/lsst/ch02sec01.html (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: $ echo $USERNAME $ echo $HOME Exercise: 1) If you want to print your home directory location then you give command: a) $ echo $HOME OR LSST v1.05r3 > Chapter 2 > Variables in Shell http://www.cyberciti.biz/pdf/lsst/ch02sec02.html (1 of 2) [7/29/2002 6:51:42 PM] (b) $ echo HOME 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 http://www.cyberciti.biz/pdf/lsst/ch02sec02.html (2 of 2) [7/29/2002 6:51:42 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) http://www.cyberciti.biz/pdf/lsst/ch02sec04.html (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: $ 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. Exercise Q.1.How to Define variable x with value 10 and print it on screen. Q.2.How to Define variable xn with value Rani and print it on screen Q.3.How to print sum of two numbers, let's say 6 and 3? Q.4.How to define two variable x=20, y=5 and then to print division of x and y (i.e. x/y) Q.5.Modify above and store division of x and y to variable called z Q.6.Point out error if any in following script $ vi variscript # # # Script to test MY knowledge about variables! # myname=Vivek myos = TroubleOS myno=5 echo "My name is $myname" echo "My os is $myos" echo "My number is myno, can you see this number" For Answers Click here Prev Home Next LSST v1.05r3 > Chapter 2 > How to print or access value of UDV (User defined variables) http://www.cyberciti.biz/pdf/lsst/ch02sec05.html (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) http://www.cyberciti.biz/pdf/lsst/ch02sec05.html (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 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 http://www.cyberciti.biz/pdf/lsst/ch02sec08.html [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: $ expr 1 + 3 $ echo $? $ echo Welcome $ echo $? $ wildwest canwork? $ echo $? $ date $ echo $? $ echon $? $ echo $? $? useful variable, want to know more such Linux variables click here to explore them! LSST v1.05r3 > Chapter 2 > Exit Status http://www.cyberciti.biz/pdf/lsst/ch02sec09.html (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 http://www.cyberciti.biz/pdf/lsst/ch02sec09.html (2 of 2) [7/29/2002 6:51:55 PM] /bin/ps /bin/rvi /bin/sleep /bin/touch /bin/view /bin/pwd /bin/rview /bin/sort /bin/true /bin/wcomp /bin/red /bin/sayHello /bin/stty /bin/umount /bin/xconf /bin/remadmin /bin/sed /bin/su /bin/uname /bin/ypdomainname /bin/rm /bin/setserial /bin/sync /bin/userconf /bin/zcat /bin/rmdir /bin/sfxload /bin/tar /bin/usleep /bin/rpm /bin/sh /bin/tcsh /bin/vi Prev Home Next The read Statement Up More command on one command line LSST v1.05r3 > Chapter 2 > Wild cards (Filename Shorthand or meta Characters) http://www.cyberciti.biz/pdf/lsst/ch02sec11.html (2 of 2) [7/29/2002 6:51:58 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 2: Getting started with Shell Programming Next More command on one command line Syntax: command1;command2 To run two command with one command line. Examples: $ date;who Will print today's date followed by users who are currently login. Note that You can't use $ date who for same purpose, you must put semicolon in between date and who command. Prev Home Next Wild cards (Filename Shorthand or meta Characters) Up Command Line Processing LSST v1.05r3 > Chapter 2 > More command on one command line http://www.cyberciti.biz/pdf/lsst/ch02sec12.html [7/29/2002 6:52:00 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 2: Getting started with Shell Programming Next Command Line Processing Try the following command (assumes that the file "grate_stories_of" is not exist on your system) $ ls grate_stories_of It will print message something like - grate_stories_of: No such file or directory. ls is the name of an actual command and shell executed this command when you type command at shell prompt. Now it creates one more question What are commands? What happened when you type $ ls grate_stories_of ? The first word on command line is, ls - is name of the command to be executed. Everything else on command line is taken as arguments to this command. For e.g. $ tail +10 myf Name of command is tail, and the arguments are +10 and myf. Exercise Try to determine command and arguments from following commands $ ls foo $ cp y y.bak $ mv y.bak y.okay $ tail -10 myf $ mail raj $ sort -r -n myf $ date $ clear Answer: Command No. of argument to this command(i.e $#) Actual Argument ls 1 foo cp 2 y and y.bak mv 2 y.bak and y.okay tail 2 -10 and myf mail 1 raj sort 3 -r, -n, and myf date 0 clear 0 NOTE: $# holds number of arguments specified on command line. And $* or $@ refer to all arguments passed to LSST v1.05r3 > Chapter 2 > Command Line Processing http://www.cyberciti.biz/pdf/lsst/ch02sec13.html (1 of 2) [7/29/2002 6:52:02 PM] Here $# (built in shell variable ) will be 2 (Since foo and bar only two Arguments), Please note at a time such 9 arguments can be used from $1..$9, You can also refer all of them by using $* (which expand to `$1,$2...$9`). Note that $1..$9 i.e command line arguments to shell script is know as "positional parameters". Exercise Try to write following for commands Shell Script Name ($0), No. of Arguments (i.e. $#), And actual argument (i.e. $1,$2 etc) $ sum 11 20 $ math 4 - 7 $ d $ bp -5 myf +20 $ Ls * $ cal $ findBS 4 8 24 BIG Answer Shell Script Name No. Of Arguments to script Actual Argument ($1,..$9) $0 $# $1 $2 $3 $4 $5 sum 2 11 20 math 3 4 - 7 d 0 bp 3 -5 myf +20 Ls 1 * cal 0 findBS 4 4 8 24 BIG Following script is used to print command ling argument and will show you how to access them: $ vi demo #!/bin/sh # # Script that demos, command line args # echo "Total number of command line argument are $#" echo "$0 is script name" echo "$1 is first argument" echo "$2 is second argument" echo "All of them are :- $* or $@" Run it as follows LSST v1.05r3 > Chapter 2 > Why Command Line arguments required http://www.cyberciti.biz/pdf/lsst/ch02sec14.html (2 of 3) [7/29/2002 6:52:05 PM] Set execute permission as follows: $ chmod 755 demo Run it & test it as follows: $ ./demo Hello World If test successful, copy script to your own bin directory (Install script for private use) $ cp demo ~/bin Check whether it is working or not (?) $ demo $ demo Hello World NOTE: After this, for any script you have to used above command, in sequence, I am not going to show you all of the above command(s) for rest of Tutorial. Also note that you can't assigne the new value to command line arguments i.e positional parameters. So following all statements in shell script are invalid: $1 = 5 $2 = "My Name" Prev Home Next Command Line Processing Up Redirection of Standard output/input i.e.Input - Output redirection LSST v1.05r3 > Chapter 2 > Why Command Line arguments required http://www.cyberciti.biz/pdf/lsst/ch02sec14.html (3 of 3) [7/29/2002 6:52:05 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 2: Getting started with Shell Programming Next Redirection of Standard output/input i.e. Input - Output redirection Mostly all commands give output on screen or take input from keyboard, but in Linux (and in other OSs also) it's possible to send output to file or to read input from file. For e.g. $ ls command gives output to screen; to send output to file of ls command give command $ ls > filename It means put output of ls command to filename. There are three main redirection symbols >,>>,< (1) > Redirector Symbol Syntax: Linux-command > filename To output Linux-commands result (output of command or shell script) to file. Note that if file already exist, it will be overwritten else new file is created. For e.g. To send output of ls command give $ ls > myfiles Now if 'myfiles' file exist in your current directory it will be overwritten without any type of warning. (2) >> Redirector Symbol Syntax: Linux-command >> filename To output Linux-commands result (output of command or shell script) to END of file. Note that if file exist , it will be opened and new information/data will be written to END of file, without losing previous information/data, And if file is not exist, then new file is created. For e.g. To send output of date command to already exist file give command $ date >> myfiles (3) < Redirector Symbol Syntax: Linux-command < filename To take input to Linux-command from file instead of key-board. For e.g. To take input for cat command give $ cat < myfiles Click here to learn more about I/O Redirection You can also use above redirectors simultaneously as follows Create text file sname as follows LSST v1.05r3 > Chapter 2 > Redirection of Standard output/input i.e. Input - Output redirection http://www.cyberciti.biz/pdf/lsst/ch02sec15.html (1 of 2) [7/29/2002 6:52:06 PM] $ who | grep raju Output of who command is given as input to grep command So that it will print if particular user name if he is logon or nothing is printed (To see particular user is logon or not) Prev Home Next Redirection of Standard output/input i.e.Input - Output redirection Up Filter LSST v1.05r3 > Chapter 2 > Pipes http://www.cyberciti.biz/pdf/lsst/ch02sec16.html (2 of 2) [7/29/2002 6:52:08 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 2: 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. For e.g.. Suppose you have file called 'hotel.txt' with 100 lines data, And from 'hotel.txt' you would like to print contains from line number 20 to line number 30 and store this result to file called 'hlist' then give command: $ tail +20 < hotel.txt | head -n30 >hlist Here head command is filter which takes its input from tail command (tail command start selecting from line number 20 of given file i.e. hotel.txt) and passes this lines as input to head, whose output is redirected to 'hlist' file. Consider one more following example $ sort < sname | uniq > u_sname Here uniq is filter which takes its input from sort command and passes this lines as input to uniq; Then uniqs output is redirected to "u_sname" file. Prev Home Next Pipes Up What is Processes LSST v1.05r3 > Chapter 2 > Filter http://www.cyberciti.biz/pdf/lsst/ch02sec17.html [7/29/2002 6:52:09 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 2: Getting started with Shell Programming Next What is Processes Process is kind of program or task carried out by your PC. For e.g. $ ls -lR ls command or a request to list files in a directory and all subdirectory in your current directory - It is a process. Process defined as: "A process is program (command given by user) to perform specific Job. In Linux when you start process, it gives a number to process (called PID or process-id), PID starts from 0 to 65535." Prev Home Next Filter Up Why Process required LSST v1.05r3 > Chapter 2 > What is Processes http://www.cyberciti.biz/pdf/lsst/ch02sec18.html [7/29/2002 6:52:11 PM] 1) Is it example of Multitasking? 2) How you will you find out the both running process (MP3 Playing & Letter typing)? 3) "Currently only two Process are running in your Linux/PC environment", Is it True or False?, And how you will verify this? 4) You don't want to listen music (MP3 Files) but want to continue with other work on PC, you will take any of the following action: Turn off Speakers1. Turn off Computer / Shutdown Linux Os2. Kill the MP3 playing process3. None of the above4. Click here for answers. Prev Home Next Why Process required Up Shells (bash) structured Language Constructs LSST v1.05r3 > Chapter 3 > Linux Command Related with Process http://www.cyberciti.biz/pdf/lsst/ch02sec20.html (2 of 2) [7/29/2002 6:52:14 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 3: Shells (bash) structured Language Constructs Next Introduction Making decision is important part in ONCE life as well as in computers logical driven program. In fact logic is not LOGIC until you use decision making. This chapter introduces to the bash's structured language constructs such as: Decision making● Loops● Is there any difference making decision in Real life and with Computers? 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. What computer know is 0 (zero) and 1 that is Yes or No. To make this idea clear, lets play some game (WOW!) with bc - Linux calculator program. $ bc After this command bc is started and waiting for your commands, i.e. give it some calculation as follows type 5 + 2 as: 5 + 2 7 7 is response of bc i.e. addition of 5 + 2 you can even try 5 - 2 5 / 2 See what happened if you type 5 > 2 as follows 5 > 2 1 1 (One?) is response of bc, How? bc compare 5 with 2 as, Is 5 is greater then 2, (If I ask same question to you, your answer will be YES), bc gives this 'YES' answer by showing 1 value. Now try 5 < 2 0 0 (Zero) indicates the false i.e. Is 5 is less than 2?, Your answer will be no which is indicated by bc by showing 0 (Zero). Remember in bc, relational expression always returns true (1) or false (0 - zero). Try following in bc to clear your Idea and not down bc's response 5 > 12 5 == 10 5 != 2 5 == 5 12 < 2 Expression Meaning to us Your Answer BC's Response 5 > 12 Is 5 greater than 12 NO 0 5 == 10 Is 5 is equal to 10 NO 0 5 != 2 Is 5 is NOT equal to 2 YES 1 LSST v1.05r3 > Chapter 3 > Introducation http://www.cyberciti.biz/pdf/lsst/ch03.html (1 of 2) [7/29/2002 6:52:15 PM] 5 == 5 Is 5 is equal to 5 YES 1 1 < 2 Is 1 is less than 2 Yes 1 It means when ever there is any type of comparison in Linux Shell It gives only two answer one is YES and NO is other. In Linux Shell Value Meaning Example Zero Value (0) Yes/True 0 NON-ZERO Value No/False -1, 32, 55 anything but not zero Remember both bc and Linux Shell uses different ways to show True/False values Value Shown in bc as Shown in Linux Shell as True/Yes 1 0 False/No 0 Non - zero value Prev Home Next Linux Command(s) Related with Process Up if condition LSST v1.05r3 > Chapter 3 > Introducation http://www.cyberciti.biz/pdf/lsst/ch03.html (2 of 2) [7/29/2002 6:52:15 PM] Shells (bash) structured Language Constructs Up test command or [ expr ] LSST v1.05r3 > Chapter 3 > if condition http://www.cyberciti.biz/pdf/lsst/ch03sec01.html (3 of 3) [7/29/2002 6:52:16 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 3: Shells (bash) structured Language Constructs Next test command or [ expr ] test command or [ expr ] is used to see if an expression is true, and if it is true it return zero(0), otherwise returns nonzero for false. Syntax: test expression OR [ expression ] Example: Following script determine whether given argument number is positive. $ cat > ispositive #!/bin/sh # # Script to see whether argument is positive # if test $1 -gt 0 then echo "$1 number is positive" fi Run it as follows $ chmod 755 ispostive $ ispostive 5 5 number is positive $ispostive -45 Nothing is printed $ispostive ./ispostive: test: -gt: unary operator expected Detailed explanation The line, if test $1 -gt 0 , test to see if first command line argument($1) is greater than 0. If it is true(0) then test will return 0 and output will printed as 5 number is positive but for -45 argument there is no output because our condition is not true(0) (no -45 is not greater than 0) hence echo statement is skipped. And for last statement we have not supplied any argument hence error ./ispostive: test: -gt: unary operator expected, is generated by shell , to avoid such error we can test whether command line argument is supplied or not. test or [ expr ] works with 1.Integer ( Number without decimal point) 2.File types 3.Character strings LSST v1.05r3 > Chapter 3 > test command or [ expr ] http://www.cyberciti.biz/pdf/lsst/ch03sec02.html (1 of 3) [7/29/2002 6:52:17 PM] For Mathematics, use following operator in Shell Script Mathematical Operator in Shell Script Meaning Normal Arithmetical/ Mathematical Statements But in Shell For test statement with if command For [ expr ] statement with if command -eq is equal to 5 == 6 if test 5 -eq 6 if [ 5 -eq 6 ] -ne is not equal to 5 != 6 if test 5 -ne 6 if [ 5 -ne 6 ] -lt is less than 5 < 6 if test 5 -lt 6 if [ 5 -lt 6 ] -le is less than or equal to 5 <= 6 if test 5 -le 6 if [ 5 -le 6 ] -gt is greater than 5 > 6 if test 5 -gt 6 if [ 5 -gt 6 ] -ge is greater than or equal to 5 >= 6 if test 5 -ge 6 if [ 5 -ge 6 ] NOTE: == is equal, != is not equal. For string Comparisons use Operator Meaning string1 = string2 string1 is equal to string2 string1 != string2 string1 is NOT equal to string2 string1 string1 is NOT NULL or not defined -n string1 string1 is NOT NULL and does exist -z string1 string1 is NULL and does exist Shell also test for file and directory types Test Meaning -s file Non empty file -f file Is File exist or normal file and not a directory -d dir Is Directory exist and not a file -w file Is writeable file -r file Is read-only file -x file Is file is executable Logical Operators Logical operators are used to combine two or more condition at a time Operator Meaning ! expression Logical NOT expression1 -a expression2 Logical AND LSST v1.05r3 > Chapter 3 > test command or [ expr ] http://www.cyberciti.biz/pdf/lsst/ch03sec02.html (2 of 3) [7/29/2002 6:52:17 PM] -45 number is negative $ isnump_n ./ispos_n : You must give/supply one integers $ isnump_n 0 0 number is negative Detailed explanation First script checks whether command line argument is given or not, if not given then it print error message as "./ispos_n : You must give/supply one integers". if statement checks whether number of argument ($#) passed to script is not equal (-eq) to 0, if we passed any argument to script then this if statement is false and if no command line argument is given then this if statement is true. The echo command i.e. echo "$0 : You must give/supply one integers" | | | | 1 2 1 will print Name of script 2 will print this error message And finally statement exit 1 causes normal program termination with exit status 1 (nonzero means script is not successfully run). The last sample run $ isnump_n 0 , gives output as "0 number is negative", because given argument is not > 0, hence condition is false and it's taken as negative number. To avoid this replace second if statement with if test $1 -ge 0. 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. This is called the nesting of ifs. $ vi nestedif.sh osch=0 echo "1. Unix (Sun Os)" echo "2. Linux (Red Hat)" echo -n "Select your os choice [1 or 2]? " read osch if [ $osch -eq 1 ] ; then echo "You Pick up Unix (Sun Os)" else #### nested if i.e. if within if ###### LSST v1.05r3 > Chapter 3 > if...else...fi http://www.cyberciti.biz/pdf/lsst/ch03sec03.html (2 of 4) [7/29/2002 6:52:18 PM] if [ $osch -eq 2 ] ; then echo "You Pick up Linux (Red Hat)" else echo "What you don't like Unix/Linux OS." fi fi Run the above shell script as follows: $ chmod +x nestedif.sh $ ./nestedif.sh 1. Unix (Sun Os) 2. Linux (Red Hat) Select you os choice [1 or 2]? 1 You Pick up Unix (Sun Os) $ ./nestedif.sh 1. Unix (Sun Os) 2. Linux (Red Hat) Select you os choice [1 or 2]? 2 You Pick up Linux (Red Hat) $ ./nestedif.sh 1. Unix (Sun Os) 2. Linux (Red Hat) Select you os choice [1 or 2]? 3 What you don't like Unix/Linux OS. 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. If it is false as well the final else statement is executed. You can use the nested ifs as follows also: Syntax: if condition then if condition then ..... .. do this else .... .. do this fi else LSST v1.05r3 > Chapter 3 > if...else...fi http://www.cyberciti.biz/pdf/lsst/ch03sec03.html (3 of 4) [7/29/2002 6:52:18 PM] ... ..... do this fi Prev Home Next test command or [ expr ] Up Multilevel if-then-else LSST v1.05r3 > Chapter 3 > if...else...fi http://www.cyberciti.biz/pdf/lsst/ch03sec03.html (4 of 4) [7/29/2002 6:52:18 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 3: Shells (bash) structured Language Constructs Next Loops in Shell Scripts Loop defined as: "Computer can repeat particular instruction again and again, until particular condition satisfies. A group of instruction that is executed repeatedly is called a loop." Bash supports: for loop● while loop● Note that in each and every loop, (a) First, the variable used in loop condition must be initialized, then execution of the loop begins. (b) A test (condition) is made at the beginning of each iteration. (c) The body of loop ends with a statement that modifies the value of the test (condition) variable. Prev Home Next Multilevel if-then-else Up for loop LSST v1.05r3 > Chapter 3 > Loops in Shell Scripts http://www.cyberciti.biz/pdf/lsst/ch03sec05.html [7/29/2002 6:52:23 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 3: Shells (bash) structured Language Constructs Next for Loop Syntax: for { variable name } in { list } do execute one for each item in the list until the list is not finished (And repeat all statement between do and done) done Before try to understand above syntax try the following script: $ cat > testfor for i in 1 2 3 4 5 do echo "Welcome $i times" done Run it above script as follows: $ chmod +x testfor $ ./testfor The for loop first creates i variable and assigned a number to i from the list of number from 1 to 5, The shell execute echo statement for each assignment of i. (This is usually know as iteration) This process will continue until all the items in the list were not finished, because of this it will repeat 5 echo statements. To make you idea more clear try following script: $ cat > mtable #!/bin/sh # #Script to test for loop # # if [ $# -eq 0 ] then echo "Error - Number missing form command line argument" echo "Syntax : $0 number" echo "Use to print multiplication table for given number" exit 1 fi n=$1 for i in 1 2 3 4 5 6 7 8 9 10 do echo "$n * $i = `expr $i \* $n`" done Save above script and run it as: $ chmod 755 mtable $ ./mtable 7 $ ./mtable For first run, above script print multiplication table of given number where i = 1,2 ... 10 is multiply by given n (here LSST v1.05r3 > Chapter 3 > for Loop http://www.cyberciti.biz/pdf/lsst/ch03sec06.html (1 of 5) [7/29/2002 6:52:26 PM] command line argument 7) in order to produce multiplication table as 7 * 1 = 7 7 * 2 = 14 ... .. 7 * 10 = 70 And for second test run, it will print message - Error - Number missing form command line argument Syntax : ./mtable number Use to print multiplication table for given number This happened because we have not supplied given number for which we want multiplication table, Hence script is showing Error message, Syntax and usage of our script. This is good idea if our program takes some argument, let the user know what is use of the script and how to used the script. 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: Syntax: for (( expr1; expr2; expr3 )) do ..... ... repeat all statements between do and done until expr2 is TRUE Done In above syntax BEFORE the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop. All the statements between do and done is executed repeatedly UNTIL the value of expr2 is TRUE. AFTER each iteration of the loop, expr3 is evaluated. This is usually use to increment a loop counter. $ cat > for2 for (( i = 0 ; i <= 5; i++ )) do echo "Welcome $i times" done Run the above script as follows: $ chmod +x for2 $ ./for2 Welcome 0 times Welcome 1 times Welcome 2 times Welcome 3 times Welcome 4 times Welcome 5 times In above example, first expression (i = 0), is used to set the value variable i to zero. Second expression is condition i.e. all statements between do and done executed as long as expression 2 (i.e continue as long as the value of variable i is less than or equel to 5) is TRUE. Last expression i++ increments the value of i by 1 i.e. it's equivalent to i = i + 1 statement. LSST v1.05r3 > Chapter 3 > for Loop http://www.cyberciti.biz/pdf/lsst/ch03sec06.html (2 of 5) [7/29/2002 6:52:26 PM] Prev Home Next Loops in Shell Scripts Up while loop LSST v1.05r3 > Chapter 3 > for Loop http://www.cyberciti.biz/pdf/lsst/ch03sec06.html (5 of 5) [7/29/2002 6:52:26 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 3: Shells (bash) structured Language Constructs Next while loop Syntax: while [ condition ] do command1 command2 command3 .. .... done Loop is executed as long as given condition is true. For e.g.. Above for loop program (shown in last section of for loop) can be written using while loop as: $cat > nt1 #!/bin/sh # #Script to test while statement # # if [ $# -eq 0 ] then echo "Error - Number missing form command line argument" echo "Syntax : $0 number" echo " Use to print multiplication table for given number" exit 1 fi n=$1 i=1 while [ $i -le 10 ] do echo "$n * $i = `expr $i \* $n`" i=`expr $i + 1` done Save it and try as $ chmod 755 nt1 $./nt1 7 Above loop can be explained as follows: LSST v1.05r3 > Chapter 3 > The case Statement http://www.cyberciti.biz/pdf/lsst/ch03sec07.html (1 of 2) [7/29/2002 6:52:28 PM] n=$1 Set the value of command line argument to variable n. (Here it's set to 7 ) i=1 Set variable i to 1 while [ $i -le 10 ] This is our loop condition, here if value of i is less than 10 then, shell execute all statements between do and done do Start loop echo "$n * $i = `expr $i \* $n`" Print multiplication table as 7 * 1 = 7 7 * 2 = 14 .... 7 * 10 = 70, Here each time value of variable n is multiply be i. i=`expr $i + 1` Increment i by 1 and store result to i. ( i.e. i=i+1) Caution: If you ignore (remove) this statement than our loop become infinite loop because value of variable i always remain less than 10 and program will only output 7 * 1 = 7 ... ... E (infinite times) done Loop stops here if i is not less than 10 i.e. condition of loop is not true. Hence loop is terminated. Prev Home Next for loop Up The case Statement LSST v1.05r3 > Chapter 3 > The case Statement http://www.cyberciti.biz/pdf/lsst/ch03sec07.html (2 of 2) [7/29/2002 6:52:28 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 3: 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 - debug). For this purpose you can use -v and -x option with sh or bash command to debug the shell script. General syntax is as follows: Syntax: sh option { shell-script-name } OR bash option { shell-script-name } Option can be -v Print shell input lines as they are read. -x After expanding each simple-command, bash displays the expanded value of PS4 system variable, followed by the command and its expanded arguments. Example: $ cat > dsh1.sh # # Script to show debug of shell # tot=`expr $1 + $2` echo $tot Press ctrl + d to save, and run it as $ chmod 755 dsh1.sh $ ./dsh1.sh 4 5 9 $ sh -x dsh1.sh 4 5 # # Script to show debug of shell # tot=`expr $1 + $2` expr $1 + $2 ++ expr 4 + 5 + tot=9 echo $tot + echo 9 9 See the above output, -x shows the exact values of variables (or statements are shown on screen with values). LSST v1.05r3 > Chapter 3 > How to de-bug the shell script? http://www.cyberciti.biz/pdf/lsst/ch03sec09.html (1 of 2) [7/29/2002 6:52:33 PM] $ sh -v dsh1.sh 4 5 Use -v option to debug complex shell script. Prev Home Next The case Statement Up Advanced Shell Scripting LSST v1.05r3 > Chapter 3 > How to de-bug the shell script? http://www.cyberciti.biz/pdf/lsst/ch03sec09.html (2 of 2) [7/29/2002 6:52:33 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 4: Advanced Shell Scripting Commands Next Introduction After learning basis of shell scripting, its time to learn more advance features of shell scripting/command such as: Functions● User interface● Conditional execution● File Descriptors● traps● Multiple command line args handling etc● Prev Home Next How to de-bug the shell script? Up /dev/null - to send unwanted output of program LSST v1.05r3 > Chapter 4 > Introduction http://www.cyberciti.biz/pdf/lsst/ch04.html [7/29/2002 6:52:35 PM] Examples: $ vech=Bus $ echo $vech Bus $ export vech $ /bin/bash $ echo $vech Bus $ exit $ echo $vech Bus Command Meaning $ vech=Bus Create new local variable 'vech' with Bus as value in first shell $ echo $vech Print the contains of variable vech $ export vech Export first shells variable to second shell i.e. global varible $ /bin/bash Now load second shell in memory (Old shell's variable is accessed from second shell, if they are exported ) $ echo $vech Print the contains of variable vech $ exit Exit from second shell return to first shell $ echo $vech Print the contains of variable vech Prev Home Next /dev/null - to send unwanted output of program Up Conditional execution i.e. && and || LSST v1.05r3 > Chapter 4 > Local and Global Shell variable (export comman http://www.cyberciti.biz/pdf/lsst/ch04sec2.html (2 of 2) [7/29/2002 6:52:41 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 4: Advanced Shell Scripting Commands Next Conditional execution i.e. && and || The control operators are && (read as AND) and || (read as OR). The syntax for AND list is as follows Syntax: command1 && command2 command2 is executed if, and only if, command1 returns an exit status of zero. The syntax for OR list as follows Syntax: command1 || command2 command2 is executed if and only if command1 returns a non-zero exit status. You can use both as follows Syntax: command1 && comamnd2 if exist status is zero || command3 if exit status is non-zero if command1 is executed successfully then shell will run command2 and if command1 is not successful then command3 is executed. Example: $ rm myf && echo "File is removed successfully" || echo "File is not removed" If file (myf) is removed successful (exist status is zero) then "echo File is removed successfully" statement is executed, otherwise "echo File is not removed" statement is executed (since exist status is non-zero) Prev Home Next Local and Global Shell variable (export command) Up I/O Redirection and file descriptors LSST v1.05r3 > Chapter 4 > Conditional execution i.e. && and || http://www.cyberciti.biz/pdf/lsst/ch04sec3.html [7/29/2002 6:52:44 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 4: Advanced Shell Scripting Commands Next I/O Redirection and file descriptors As you know I/O redirectors are used to send output of command to file or to read input from file. Consider following example $ cat > myf This is my file ^D (press CTRL + D to save file) Above command send output of cat command to myf file $ cal Above command prints calendar on screen, but if you wish to store this calendar to file then give command $ cal > mycal The cal command send output to mycal file. This is called output redirection. $ sort 10 -20 11 2 ^D -20 2 10 11 sort command takes input from keyboard and then sorts the number and prints (send) output to screen itself. If you wish to take input from file (for sort command) give command as follows: $ cat > nos 10 -20 11 2 ^D $ sort < nos -20 2 10 11 First you created the file nos using cat command, then nos file given as input to sort command which prints sorted numbers. This is called input redirection. In Linux (And in C programming Language) your keyboard, screen etc are all treated as files. Following are name of such files LSST v1.05r3 > Chapter 4 > I/O Redirection and file descriptors http://www.cyberciti.biz/pdf/lsst/ch04sec4.html (1 of 3) [7/29/2002 6:52:45 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 4: Advanced Shell Scripting Commands Next Functions Humans are intelligent animals. They work together to perform all of life's task, in fact most of us depend upon each other. For e.g. you rely on milkman to supply milk, or teacher to learn new technology (if computer teacher). What all this mean is you can't perform all of life's task alone. You need somebody to help you to solve specific task/problem. The above logic also applies to computer program (shell script). When program gets complex we need to use divide and conquer technique. It means whenever programs gets complicated, we divide it into small chunks/entities which are known as functions. Function is series of instruction/commands. Function performs particular activity in shell i.e. it had specific work to do or simply say task. To define function use following syntax: Syntax: function-name ( ) { command1 command2 ..... ... commandN return } Where function-name is name of you function, that executes series of commands. A return statement will terminate the function. Example: Type SayHello() at $ prompt as follows $ SayHello() { echo "Hello $LOGNAME, Have nice computing" return } To execute this SayHello() function just type it name as follows: $ SayHello Hello vivek, Have nice computing. This way you can call function. Note that after restarting your computer you will loss this SayHello() function, since its created for current session only. To overcome this problem and to add you own function to automate some of the day today life task, add your function to /etc/bashrc file. To add function to this file you must logon as root. Following is the sample /etc/bashrc file with today() function , which is used to print formatted date. First logon as root or if you already logon with your name (your login is not root), and want to move to root account, then you can type following command , when asked LSST v1.05r3 > Chapter 4 > Functions http://www.cyberciti.biz/pdf/lsst/ch04sec5.html (1 of 4) [7/29/2002 6:52:46 PM] for password type root (administrators) password $ su -l password: Open file /etc/bashrc using vi and goto the end of file (by pressing shift+G) and type the today() function: # vi /etc/bashrc # At the end of file add following in /etc/bashrc file # # today() to print formatted date # # To run this function type today at the $ prompt # Added by Vivek to show function in Linux # today() { echo This is a `date +"%A %d in %B of %Y (%r)"` return } Save the file and exit it, after all this modification your file may look like as follows (type command cat /etc/bashrc) # cat /etc/bashrc # /etc/bashrc # System wide functions and aliases # Environment stuff goes in /etc/profile # For some unknown reason bash refuses to inherit # PS1 in some circumstances that I can't figure out. # Putting PS1 here ensures that it gets loaded every time. PS1="[\u@\h \W]\\$ " # # today() to print formatted date # # To run this function type today at the $ prompt # Added by Vivek to show function in Linux today() { echo This is a `date +"%A %d in %B of %Y (%r)"` return } To run function first completely logout by typing exit at the $ prompt (Or press CTRL + D, Note you may have to type exit (CTRL +D) twice if you login to root account by using su command) ,then login and type $ today , this way today() is available to all user in your system, If you want to add particular LSST v1.05r3 > Chapter 4 > Functions http://www.cyberciti.biz/pdf/lsst/ch04sec5.html (2 of 4) [7/29/2002 6:52:46 PM] function to particular user then open .bashrc file in users home directory as follows: # vi .bashrc OR # mcedit .bashrc At the end of file add following in .bashrc file SayBuy() { echo "Buy $LOGNAME ! Life never be the same, until you login again!" echo "Press a key to logout. . ." read return } Save the file and exit it, after all this modification your file may look like as follows (type command cat .bashrc) # cat .bashrc # .bashrc # # User specific aliases and functions # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc fi SayBuy() { echo "Buy $LOGNAME ! Life never be the same, until you login again!" echo "Press a key to logout. . ." read return } To run function first logout by typing exit at the $ prompt (Or press CTRL + D ) ,then logon and type $ SayBuy , this way SayBuy() is available to only in your login and not to all user in system, Use .bashrc file in your home directory to add User specific aliases and functions only. Tip: If you want to show some message or want to perform some action when you logout, Open file .bash_logout in your home directory and add your stuff here For e.g. When ever I logout, I want to show message Buy! Then open your .bash_logout file using text editor such as vi and add statement: echo "Buy $LOGNAME, Press a key. . ." read Save and exit from the file. Then to test this logout from your system by pressing CTRL + D (or type exit) immediately you will see message "Buy xxxxx, Press a key. . .", after pressing key you will be logout and login prompt will be shown to you. :-) LSST v1.05r3 > Chapter 4 > Functions http://www.cyberciti.biz/pdf/lsst/ch04sec5.html (3 of 4) [7/29/2002 6:52:46 PM] $ cat > menuui # # Script to create simple menus and take action according to that selected # menu item # while : do clear echo "-------------------------------------" echo " Main Menu " echo "-------------------------------------" echo "[1] Show Todays date/time" echo "[2] Show files in current directory" echo "[3] Show calendar" echo "[4] Start editor to write letters" echo "[5] Exit/Stop" echo "=======================" echo -n "Enter your menu choice [1-5]: " read yourch case $yourch in 1) echo "Today is `date` , press a key. . ." ; read ;; 2) echo "Files in `pwd`" ; ls -l ; echo "Press a key. . ." ; read ;; 3) cal ; echo "Press a key. . ." ; read ;; 4) vi ;; 5) exit 0 ;; *) echo "Opps!!! Please select choice 1,2,3,4, or 5"; echo "Press a key. . ." ; read ;; esac done Above all statement explained in following table: Statement Explanation while : Start infinite loop, this loop will only break if you select 5 ( i.e. Exit/Stop menu item) as your menu choice do Start loop clear Clear the screen, each and every time LSST v1.05r3 > Chapter 4 > User Interface and dialog utility-Part I http://www.cyberciti.biz/pdf/lsst/ch04sec6.html (2 of 3) [7/29/2002 6:52:47 PM] echo "-------------------------------------" echo " Main Menu " echo "-------------------------------------" echo "[1] Show Todays date/time" echo "[2] Show files in current directory" echo "[3] Show calendar" echo "[4] Start editor to write letters" echo "[5] Exit/Stop" echo "=======================" Show menu on screen with menu items echo -n "Enter your menu choice [1-5]: " Ask user to enter menu item number read yourch Read menu item number from user case $yourch in 1) echo "Today is `date` , press a key. . ." ; read ;; 2) echo "Files in `pwd`" ; ls -l ; echo "Press a key. . ." ; read ;; 3) cal ; echo "Press a key. . ." ; read ;; 4) vi ;; 5) exit 0 ;; *) echo "Opps!!! Please select choice 1,2,3,4, or 5"; echo "Press a key. . ." ; read ;; esac Take appropriate action according to selected menu item, If menu item is not between 1 - 5, then show error and ask user to input number between 1-5 again done Stop loop , if menu item number is 5 ( i.e. Exit/Stop) User interface usually includes, menus, different type of boxes like info box, message box, Input box etc. In Linux shell (i.e. bash) there is no built-in facility available to create such user interface, But there is one utility supplied with Red Hat Linux version 6.0 called dialog, which is used to create different type of boxes like info box, message box, menu box, Input box etc. Next section shows you how to use dialog utility. Prev Home Next Functions Up User Interface and dialog utility-Part II LSST v1.05r3 > Chapter 4 > User Interface and dialog utility-Part I http://www.cyberciti.biz/pdf/lsst/ch04sec6.html (3 of 3) [7/29/2002 6:52:47 PM] Linux Shell Scripting Tutorial (LSST) v1.05r3 Prev Chapter 4: Advanced Shell Scripting Commands Next User Interface and dialog utility-Part II Before programming using dialog utility you need to install the dialog utility, since dialog utility in not installed by default. For Red Hat Linux 6.2 user install the dialog utility as follows (First insert Red Hat Linux 6.2 CD into CDROM drive) # mount /mnt/cdrom # cd /mnt/cdrom/RedHat/RPMS # rpm -ivh dialog-0.6-16.i386.rpm For Red Hat Linux 7.2 user install the dialog utility as follows (First insert Red Hat Linux 7.2 # 1 CD into CDROM drive) # mount /mnt/cdrom # cd /mnt/cdrom/RedHat/RPMS # rpm -ivh dialog-0.9a-5.i386.rpm After installation you can start to use dialog utility. Before understanding the syntax of dialog utility try the following script: $ cat > dia1 dialog --title "Linux Dialog Utility Infobox" --backtitle "Linux Shell Script\ Tutorial" --infobox "This is dialog box called infobox, which is used \ to show some information on screen, Thanks to Savio Lam and\ Stuart Herbert to give us this utility. Press any key. . . " 7 50 ; read Save the shell script and run it as: $ chmod +x dia1 $ ./dia1 LSST v1.05r3 > Chapter 4 > User Interface and dialog utility-Part II http://www.cyberciti.biz/pdf/lsst/ch04sec7.html (1 of 2) [7/29/2002 6:52:49 PM]
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved