Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 14: Writing Shell Scripts

Similar presentations


Presentation on theme: "Chapter 14: Writing Shell Scripts"— Presentation transcript:

1 Chapter 14: Writing Shell Scripts
The Complete Guide to Linux System Administration

2 Objectives Understand how shell scripts operate
Collect user input and write to the screen from within a script Control command execution using tests and loops Debug shell scripts The Complete Guide to Linux System Administration

3 Scripting Basics Shell script Executable file
Contains lines of text as would be entered at command line Executed like any other program Used on every Linux system The Complete Guide to Linux System Administration

4 Scripting Basics (continued)
Shell script advantages Can study what is happening on Linux system by viewing contents of scripts that control various system events Can change way anything on system occurs simply by altering relevant shell script The Complete Guide to Linux System Administration

5 Interpreting and Compiling Programs
Two basic types of computer programs: Interpreted programs Compiled programs Computer language Programming language Set of words and syntax rules Can be arranged in predefined ways to cause computer to perform tasks The Complete Guide to Linux System Administration

6 Interpreting and Compiling Programs (continued)
Keywords Words used in computer language Source code Human readable computer program written by programmer Binary file Executable file Source code converted to numeric code that computer’s CPU can process The Complete Guide to Linux System Administration

7 Interpreting and Compiling Programs (continued)
Compiled language Source code converted to binary file before program run by users Interpreted language Source code converted into numeric codes at instant user runs program Shell script Interpreted program The Complete Guide to Linux System Administration

8 Understanding Programming Concepts
Computer program executed one command at a time Statement Command within program Programs define list of statements that are executed once, many times, or not at all depending on what happens at some other point in program The Complete Guide to Linux System Administration

9 Understanding Programming Concepts (continued)
Statement block Group of statements Nesting One statement block contains another statement block The Complete Guide to Linux System Administration

10 Components of a Shell Script
Three basic rules: First line must indicate name of shell used to interpret script #!/bin/bash File must have execute file permission set File must contain valid commands that interpreter can recognize The Complete Guide to Linux System Administration

11 Components of a Shell Script (continued)
echo command Prints text to STDOUT channel Example: echo hello world Test new script ./testscript a period and a forward slash ( ./ ) before the file name to tell the shell that the file is located in the current directory rather than in a directory that is part of the PATH environment variable The Complete Guide to Linux System Administration

12 Components of a Shell Script (continued)
Exit code Numeric code returned by program on exit Variable $? used to reference code at command line or in script Value of 0 indicates no problems Nonzero value usually indicates some type of problem or error The Complete Guide to Linux System Administration

13 EXAMPLE suppose you are working at the command line and successfully create a new directory called data_dir using the command mkdir data_dir. The exit code would be zero, though you don't see that code anywhere. If you then execute the same command again, mkdir data_dir, that command returns a nonzero exit code-an error occurred because the directory you tried to create already existed. Again, you do not see the exit code, but it is passed to the shell. The Complete Guide to Linux System Administration

14 example The Complete Guide to Linux System Administration
File named clean #!/bin/bash # # Author, dave lambert, .org # Date, October 2005 # Description: Collect info on core dump files # and create file with directory sizes find /home -name core -exec rm { } \; du /home >/tmp/home_sizes The purpose of the second line of this script is to locate and remove all files named core within all users' home directories. In the third line, the du command creates a summary of the size of every subdirectory under /home, storing that information in a file named home_sizes To execute . /clean. The Complete Guide to Linux System Administration

15 Input and Output read command
Causes shell to pause for user to enter information at keyboard Entered information assigned to variable provided with read command read THEFILE Define variable by assigning value to name MyFile="index.html" The Complete Guide to Linux System Administration

16 Example The Complete Guide to Linux System Administration
The following script, called filesize #! /bin/bash # # Author, dave lambert, # Date, 12 October 2005 # Description : Read filename with READ; # process file size information with wc echo Enter a filename to process: read THEFILE echo The number of lines in $THEFILE is: wc -l $THEFILE echo The number of words in $THEFILE is: wc -w $THEFILE echo End of processing for $THEFILE The Complete Guide to Linux System Administration

