Lecture 05
Lecture 05
1
Administrivia
HW1 Live - Due next Thursday 10/14 at 11:50pm
declaration
function_name() { hello_world () {
echo 'hello, world'
commands
}
}
- semicolons not required at end of lines
hello_world
https://linuxize.com/post/bash-functions/ 3
Variable Scope
All variables are by default global, even if declared inside a function
Local can be declared using the local keyword
~/variables_scope.sh
#!/bin/bash
var1='A'
var2='B'
my_function () { Output:
local var1='C'
Before executing function: var1: A, var2: B
var2='D'
Inside function: var1: C, var2: D
echo "Inside function: var1: $var1, var2: $var2"
After executing function: var1: A, var2: D
}
my_function
4
Boolean Logic in Bash
•Bash understands Boolean logic syntax
• && and
• || or
• ! not
• binary operators:
• -eq equals Ex: 1 -eq 1 is TRUE
• -ne not equals Ex: 1 -ne 2 is TRUE
• -lt less than Ex: 1 -lt 2 is TRUE
• -gt greater than Ex: 1 -gt 2 is FALSE
• -le less than or equal to Ex: 2 -le 2 is TRUE
• -ge greater than or equal to Ex: 2 -ge 1 is TRUE
•Square brackets encase tests: [ test ]
• you can use the typical symbols for comparison when between brackets, but syntax will be a bit different
https://opensource.com/article/19/10/programming-bash-logical-operators-shell-expansions 5
If Statements if [ $# -ne 2 ]
then
if [ test ]; then echo "$0: takes 2 arguments" 1>&2
commands exit 1
fi fi
if [ -f .bash_profile ]; then
echo “You have a .bash_profile.”
else
echo “You do not have a .bash_profile”
fi
https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php 6
Common If Use Cases
▪If file contains
if grep –q –E ‘myregex’ file.txt; then
echo “found it!”
fi
-q option “quiet” suppresses the output from the loop
If is gated on successful command execution (returns 0)
done
https://ryanstutorials.net/bash-scripting-tutorial/bash-loops.php 8
Common loop use cases
▪Iterate over files ▪Iterate over arguments to script
s + d i re ctories
for file in $(ls) <- All file while [ $# -gt 0 ]
do do
if [-f $file ]; then echo $*
echo “$file” shift
fi done
done Shift command moves through list
of arguments
Similar to .next in Java Scanner
▪End scripts with a code to tell the computer whether the script was successful or had an error
▪0 = successful
- exit without a number defaults to 0
exit
exit 0
▪Non 0 = error
exit 1