Shell Scripting
Ian McDonald
Sign In Link: decal.ocf.berkeley.edu/signin
Magic Word:
the motivation
the motivation
the motivation
the motivation
with great power comes…
xkcd.com/974
Bash Is...
Bash Is...
shell variables and types
shell variables and types
shell variables and types
shell variables and types
test
test - integer comparison
$ test 0 -eq 0; echo $? # exit code 0 means true�0�$ test 0 -eq 1; echo $? # exit code 1 means false�1
test - string comparison
$ test zero = zero; echo $? # exit code 0 means true�0�$ test zero = one; echo $? # exit code 1 means false�1
test - integer comparison
$ [ 0 -eq 0 ]; echo $? # exit code 0 means true�0�$ [ 0 -eq 1 ]; echo $? # exit code 1 means false�1
test - string comparison
$ [ zero = zero ]; echo $? # exit code 0 means true�0�$ [ zero = one ]; echo $? # exit code 1 means false�1
if-then
if TEST-COMMANDS; then�� CONSEQUENT-COMMANDS��elif MORE-TEST-COMMANDS; then�� MORE-CONSEQUENT-COMMANDS��else �� ALTERNATE-CONSEQUENT-COMMANDS;��fi
if-then
#!/bin/bash�# contents of awesome_shell_script��if [ “$1” -eq “$2” ]; then� echo “args are equal”�else� echo “args are not equal”�fi
if-then
$ ./awesome_shell_script 0 0�args are equal�$ ./awesome_shell_script 0 1�args are not equal
while
while TEST-COMMANDS; do�� CONSEQUENT-COMMANDS��done
while
#!/bin/bash�# contents of awesome_shell_script��n=”$1”�while [ “$n” -gt 0 ]; do� echo “$n”� let n=”$n-1”�done
while
$ ./awesome_shell_script 5�5�4�3�2�1
command substitution
$ A=`expr 1 + 1`
$ echo $A
2
functions
name_of_function() {�� FUNCTION_BODY��}
name_of_function $arg1 $arg2 ... $argN
functions
#!/bin/bash�# contents of awesome_shell_script��foo() {� echo hello “$1”�}��foo “$1”
functions
$ ./awesome_shell_script world�hello world
functions
fib() {� N=”$1”� if [ “$N” -eq 0 ]; then� echo 0� elif [ “$N” -eq 1 ]; then� echo 1� else� echo $(($(fib $(($N-2))) + $(fib $(($N-1)))))� fi�}��fib “$1”
functions
$ ./fibonacci 10�55
the case for python
the case for python
the case for python
Use Bash when:
the case for python
Use Python when:
shebang!
shebang!
She bang! (Tangent)
running your script
$ path/to/interpreter my-shell-script
running your script
$ path/to/my-shell-script
other resources
lab assignment