17 echo $ echo “enter your name “;name enter your name ghadeer
$ echo name In this case name entered in a new line While in the following case $ echo –n “enter your name “;name enter your name ghadeer In this case name entered in a same line The Complete Guide to Linux System Administration

18 Read command Options Example read –s (does not echo input)
read –nN (accepts only N characters of input) read –p “message” (prompts message) read –tT (accepts input for T seconds) Example $ read –s –n1 -p “Yes (Y) or not (N)?” answer Yes (Y) or not (N) ? Y $ echo $answer Y

19 Read command The read command allows you to prompt for input and store it in a variable. Example (read.sh) #!/bin/bash echo -n “Enter name of file to delete: ” read file echo “Type 'y' to remove it, 'n' to change your mind ... ” rm -i $file echo "That was YOUR decision!" Line 3 creates a variable called file and assigns the input from keyboard to it. Then the value of this variable is retrieved by putting the '$' in at its beginning.

20 Variables We can use variables as in any programming languages. Their values are always stored as strings, but there are mathematical operators in the shell language that will convert variables to numbers for calculations. We have no need to declare a variable, just assigning a value to its reference will create it. Example #!/bin/bash STR=“Hello World!” echo $STR Line 2 creates a variable called STR and assigns the string "Hello World!" to it. Then the value of this variable is retrieved by putting the '$' in at the beginning.

21 Single and Double Quote
When assigning character data containing spaces or special characters, the data must be enclosed in either single or double quotes. Using double quotes (partial quoting) to show a string of characters will allow any variables in the quotes to be resolved $ var=“test string” $ newvar=“Value of var is $var” $ echo $newvar Value of var is test string Using single quotes (full quoting) to show a string of characters will not allow variable resolution $ var=’test string’ $ newvar=’Value of var is $var’ Value of var is $var

22 Using Variables in Scripts
Shell variable Variable used in shell script Initialize variable Assign initial value Positional variable Takes value based on information user includes on command line Indicate using dollar sign and number $0 first variable on command line The Complete Guide to Linux System Administration

23 Using Variables in Scripts (continued)
Contains number of items on command line used to execute script The Complete Guide to Linux System Administration

24 The Complete Guide to Linux System Administration
#!/bin/bash # # Author:dave lambert, # Date:12 October 2005 # Description: Read filename from command line; # process file size information with we echo The number of lines in $1 is: wc -l $1 echo The number of words in $1 is: wc –w $1 echo End of processing for $1 ./filesize report.txt Within a script, you indicate positional variables using a dollar sign and a number. The notation $0 indicates the first item on the command line (the script name: ./filesize in the example above). A $1 indicates the second item on the command line (report. txt in the example above). A $2 indicates the third item on the command line, and so forth. The Complete Guide to Linux System Administration

25 The Complete Guide to Linux System Administration
#!/bin/bash # Author: dave lambert, # Date: 12 October 2005 # Description: Read multiple filenames from command line; # process each with we # echo The script you are running is $0 echo The number of filenames you provided #$ echo The number of lines in file $1 is: wc -l $1 echo The number of lines in file $2 is: wc -l $2 echo The number of lines in file $3 is: wc -l $3 echo The number of lines in file $4 is: wc -l $4 Suppose you ran the script above with this command: ./filesize datal data2 data3 data4 The Complete Guide to Linux System Administration

26 The script you are running is filesize
Each time you execute a script, the shell defines a special variable called $# that contains the number of items on the command line used to execute the script. The script you are running is filesize The number of filenames you provided is 4 The number of lines in file datal is: 123 The number of lines in file data2 is: 11241 The number of lines in file data3 is: 2321 The number of lines in file data4 is : 3159 The Complete Guide to Linux System Administration

