Download presentation
Presentation is loading. Please wait.
Published byAnthony Stevenson Modified over 6 years ago
1
Shell Scripting March 1st, 2004 Class Meeting 7
2
Shell Script (Program)
What is a shell script? A series of shell commands placed in an ASCII text file Commands include . . . anything you can type on the command line shell variables control statements (if, while, for, )
3
Script Execution Provide script as an argument to the shell program (i.e. bash my_script) Or specify which shell to use within the script First line of the script: #!/bin/bash Make sure that the script is executable Run directly from the command line No compilation is necessary
4
Simple Script #!/bin/bash echo “Hello, World!” cd ~ pwd Output:
/home/grads/callgood
5
Shell Variables Numeric Strings Arrays
var refers to the name of the variable, $var refers to the value var=100 # sets the value to 100 (( var2=1+$var )) Variable names begin with an alphabetic character and can include alpha, numeric, and the underscore
6
Numeric Variables Integer variables are the only pure numeric variables that can be used in bash Declaration and setting value declare –i var=100 Numeric expressions are enclosed in double parentheses (( var+=1 )) Operators are the same as in C/C++ +, -, *, /, %, &, |, <, >, <=, >=, ==, !=, &&, ||
7
String Variables Unless variables are explicitly declared as another type, they are considered to be strings var=100 makes the var the string 100 However, placing the variable within double parentheses will treat it as an integer (( var2=1+$var ))
8
String Variables (cont)
Using substrings ${string:n} ${string:5} # first five chars ${string:-2} # last two chars ${string:n:m} ${string:0:4} # first to fifth ${string:1:3} # second to fourth ${#string} # length of string Concatenating strings string_var1=“$string_var1 $string_var2”
9
Array Variables Array is a list of values – do not have to declare size Reference a value by ${a[index]} ${a[3]} # value in fourth position $a # same as ${a[0]} Use the declare –a command to declare an array declare –a sports sports=(basketball football soccer) sports[3]=hockey
10
Array Variables (cont)
Array initialization sports=(football basketball) moresports=($sports tennis) or ${array[*]} refers to the entire contents of the array echo ${moresports[*]} Output: football basketball tennis
11
Command Line Arguments
If arguments are passed to a script, they can be referenced by $1, $2, $3, . . . $0 refers to the name of the script refers to all of the arguments – not an array – space separated group of strings $# refers to the number of arguments
12
Output and Quoting echo command is used to output information to standard out echo –n does not print a newline Shell interprets $ and `` within double quotes $ - variable substitution ` - command substitution echo “`date +%D`” # 03/01/04 Shell does not interpret special charactes within single quotes echo ‘`date +%D`” # `date +%D`
13
Redirecting Output to File
Redirecting output to a file is the same as on the command line Examples echo “$var” > $OUTFILE # overwrite echo “$var” >> $OUTFILE # append String expansion echo $’\n\n\n’ echo $’\t’
14
Conditions If using integers: (( condition ))
If using strings: [[ condition ]] Examples (( a == 10 )) (( b >= 3 )) [[ $1 = -n ]] [[ ($v != fun) && ($v != games) ]] Special conditions for file existence, file permissions, ownership, file type, . . .
15
Conditions (cont) [[ -e $file ]] – File exists?
[[ -f $file ]] – Regular file? [[ -d $file ]] – Directory? [[ -L $file ]] – Symbolic link? [[ -r $file ]] – Read permission? [[ -w $file ]] – Write permission? [[ -x $file ]] – Execute permission?
16
If Statement Syntax if condition then statements elif else fi optional
17
If Statement (cont) Example if [[ -r $file ]] then
echo “$file is readable” elif [[ (-w $file) && (-x $file) ]] echo “$file is writeable and exectuable” fi
18
For Loops Syntax If list is omitted, $@ is assumed
for var [in list] do statements done If list is omitted, is assumed Otherwise ${list[*]}, where list is an array variable
19
For Loops (cont) Example colors=(yellow red blue green orange)
for color in ${colors[*]} do echo $color done
20
While Loops Syntax while condition do statements done The keywords break, continue, and return have the same meaning as in C/C++
21
Case Statements Syntax case expression in pattern1) statements ;;
... *) esac
22
Case Statements (cont)
Example case $1 in -a) # statements related to option a ;; -b) # statements related to option b *) # all other options esac
23
Command Substitution Use the command of a command in a variable, condition, . . . `command` $(command) Example files=(`ls`) for file in ${files[*]} do echo $file done
24
Functions Syntax function function_name { statements . . . }
Functions can take arguments, in the same way that the script takes arguments (i.e. $1 represents first argument, $2 the second, )
25
Functions (cont) Example function add_two{ (( $sum=$1+$2 ))
return $sum } . . . # calling a function add_two 1 3 echo $? $? represents the return value of the last function call or command Function definition needs to occur before the function is called in the script
26
Assignment Suggestions
One approach to the script: Handle arguments, setting flags for each i.e., if recursive option is given, set a variable that indicates that it was set Write part of script that generates the makefile in a function; call this function recursively, if necessary (i.e. if recursive option was set)
27
Assignment Suggestions (cont)
Within function, store the output of ls command in an array; loop through this array and test filename of each file in the current directory for valid filenames and/or extensions files=(`ls`) for file in ${files[*]} do # no need to check directories if [[ -f $file ]] then # test for valid filename and/or extensions fi done
28
Assignment Suggestions (cont)
Remember that you need to know all of the valid filenames before you can begin writing any of the makefile; you may need to store parts of the output in temporary files, and then concatenate these files into your makefile; be sure that you remove and temporary files that you create
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.