Shell Scripting
Lecture 2
laksith, trinityc
Course Resources
Engaging with this lecture
Topics
What’s on the menu?
But WHY should I learn to script?
Topics
What’s on the menu?
Bash
A shell...
And also a programming language!
Comments
Use a pound/sharp/hashtag
# This is a comment
shell variables
NAME=”value”
echo “$NAME”
shell variables
FOO=1
$FOO + 1
shell variables
FOO=1
$FOO + 1
error!
shell variables
FOO=1
expr $FOO + 1
2
User input
read -p “send: ” FOO
# type “hi” and enter
echo “sent: $FOO”
sent: hi
subshell
FOO=$(expr 1 + 1)
echo “$FOO”
2
Topics
What’s on the menu?
test
(Yup you read that right)
test
-eq ==
-ne !=
-gt >
-ge >=
-lt <
-le <=
test
test zero = zero; echo $?
0 # 0 means true
test zero = one; echo $?
1 # 1 means false
if
What if...?
if [ “$1” -eq 69 ];
then
echo “nice”
fi
if-else
...And what ifn’t
if [ “$1” -eq 69 ];
then
echo “nice”
else
echo “darn”
fi
elif
...And what ifn’t but if
if [ “$1” -eq 69 ];
then
echo “nice”
elif [ “$1” -eq 42 ];
then
echo “the answer!”
else
echo “wat r numbers”
fi
case
No one likes long if statements…
read -p "are you 21?" ANSWER
case "$ANSWER" in
“yes”)
echo "i give u cookie";;
“no”)
echo "thats illegal";;
“are you?”)
echo “lets not”;;
*)
echo "please answer"
esac
Topics
What’s on the menu?
for loops
for all your stuff in stuffs
SHEEP=("one" "dos" "tre")
for S in $SHEEP
do
echo "$S sheep..."
done
while loops
the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never the end is never
while true
do
echo "the end is never "
done
Time to Exercise!
Let’s write a script that renames files in our current directory
> ls
a.txt b.txt c.txt
> ./mycoolscript.sh
> ls
new_a.txt new_b.txt new_c.txt
Time to Exercise!
Let’s write a script that renames files in our current directory
#! /bin/sh
FILES=$(ls *.txt)
for FILE in $FILES
do
mv $FILE new_$FILE
done
Topics
What’s on the menu?
functions
fun
function greet() {
echo "hey there $1"
}
greet “Richard”
hey there Richard
Topics
What’s on the menu?
Redirection
echo "hello" > out.txt
Use > to output to somewhere else,�like a text file!
Redirection
sort < file
Use < to take input�from a file!
Pipes
command1 | command2
Take output of first command and “pipe” it into the second one, connecting stdin and stdout
Additional Notes
Other Resources
OCF logo assets
Copy-paste these!!!
DO NOT MODIFY
Individually cropped sticker assets
Copy-paste these!!!
DO NOT MODIFY