27 Command Substitution The backquote “`” is different from the single quote “´”. It is used for command substitution: `command` $ LIST=`ls` $ echo $LIST hello.sh read.sh PS1=“`pwd`>” /home/rinaldi/didattica/> We can perform the command substitution by means of $(command) $ LIST=$(ls) rm $( find / -name “*.tmp” ) ls $( pwd ) ls $( echo /bin )

28 Arithmetic Operators + plus - minus * multiplication / division
** exponentiation % modulo Example $ a=(5+2)*3 $ echo $a $ b=2*3 $ echo $a+$b

29 Operations on vabiables
……. let “index += 5” #increment index by 5 …… += #increment variable -= # decrement variable *= # multiply variable /= # divide variable

30 Arithmetic Evaluation
The let statement can be used to do mathematical functions: $ let X=10+2*7 $ echo $X 24 $ let Y=X+2*4 $ echo $Y 32 An arithmetic expression can be evaluated by $[expression] or $((expression)) echo $((123+20)) 143 VALORE=$[123+20] echo $[123*$VALORE] 17589 $ echo $[2*3] $ echo $[8%3] Not necessary to use $X to refer to the value of X

31 Arithmetic Evaluation
Example (operations.sh) #!/bin/bash echo -n “Enter the first number: ”; read x echo -n “Enter the second number: ”; read y add=$(($x + $y)) sub=$(($x - $y)) mul=$(($x * $y)) div=$(($x / $y)) mod=$(($x % $y)) # print out the answers: echo “Sum: $add” echo “Difference: $sub” echo “Product: $mul” echo “Quotient: $div” echo “Remainder: $mod”

32 Manipulating Strings $ echo ${#st}
Bash supports a surprising number of string manipulation operations. Unfortunately, these tools lack a unified focus. ${#string} gives the string length ${string:position} extracts sub-string from $string at $position ${string:position:length} Extracts $length characters of sub-string from $string at $position Example $ st= $ echo ${#st} 10 $ echo ${st:6} 6789 $ echo ${st:6:2} 67

33 Advanced operations on strings
${string/substring/replacement},strips the first match of substring in string with replacement. pippo=abbcaabccbcabcdbcdabab echo ${pippo/ca/11} # abb11abccbcabcdbcdabab #replace the first match echo ${pippo//ca/11} # abb11abccb11bcdbcdabab # replaces all matches

34 Conditional and Looping Structures
Selection statement Determine which parts of program will execute according to values determined as program executes All lines in shell script not necessarily executed when script is run Most shell scripts include selection statements The Complete Guide to Linux System Administration

35 Conditional and Looping Structures (continued)
The Complete Guide to Linux System Administration

36 Conditional and Looping Structures (continued)
Selection statement Tests performed in shell scripts only have two possible outcomes: True False test command creates type of selection statement to determine if condition true or false The Complete Guide to Linux System Administration

37 Using if Statements if command followed by then command fi command
Lists commands to be executed if test succeeds fi command Marks end of if statement Test succeeds All commands between then and fi executed Test fails No commands executed The Complete Guide to Linux System Administration

38 Using if Statements (continued)
test command Evaluates parameters provided Returns either: True, value of 1 False, value of 0 if-then-else statement If test returns value of true One set of commands executed If test returns value of false Another set of commands executed The Complete Guide to Linux System Administration

39 Using if Statements (continued)
The Complete Guide to Linux System Administration

40 The Complete Guide to Linux System Administration

41 Expressions An expression can be: String comparison, Numeric comparison, File operators and Logical operators and it is represented by [expression]: String Comparisons: = compare if two strings are equal != compare if two strings are not equal -n evaluate if string length is greater than zero -z evaluate if string length is equal to zero Examples: [ s1 = s2 ] (true if s1 same as s2, else false) [ s1 != s2 ] (true if s1 not same as s2, else false) [ s1 ] (true if s1 is not empty, else false) [ -n s1 ] (true if s1 has a length greater then 0, else false) [ -z s2 ] (true if s2 has a length of 0, otherwise false)

42 Expressions Number Comparisons: Examples:
-eq compare if two numbers are equal -ge compare if one number is greater than or equal to a number -le compare if one number is less than or equal to a number -ne compare if two numbers are not equal -gt compare if one number is greater than another number -lt compare if one number is less than another number Examples: [ n1 -eq n2 ] (true if n1 same as n2, else false) [ n1 -ge n2 ] (true if n1greater then or equal to n2, else false) [ n1 -le n2 ] (true if n1 less then or equal to n2, else false) [ n1 -ne n2 ] (true if n1 is not same as n2, else false) [ n1 -gt n2 ] (true if n1 greater then n2, else false) [ n1 -lt n2 ] (true if n1 less then n2, else false)

43 Expressions Files operators: Examples:
-d check if path given is a directory -f check if path given is a file -s check if path given is a symbolic link -e check if file name exists -s check if a file has a length greater than 0 -r check if read permission is set for file or directory -w check if write permission is set for a file or directory -x check if execute permission is set for a file or directory Examples: [ -d fname ] (true if fname is a directory, otherwise false) [ -f fname ] (true if fname is a file, otherwise false) [ -e fname ] (true if fname exists, otherwise false) [ -s fname ] (true if fname length is greater then 0, else false) [ -r fname ] (true if fname has the read permission, else false) [ -w fname ] (true if fname has the write permission, else false) [ -x fname ] (true if fname has the execute permission, else false)

44 example if [ $1 -eq report ];
The Complete Guide to Linux System Administration

45 Using if Statements (continued)
The Complete Guide to Linux System Administration

46 if [ -f /etc/samba/smb.conf ]; then
echo The Samba server appears to be configured. else echo The Samba server cannot be started. fi The Complete Guide to Linux System Administration

47 Using if Statements (continued)
else command Adds block of commands Only executed if test returns value of false exit command Stops execution of script immediately Returns exit code provided Avoid using exit within loop The Complete Guide to Linux System Administration

48 Using if Statements (continued)
Comment Line within script not processed by shell Helps reader understand purpose of script Begins with hash mark # elif keyword Used in place of else when using if-then-else When first command in else block another if-then-else statement The Complete Guide to Linux System Administration

49 #!/bin/bash # # Author, dave lambert, # Date, 12 October 2005 # Description: Add a user for database access # Requires a user name and database table name on the # command line if [ $# -ne 2 ]; then echo You must provide a user name and a database table name . exit fi # Begin processing : # Store command line parameters in shell variables DB_USER=$l DB_TABLE=$2 The Complete Guide to Linux System Administration

50 Expressions #!/bin/bash # if0.sh echo -n “Enter your login name: "
read name if [ “$name” = “$USER” ]; then echo “Hello, $name. How are you today ?” else echo “You are not $USER, so who are you ?” fi #!/bin/bash # if1.sh echo -n “Enter a number 1 < x < 10: " read num if [ “$num” -lt 10 ]; then if [ “$num” -gt 1 ]; then echo “$num*$num=$(($num*$num))” echo “Wrong insertion !”

51 Example #!/bin/bash if [ -f /etc/fstab ]; then cp /etc/fstab .
echo “Done.” else echo “This file does not exist.” exit 1 fi

52 Expressions Logical operators: ! negate (NOT) a logical expression
-a logically AND two logical expressions -o logically OR two logical expressions #!/bin/bash # if3.sh echo -n “Enter a number 1 < x < 10:” read num if [ “$num” -gt 1 –a “$num” -lt 10 ]; then echo “$num*$num=$(($num*$num))” else echo “Wrong insertion !” fi

53 Expressions Logical operators:
&& logically AND two logical expressions || logically OR two logical expressions #!/bin/bash # if4.sh echo -n "Enter a number 1 < x < 10: " read num if [ “$number” -gt 1 ] && [ “$number” -lt 10 ]; then echo “$num*$num=$(($num*$num))” else echo “Wrong insertion !” fi

54 If-elif-fi The Complete Guide to Linux System Administration
you often need to determine the value of a variable or file name that may have anyone of several values. You could use multiple if then-else statements to check for different values, as shown here. When you are using an if then -else statement and the first command in the else block is another if then-else statement, you can use the elif keyword instead of else, as shown here : if [ $# = 4] ; then Echo “Ready to process four files . “ elif [ $# = 3] ; then Echo “Ready to process three files. “ elif [ $# = 2 ] ; then echo ” Ready to process two files " elif [ $# = 1 ] ; then echo "Ready to process one file , " else echo "No filenames to process. " fi The Complete Guide to Linux System Administration

55 Using if Statements (continued)
case statement Specify number of possible values for variable Statement block executed for matching value Only one block executed The Complete Guide to Linux System Administration

56 Case Statement Used to execute statements based on specific values. Often used in place of an if statement if there are a large number of conditions. Value used can be an expression each set of statements must be ended by a pair of semicolons; a *) is used to accept any value not matched with list of values case $var in val1) statements;; val2) *) esac

57 echo “Ready to process four files. “ ;; 3)
case $# in 4) echo “Ready to process four files. “ ;; 3) echo “Ready to process three files.” ;; 2) echo “Ready to process two files.” ;; 1) echo “ Ready to process one file.” ;; *) echo “Invalid number of filenames provided, “ ;; esac In the above example, the statement block following the *) case is executed if the $# variable does not match any of the previous cases (4,3,2, or 1). A double semicolon indicates the end of the statement block for each case. The esac keyword ("case" spelled backward) is used to indicate the end of the case statement. After one of the statement blocks in the case statement is executed (such as echo (“Ready to process four files. "), the next statement executed is the line after the esac keyword. The Complete Guide to Linux System Administration

58 Example #!/bin/bash ( case.sh )
echo -n “Enter a number 1 < x < 10: ” read x case $x in 1) echo “Value of x is 1.”;; 2) echo “Value of x is 2.”;; 3) echo “Value of x is 3.”;; 4) echo “Value of x is 4.”;; 5) echo “Value of x is 5.”;; 6) echo “Value of x is 6.”;; 7) echo “Value of x is 7.”;; 8) echo “Value of x is 8.”;; 9) echo “Value of x is 9.”;; 0 | 10) echo “wrong number.”;; *) echo “Unrecognized value.”;; esac

59 Adding Loops to a Script
for loop Repeats statement block once for each item in list Syntax: for <counting variable> in <list of items> do <statement block> done The Complete Guide to Linux System Administration

60 Adding Loops to a Script
Loop statement Used to determine whether statement block executed more than once Parts: Counting variable List of values • Numbers: for COUNT in • Words: for NAME in george ali maria rupert kim • A regular expression used to match file names: for db_filename in *html • The special variable : for db_filename in List of statements The Complete Guide to Linux System Administration

61 Adding Loops to a Script (continued)
Iteration Each time through loop variable Contains all parameters included on command line when script executed Used as <list of items> in for loop The Complete Guide to Linux System Administration

62 Adding Loops to a Script (continued)
in a for loop, the shell replaces the regular expression with all matching file names. Using the example of *html, the shell substitutes all the file names in the current directory that end with the letters "html." This substitution occurs before the shell executes the for loop. A special variable used in for loops is This variable contains all the parameters that were included on the command line when the script was executed. If you include a regular expression on the command line, such as "txt or "html, the shell finds all matching file names and includes them as part of when the script is executed. By using as the <list of items> in a for loop, you automatically include all items from the command line. The Complete Guide to Linux System Administration

63 Iteration Statements The for structure is used when you are looping through a range of variables. for var in list do statements done statements are executed with var set to each value in the list. #!/bin/bash let sum=0 for num in let “sum = $sum + $num” echo $sum

64 Iteration Statements: <list>
#!/bin/bash lista=“antonio michele paolo luca” for x in $lista do echo “The value of variable x is: $x” sleep 1 done # The value of variable x is antonio # The value of variable x is michele # The value of variable x is paolo # The value of variable x is luca

65 Iteration Statements: <list>
#!/bin/bash for x in * do ls -l “$x” sleep 1 done # Lists all files in current directory for x in /bin # Lists all files in /bin

66 Using Arrays with Loops
In the bash shell, we may use arrays. The simplest way to create one is using one of the two subscripts: pet[0]=dog pet[1]=cat pet[2]=fish pet[4]=apple pet=( dog cat fish apple ) We may have up to 1024 elements. To extract a value, type ${arrayname[i]} $ echo ${pet[0]} dog $ echo ${pet[2]} fish

67 Arrays To extract all the elements, use an asterisk as:
echo ${arraynames[*]} To see how many elements are in the array: echo ${#arraynames[*]} We can combine arrays with loops using a for loop: for x in ${arrayname[*]} do echo ${arrayname[$x]} done

68 A C-like for loop An alternative form of the for structure is
for (( EXPR1 ; EXPR2 ; EXPR3 )) do statements done First, the arithmetic expression EXPR1 is evaluated. EXPR2 is then evaluated repeatedly until it evaluates to 0. Each time EXPR2 is evaluates to a non-zero value, statements are executed and EXPR3 is evaluated. $ cat for2.sh #!/bin/bash echo –n “Enter a number: ”; read x let sum=0 for (( i=1 ; $i<$x ; i=$i+1 )) ; do let “sum = $sum + $i” echo “the sum of the first $x numbers is: $sum”

69 Example vi squash #!/bin/bash # Author: dave lambert, dave@xyz.org
# Date:12 October 2005 # Description: Compress each filename given on the command line # for counter in do gzip $counter done ./squash phoebe.tif charon.tif europa.tif The Complete Guide to Linux System Administration

70 Adding Loops to a Script (continued)
while loop Uses test like if-then statement As long as test returns value of true, statement block within loop executed As soon as test returns value of false, loop exits while loop syntax: while <test> do <statement block> done The Complete Guide to Linux System Administration

71 While Statements The while structure is a looping structure. Used to execute a set of commands while a specified condition is true. The loop terminates as soon as the condition becomes false. If condition never becomes false, loop will never exit. while expression do statements done $ cat while.sh ( while.sh ) #!/bin/bash echo –n “Enter a number: ”; read x let sum=0; let i=1 while [ $i –le $x ]; do let “sum = $sum + $i” i=$i+1 echo “the sum of the first $x numbers is: $sum”

72 example DB_ FILE=“ “ while [ ! -f $DB_FILE ] ; do
echo Please enter the database file to archive: read DB_FILE done The Complete Guide to Linux System Administration

73 Until Statements The until structure is very similar to the while structure. The until structure loops until the condition is true. So basically it is “until this condition is true, do this”. until [expression] do statements done $ cat countdown.sh #!/bin/bash #countdown.sh #echo “Enter a number: ”; read x echo ; echo Count Down until [ “$x” -le 0 ]; do echo $x x=$(($x –1)) sleep 1 echo ; echo GO !

74 Adding Loops to a Script (continued)
You normally can exit any shell script by pressing Ctrl+c. break command Exit from loop completely continue command Skip immediately to next iteration The Complete Guide to Linux System Administration

75 Continue Statements The continue command causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle. #!/bin/bash LIMIT=19 echo echo “Printing Numbers 1 through 20 (but not 3 and 11)” a=0 while [ $a -le “$LIMIT” ]; do a=$(($a+1)) if [ “$a” -eq 3 ] || [ “$a” -eq 11 ] then continue fi echo -n “$a ” done

76 example for NEXTFILE in $@ do if [ ! –f ‘$NEXTFILE' ] ; then
Suppose you want to process a number of file names that are provided on the command line. You need to test whether each file name is valid before you begin processing it. If the name is valid, you want to process that file, otherwise, you want to skip to the next file name. The continue command shown here causes the script to perform the next iteration of the for loop if a file name is not valid. for NEXTFILE in do if [ ! –f ‘$NEXTFILE' ] ; then echo “$NEXTFILE cannot be found! “ continue fi # Everything looks OK for the current file name. # Begin processing it done The Complete Guide to Linux System Administration

77 Break Statements The break command terminates the loop (breaks out of it). #!/bin/bash LIMIT=19 echo “Printing Numbers 1 through 20, but something happens after 2 … ” a=0 while [ $a -le “$LIMIT” ]; do a=$(($a+1)) if [ “$a” -gt 2 ] then break fi echo -n “$a ” done echo; echo; echo exit 0

78 example The Complete Guide to Linux System Administration
In a similar way, you can use the break command to exit from the loop completely. The example here uses a while loop with no test at all. This creates an infinite loop-the nonexistent test never fails, so the loop continues until the user presses Ctrl+c or the break command is executed. In in the script fragment that follows, the user does not need to press Ctrl+c to exit from the script. The script never exits based on testing a value in the while statement, but it does exit if a user enters q or Q because of the break command in the case statement. while do echo “Enter a file to see how many lines it contains (q to quit):” read NEXTFILE case $NEXTFILE in [qQ] break; ; *) wc -l $NEXTFILE ; ; esac done The Complete Guide to Linux System Administration

79 Using Functions in a Script
Named small shell script Can be referenced from other locations To define function: Follow name with ( ) Statements enclosed in braces { } considered part of function The Complete Guide to Linux System Administration

80 Functions Functions make scripts easier to maintain. Basically it breaks up the program into smaller pieces. A function performs an action defined by you, and it can return a value if you wish. #!/bin/bash hello() { echo “You are in function hello()” } echo “Calling function hello()…” hello echo “You are now out of function hello()” In the above, we called the hello() function by name by using the line: hello . When this line is executed, bash searches the script for the line hello(). It finds it right at the top, and executes its contents.

81 functions • You can copy the function from one script to another and know exactly what it will do, and that it has been written correctly (it doesn't have any bugs) because you've used it previously. • You can call the same function multiple times in a single script, so you don't have to rewrite and retest the same commands again and again. • You can separate the actions of your script into groups and make the script more readable, as the next example shows. The Complete Guide to Linux System Administration

82 function init_db_files() { DB_FILE="/data/newport/users.db
ADMIN=”nwells “ SQL_ MODE=”standard” } The Complete Guide to Linux System Administration

83 example #!/bin/bash # Author, dave lambert, dave@xyz.org
# Date, 12 October 2005 # Description: Database analysis, main script # init_db_files () { DB_FILE=" /data/newport/users.db ADMIN="nwells" SQL_MODE=“standard” } # Main part of script # First, initialize the database variables init_db_files # Now, let's begin reading data from the database file and # making calculations The Complete Guide to Linux System Administration

84 Shell Script Debugging
Syntax error Error in how statement is entered Logic error Error in what commands are trying to accomplish Find and fix both types of errors Use debugging features of shell The Complete Guide to Linux System Administration

85 Shell Script Debugging (continued)
You can start that script using this command: $ bash ./startnet -n option Check for syntax errors in script $ bash -n ./startnet Shell prints message when it finds syntax errors Does not actually execute any commands in script -v option Shell displays each line of script as it reads it $ bash -nv ./startnet The Complete Guide to Linux System Administration

86 Debugging Bash provides two options which will give useful information for debugging -v : displays each line of the script as typed before execution -x : displays each line as it is executed (abbreviated) Usage: #!/bin/bash –v, or #!/bin/bash –x $ cat for3.sh #!/bin/bash –x echo –n “Enter a number: ”; read x let sum=0 for (( i=1 ; $i<$x ; i=$i+1 )) ; do let “sum = $sum + $i” done echo “the sum of the first $x numbers is: $sum”

87 Using Shell Tracing Shell trace
Displays each line of script on screen as it is executed Different from –v option Substitutes actual values for regular expressions and variables Activated with -x option See if script is really using expected values The Complete Guide to Linux System Administration

88 example for loopvar in $@ Bash -x ./startnet *conf
The -x option causes the shell to print each line as it will be executed. So when the shell reaches the for statement, it displays the line as it has expanded it, containing all the matching names from the variable. If your working directory contains four files matching the pattern •*conf, then the shell prints something like this: For loopvar in eth0.conf lo.conf ethl.conf ppp.conf A shell trace lets you see if the script is really using the values you expect, and if it is executing commands in the order that you expect. The Complete Guide to Linux System Administration

89 Debugging within a Script
set command with -x option Turn on debugging within script Just at point where script appears to be working incorrectly set -x commands to debug set +x The Complete Guide to Linux System Administration

90 example If your script includes a jar loop that does not function as expected, you can enclose that loop within two set commands, enabling and then disabling the shell trace debugging function. By doing this, debugging information is only displayed for the loop causing the problem, making it easier to spot the problem: set -x for loopvar in do # process each file name that was provided on the command line done set +x The Complete Guide to Linux System Administration

91 Summary Shell scripts Execute complex set of commands by entering single script name Uses keywords from programming language Environment and positional variables often referenced in scripts if-then-else statement tests condition and executes statements if condition is present The Complete Guide to Linux System Administration

92 Summary (Continued) Loops using for and while
Repeatedly execute statement block Complex scripts make extensive use of functions Shell scripts can be debugged using shell options Many scripting languages used on Linux systems Linux includes support for many computer languages The Complete Guide to Linux System Administration


Download ppt "Chapter 14: Writing Shell Scripts"

Similar presentations


Ads by Google