Bash Syntax(from Sysadmin Decal)

1.Bash

Shebang

  • Determins the program used to execute the lines below
#! /path/to/interpreter

# such as
#! /bin/bash
#! /bin/sh
#! /usr/bin/python3

Running Your Scipt

  • Remeber to make your script executable
# Make executable
chmod +x your-script.sh

# Run script!
./your-script.sh

2.Variable

shell variables

  • Whitespace matters!
  • Variable interpolation with $
  • Display text with echo
NAME="value"
echo "$NAME"
  • Bash variables are untyped
  • Operations are contextual
  • Use the expr command to evaluate expressions
FOO=1
$FOO + 1 # ERROR!
expr $FOO + 1 # 2

User input

  • Use the read command to get user input
  • “-p” is for the optional prompt
read -p "send: " FOO
# enter "hi"
echo "sent: $FOO"
# output: sent: hi

subshell

  • Command substitution allows you to use another command’s output to replace the text of the command
FOO=$(expr 1 + 1)
echo "$FOO" # 2

3.Conditionals

  • Evaluates an expression
  • Also synonymous with []
  • Sets exit status to
    • 0(true)
    • 1(false)
logical operator equal to
-eq(equal) ==
-ne(not equal) !=
-gt(greater than) >
-ge(greater equal) >=
-lt(less than) <
-le(less equal) <=
Examples
test zero = zero; echo $? # 0 means true
test zero = one; echo $? # 1 means false

[0 -eq 0]; echo $? # 0 means true
[0 -eq 1]; echo $? # 1 means false

# if statement
if [ "$1" -eq 69 ];
then
  echo "nice"
else if [ "$1" -eq 42 ];
then
  echo ...
else 
  ...
fi

# case statement
read -p "are you 21?" ANSWER
case "$ANSWER" in
  "yes")
    echo "i give u cookie";;
  "no")
    ...;;
  *)
    ...;;
esac

4.Loops

# for loops
LIST="a b c d"
for I in $LIST
do
  echo "HELLO $I"
done

for f in $(ls -1) # ls -1 gives the name of files in the directory
do
  echo "renaming $f to new-$f"
  mv $f "new-$f"
done

# while loops

4.Functions

function greet() {
  echo "hey there $1" # position arguments
}
greet "Richard"
# hey there is Richard

function fib() {
    if [ $1 -le 1 ]; then
      echo $1
    else
        echo $(($(fib $(($1 - 1))) + $(fib $(($1 - 2))))) # add an extra bracket arount the calculation expressions to avoid operator precedence
    fi
}

fib 10 # output 55

5.Streams

Redirection

echo "hello" > file
sort < file

Pipes

  • Take ouput of first command and “pipe” it into the second one, connecting stdin and stdout
command1|command2

Additional Notes

  • Python
    • argparse: easy CLI
    • fabric: easy deployment
    • salt: generally useful for infrastructure-related tsaks
    • psutil(python system and process utilities): monitor system info
  • Use bash when the functionality you want is easily expressed as a composition of command line tool
    • Common file manipulation operations
  • Use Python when you need “heavy lifting” with complex conditions like data structures, messy state, recursion, OOP, etc.


电波交流