Index The shell of Linux Bourne Shell Programming
Index • • The shell of Linux Bourne Shell Programming find. and. regular. expression text manipulation Shell 编程 2
The shell of Linux • • • Bourne shell (sh), C shell (csh), Korn shell (ksh), TC shell (tcsh), Bourne Again shell (bash) Shell 编程 3
Difference between programming and scripting languages – Programming languages are generally a lot more powerful and a lot faster than scripting languages. Programming languages generally start from source code and are compiled into an executable. This executable is not easily ported into different operating systems. – A scripting language also starts from source code, but is not compiled into an executable. Rather, an interpreter reads the instructions in the source file and executes each instruction. Interpreted programs are generally slower than compiled programs. The main advantage is that you can easily port the source file to any operating system. Shell 编程 4
The first bash program • We must know how to use a text editor. There are two major text editors in Linux: – vi, emacs (or xemacs). • So fire up a text editor; for example: – $ vi & and type the following inside it: – #!/bin/bash echo “Hello World” • The first line tells Linux to use the bash interpreter to run this script. We call it hello. sh. Then, make the script executable: – $ chmod 700 hello. sh – $ ls –l -rwx------ hello. sh Shell 编程 5
The first bash program • To execute the program: – $ hello. sh -bash: hello. sh: command not found The home directory (where the command hello. sh is located) is not in the variable PATH – echo $PATH : bin: /usr/bin: … We must specify the path of hello. sh – $/home/srinaldi/Scripts/hello. sh – $. /hello. sh Shell 编程 6
The second bash program • We write a program that copies all files into a directory, and then deletes the directory along with its contents. This can be done with the following commands: – $ mkdir trash $ cp * trash $ rm -rf trash $ mkdir trash • Instead of having to type all that interactively on the shell, write a shell program instead: – $ cat trash #!/bin/bash # this script deletes some files cp * trash rm -rf trash mkdir trash echo “Deleted all files!” Shell 编程 7
• #!/bin/bash # if 1. 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))” else echo “Wrong insertion !” fi
• Bourne Shell Programming Shell 编程 74
Bourne Shell Programming • Certainly the most popular shell is “bash”. Bash is the shell that will appear in the GNU operating system. Bash is an sh-compatible shell that incorporates useful features from the Korn shell (ksh) and C shell (csh). • bash is not only an excellent command line shell, but a scripting language in itself. Shell scripting allows us to use the shell's abilities and to automate a lot of tasks that would otherwise require a lot of commands. Shell 编程 75
Borne Shell q Background m Early Unix shell that was written by Steve Bourne of AT&T Bell Lab. m Basic shell provided with many commercial versions of UNIX m Many system shell scripts are written to run under Bourne Shell m A long and successful history Shell 编程 76
Bourne Shell Programming • Control structures – – – if … then for … in while until case break and continue Shell 编程 77
if … then • Structure if test-command then commands fi Example: if test “$word 1” = “$word 2” then echo “Match” fi Shell 编程 78
test • Command test is a built-in command • Syntax test expression [ expression ] – The test command evaluate an expression – Returns a condition code indicating that the expression is either true (0) or false (not 0) • Argument – Expression contains one or more criteria • • Logical AND operator to separate two criteria: -a Logical OR operator to separate two criteria: -o Negate any criterion: ! Group criteria with parentheses – Separate each element with a SPACE Shell 编程 79
Test Criteria • Test Operator for integers: int 1 relop int 2 Relop Description -gt Greater than -ge Greater than or equal to -eq Equal to -ne Not euqal to -le Less than or equal to -lt Less than Shell 编程 80
Exercise • Create a shell script to check there is at least one parameter – Something like this: … if test $# -eq 0 then echo “ you must supply at least one arguments” exit 1 fi … Shell 编程 81
Test Criteria • The test built-in options for files Option Test Performed on file -d filename Exists and is a directory file -f filename Exists and is a regular file -r filename Exists and it readable -s filename Exists and has a length greater than 0 -u filename Exists and has setuid bit set -w filename Exists and it writable -x filename Exists and it is executable …… …… Shell 编程 82
Exercise • Check weather or not the parameter is a non-zero readable file name – Continue with the previous script and add something like if [ -r “$filename” –a –s “$filename” ] then …… fi Shell 编程 83
Test Criteria • String testing Criteria meaning String True if string is not the null string -n string True if string has a length greater than zero -z string True if string has a length of zero String 1 = string 2 True if string 1 is equal to string 2 String 1 != string 2 True if string 1 is not equal to string 2 Shell 编程 84
Exercise • Check users confirmation – Frist, read user input echo -n “Please confirm: [Yes | No] “ read user_input – Then, compare it with standard answer ‘yes’ if [ “$user_input” = Yes ] then echo “Thanks for your confirmation!” Fi Shell 编程 85
if…then…else • Structure if test-command then commands else fi commands – You can use semicolon (; ) ends a command the same way a NEWLINE does. if [ … ]; then …… fi if [ 5 = 5 ]; then echo "equal"; fi Shell 编程 86
if…then…elif • Structure if test-command then commands elif test-command then commands. . . else commands fi Shell 编程 87
Debugging Shell Scripts • Display each command before it runs the command – Set the –x option for the current shell • $set –x – Use the –x to invoke the script • $sh –x command arguments – Add the set command at the top of the script • set –x • Then each command that the script executes is preceded by a plus sign (+) – Distinguish the output of trace from any output that the script produces • Turn off the debug with set +x Shell 编程 88
for… in • Structure for loop-index in argument_list do commands done Example: for file in * do if [ -d “$file” ]; then echo $file fi done Shell 编程 89
for • Structure for loop-index do commands done – Automatically takes on the value of each of command line arguments, one at a time. Which implies for arg in “$@” Shell 编程 90
while • Structure while test_command do commands done Example: while [ “$number” –lt 10 ] do …… number=`expr $number + 1` done Shell 编程 91
until • Structure until test_command do done commands Example: secretname=jenny name=noname until [ “$name” = “$secretname” ] do echo “ Your guess: c” read name done Shell 编程 92
break and continue • Interrupt for, while or until loop • The break statement – transfer control to the statement AFTER the done statement – terminate execution of the loop • The continue statement – Transfer control to the statement TO the done statement – Skip the test statements for the current iteration – Continues execution of the loop Shell 编程 93
Example: for index in 1 2 3 4 5 6 7 8 9 10 do if [ $index –le 3 ]; then echo continue fi echo $index if [ $index –ge 8 ]; then echo “break” break fi done Shell 编程 94
case • Structure case test_string in pattern-1 ) commands_1 ; ; pattern-2 ) commands_2 ; ; …… esac • default case: catch all pattern Shell 编程 *) 95
case • Special characters used in patterns Pattern Matches * Matches any string of characters. ? Matches any single character. […] Defines a character class. A hyphen specifies a range of characters | Separates alternative choices that satisfy a particular branch of the case structure Shell 编程 96
Example #!/bin/sh echo “n Command MENUn” echo “ a. Current data and time” echo “ b. Users currently logged in” echo “ c. Name of the working directoryn” echo “Enter a, b, or c: c” read answer echo case “$answer” in a) date ; ; b) who ; ; c) pwd ; ; *) echo “There is no selection: $answer” ; ; Shell 编程 esac 97
Built-in: exec • Execute a command: – Syntax: exec command argument – Run a command without creating a new process • Quick start • Run a command in the environment of the original process • Exec does not return control to the original program • Exec can be the used only with the last command that you want to run in a script • Example, run the following command in your current shell, what will happen? $exec who Shell 编程 100
Built-in: exec • Redirect standard output, input or error of a shell script from within the script • exec < infile • exec > outfile 2> errfile – Example: sh-2. 05 b$ more redirect. sh exec > /dev/tty echo "this is a test of redirection" sh-2. 05 b$. /redirect. sh 1 > /dev/null 2 >& 1 this is a test of redirection Shell 编程 101
Catch a signal: builtin trap • Built-in trap – Syntax: trap ‘commands’ signal-numbers – Shell executes the commands when it catches one of the signals – Then resumes executing the script where it left off. • Just capture the signal, not doing anything with it trap ‘ ‘ signal_number – Often used to clean up temp files – Signals • • • SIGHUP SIGINT SIGKILL SIGTERM SIGSTP … 1 2 9 15 24 disconnect line control-c kill with -9 default kill control-z Shell 编程 102
Example [ruihong@dafinn ~/cs 3451]$ more inter #!/bin/sh trap 'echo PROGRAM INTERRUPTED' 2 while true do echo "programming running. " sleep 1 done Shell 编程 103
A partial list of built-in • • • bg, fg, jobs break, continue cd, pwd echo, read eval command exec exit export, unset test job control change the loop working directory display/read scan and evaluate the execute a program exit from current shell export/ remove a val or fun compare arguments Shell 编程 104
A partial list of builtin • • • kill set shift times and trap type function umask wait ulimits sends a signal to a process or job sets flag or argument promotes each command line argument displays total times for the current shell traps a signal show whether unix command, build-in, file creation mask waits for a process to terminate. print the value of one or more resource Shell 编程 105
functions • A shell function is similar to a shell script – It stores a series of commands for execution at a later time. – The shell stores functions in the memory – Shell executes a shell function in the same shell that called it. • Where to define – In. profile – In your script – Or in command line • Remove a function – Use unset built-in Shell 编程 106
functions • Syntax function_name() { commands } • Example: sh-2. 05 b$ whoson() >{ > date > echo "users currently logged on" > who >} sh-2. 05 b$ whoson Tue Feb 1 23: 28: 44 EST 2005 users currently logged on ruihong : 0 Jan 31 08: 46 ruihong pts/1 Jan 31 08: 54 (: 0. 0) ruihong pts/2 Jan 31 09: 02 (: 0. 0) Shell 编程 107
Example sh-2. 05 b$ more. profile setenv() { if [ $# -eq 2 ] then eval $1=$2 export $1 else echo "usage: setenv NAME VALUE" 1>&2 fi } sh-2. 05 b$. . profile sh-2. 05 b$ setenv T_LIBRARY /usr/local/t sh-2. 05 b$ echo $T_LIBRARY /usr/local/t Shell 编程 108
Exercise • Let’s look at some system scripts – /etc/init. d/syslog – /etc/init. d/crond Shell 编程 109
Summary • Shell is a programming language • Programs written in this language are called shell scripts. – Variable – Built-in – Control structure – Function – Call utilities outside of shell • find, grep, awk Shell 编程 110
- Slides: 43