(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana University
Section Overview Comments and Script Headers Variables Flow Control Loops
References Linux System Administration Chapter 14 CQU COIT System Administration Course Textbook Chapter 9 Chapter 9 Lectures 2002 # #8
Why Learn Scripting? /bin/sh always there Understand/Modify Existing System Scripts RC Startup Scripts Daemon Startup Scripts Automate repetitive tasks Great for small tools
Writing/Debugging Scripts Know how to do job manually first Write in small (logical) parts Test each part before continuing Print modified variables Print command lines to be executed Never work on production data Comment code!!!
Starting Scripts Passed as input to a shell Example: /bin/bash mysript Run directly from the command line First line of script (i.e: #!/bin/bash ) Script must have execute bits set $PATH considerations
Commenting code Anything following ‘ # ’ is considered a comment and ignored Script Header Tells what the script does Common Entries: Author Date written Program name Command line usage Purpose Files used Notes/features Revision History
Argument Variables VariablePurpose $0 Name of the program $1 - $9 Command line arguments $# Number of Arguments $* All arguments as 1 word Each argument is a word
Other Special Variables VariablePurpose $$ PID number of script $! PID number of parent process $? Exit status of script (Checked by parent)
Basic Input read variable [ < filename ] Examples: read ANS read LINE < file (only reads first line)
Basic output echo [ -n ] [ -e ] “string” -n : No new line -e : Allow backslash options Example: echo –n “Enter your name: “
Backslash Options CharacterPurpose \aAlert (bell) \bBackspace \cDon’t display trailing newline \nNewline \rCarriage return \tHorizontal Tab \vVertical Tab \\Backslash \######: ascii value of character
Expression Evaluation expr command Math expressions ( +, -, *, /, % ) String expressions (match, substring, etc.) Logic expressions ( &, |, =, etc.) Example: COUNT=`expr $COUNT + 1`
Flow Control Need to determine which commands to run based on one or more conditions Useful to catch errors Provides flexibility in code Classic if-then-else model
If-Then condition Basic decision construct if condition then commands fi
String Tests Expression True if… -z string Length of string is 0 -n string Length of string is not 0 string1 = string2 If the 2 strings are identical string1 != string2 If the 2 strings are different string If string is not NULL
Numeric Tests Expression True if… int1 –eq int2 int1 equals int2 int1 –ne int2 int1 and int2 not equal int1 –gt int2 int1 > int2 int1 –ge int2 int1 >= int2 int1 –lt int2 int1 < int2 int1 –le int2 int1 <= int2
File Tests Expression True if… -r file File exists and readable -w file File exists and writable -x file File exists and executable -f file File exists and is a regular file -d file File exists and is a directory -h file File exists and is a symbolic link -p file File exists and is a named pipe
File Tests (Con’t.) Expression True if… -c file File exists and is a character device -b file File exists and is a block device -u file File exists and is SUID -g file File exists and is SGID -k file File exists and sticky bit set -s file File exists and size > 0 bytes
Logic Operators ExpressionPurpose ! Negates the expression -a AND -o OR ( expression ) Groups the expression
If-Then-Else condition if condition then commands else commands fi
If-Then-Else If condition if condition then commands elif condition then commands fi
Case condition Perform a range of tests on a variable case variable in pattern1) commands ;; pattern2) commands ;; esac *) matches all other cases
Loops Need to run block of code more than once Modes Repeat a set number of times Repeat while a condition is true Repeat until a condition is true
for loop Repeat for each variable in list for variable in variable_list do commands done
while loop Repeat until condition is false while [ condition ] do commands done
Reading Files Read a file one line at a time while read LINE do echo $LINE done < $FILENAME
do-until loop Repeat until condition is true until [ condition ] do commands done
Escaping out of loops Sometimes you need to exit loop early Error conditions Special conditions break command Example: while [ 1 ] do echo –n “Done? “ read ANS if [ $ANS = “y” ] then break fi done
Other scripting languages Perl Very popular among sysadmins Many modules available TCL/TK Expect Python