Bash

Shebang

Special comment, specifies that the file is a script and calls a certain interpreter (i.e., bash, sh, python)

1
2
3
4
5
6
7
#!/bin/bash

#!/bin/sh

#!/usr/bin/env python

#!/usr/bin/python

Comments

Use a pound/sharp/hashtag without a ! to write comments

1
# This is a comment

Variables

shell variables

  • Whitespace matters!
  • Use $VAR to output the value of variable VAR
  • Display text with echo
1
2
NAME="value"
echo "$NAME"
  • Types? What types?
  • Bash variables are untyped
  • Operations are contextual
  • Everything is string
1
2
3
FOO=1
$FOO + 1
# error!
  • Use the expr command to evaluate expressions
  • Part of coreutils
1
2
3
FOO=1
expr $FOO + 1
2

User input

  • Use the read command get user input
  • “-p” is for the optional prompt
1
2
3
4
5
read -p "send: " FOO
# type “hi” and enter

echo "sent: $FOO"
sent: hi

subshell

$(cmd) evaluates the command cmd inside, and substitutes the output into the script.

1
2
3
FOO=$(expr 1 + 1)
echo "$FOO"
2

Conditionals

test

conditional checks

  • Evaluates an expression. Also synonymous with []
  • Sets exit status to 0 (true), 1 (false)
1
2
3
4
5
6
-eq ==
-ne !=
-gt >
-ge >=
-lt <
-le <=
1
2
3
4
test zero = zero; echo $?
0 # 0 means true
test zero = one; echo $?
1 # 1 means false

“boolean” ops

&& and || for shell, -a and -o for test/[]

1
2
3
4
5
[ 0 -lt 1 ] && [ 0 -gt 1 ]; echo $?
1

[ 0 -lt 1 -o 0 -gt 1 ]; echo $?
0

if

What if…?

1
2
3
4
if [ “$1” -eq 79 ];
then
echo “nice”
fi

if-else

…And what ifn’t

1
2
3
4
5
6
if [ “$1” -eq 79 ];
then
echo “nice”
else
echo “darn”
fi

elif

…And what ifn’t but if

1
2
3
4
5
6
7
8
9
if [ “$1” -eq 79 ];
then
echo “nice”
elif [ “$1” -eq 42 ];
then
echo “the answer!”
else
echo “wat r numbers”
fi

case

No one likes long if statements…

1
2
3
4
5
6
7
8
9
10
11
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

Loops

for loops

for all your stuff in stuffs

1
2
3
4
5
SHEEP=("one" "dos" "tre")
for S in $SHEEP
do
echo "$S sheep..."
done

supports ranges too

1
2
3
4
5
6
n=0
for x in {1..10}
do
n=$(expr $x + $n)
done
echo $n

while loops

1
2
3
4
while true
do
echo "nightmare "
done

Functions

functions

1
2
3
4
5
6
function greet() {
echo "hey there $1"
}
greet “sysadmin decal”

hey there sysadmin decal

script args are stored the same way as with functions

1
2
3
4
5
6
7
8
9
10
11
# in terminal
ls .
b.txt a.txt c.txt

# script.sh
ls $1 | sort

# in terminal
./script.sh .
a.txt b.txt
c.txt

Streams

Redirection

Use > to output to somewhere else, like a text file!

1
echo "hello" > out.txt

Use < to take input from a file!

1
sort < file

Append

Use >> to append output to a file. If file is empty, works the same as >

1
echo "hello" >> out.txt

Pipes

Take output of first command and “pipe” it into the second one, connecting stdin and stdout

1
command1 | command2