guh.me - gustavo's personal blog

Book review - Pro Bash Programming: Scripting the Linux Shell

βΈ»

Shell scripting is essential if you are more than a regular user of a Unix-like operating system. Most Linux systems come with Bash, the Bourne-again shell, and that’s why I chose Pro Bash Programming: Scripting the Linux Shell, by Chris Johnson, to learn more about it. (this entire phrase is kinda stupid, lol)

This book covers basic to advanced topics in little more than 200 pages (of actual text), and even though everything is a little condensed, the text is clear enough to understand. All the basics are covered, and if you want to stick only with them, read up to chapter 6 and skim through the rest of the book - you won’t really miss learning how to “implement” awk in Bash. ;)

Despite many open-source books on Bash being available on the interwebz (Advanced Bash-Scripting Guide, Bash Guide for Beginners), Pro Bash Programming is much more newbie friendly, and I highly recommend it.

Book on Amazon: http://www.amazon.com/Pro-Bash-Programming-Scripting-Experts/dp/1430219971

My Personal Notes

Chapter 1 - Your first shell program

#!/bin/sh
#!/bin/env bash
source file.sh
# or
. file.sh

Chapter 2 - Input and output

printf "Hello, %s!" "$1"

$ hello.sh John
$ Hello, John!
var=Foo
echo $var
$ Foo
printf <FORMAT (%s %d %f %e)> <ARGS>
printf "%s" Hello World
$ Hello World
# from stdin
read var

# from file
read var < file.txt
today=$( date )
curpwd=$( pwd )

Chapter 3 - Looping and branching

$? == 0  -> success
$? != 0  -> error
# Test a file
[ -x $HOME/file ]

# Test an integer
# OPERATOR: -eq, -ne, -gt, -lt, -ge, -le
[ 2 <OPERATOR> -1 ]

# Test string
[ "a" = "b" ]
[ "a" != "b" ]

# Test regex
# The regular expression must be unquoted
[[ $string =~ h[aeiou] ]]
if <condition list>; then
elif <condition list>; then
else
fi
# Test of dir exists and then cd into it
test -d "$dir" && cd "$dir"

# Exits with an error if CD fails
cd "$dir" || exit 1
case $str in
  pattern1) commands;;
  pattern2) commands;;
esac
while <commands>; do
done

until <commands>; do
done

for var in Canada Usa Uk; do
  printf "%s\n" "$var"
done

Chapter 4 - Command-line parsing and expansion

Chapter 6 - Shell functions

function name()
{
  <commands>

  # Restricts scope of variable to function
  local var=Foo
}

Chapter 8 - File operations and commands