Bash is the default shell environment for most modern Linux distributions. While the differences between different shell environments are minimal if you are not a power user, Bash has extended functionality. Any executable in your $PATH environment variable can be used as a Bash command, and referencing an executable outside of $PATH will execute it by default. While Bash has very complete documentation, this post will demonstrate a few hacks and common usage patterns for bash scripting.
Argument parsing
while [ $# -gt 0 ]; do
case "$1" in
-h | --help) usage;;
-a | --arg1) ARG1="$2"; shift 2;;
-b | --arg2) ARG2="$2"; shift 2;;
-e | --flag1) FLAG1=1; shift;;
*) usage "$1";;
esac
done
One-liner fizzbuzz
seq 100 | awk '$0=$1%15?$1%5?$1%3?$1:"Buzz":"Fizz":"FizzBuzz"'
Text processing
grep
Print only lines that contain the given sequence
-A 7: print the matching lines and the following 7 lines after each occurrence.-B 7: same as above but before-P: use Perl-style regex
sed
sed 's/foo/bar/g' file.txt
Find foo and replace with bar
awk
The following prints the entry points for all processes running under your user
ps -ux | awk '{print $11}'
And this prints the number of each processes under each entry point
ps -ux | awk '{print $11}' | awk '{count[$0]++} END {for (line in count) print count[line], line}' | sort -nr