Tools

Bash

Shell scripting, redirection, and command-line survival.

Variables

name="Ada"
echo "Hello $name"
count=$(ls | wc -l)   # command substitution
readonly PI=3.14
unset name

Conditionals

if [ "$x" -gt 10 ]; then
  echo "big"
elif [ "$x" -eq 10 ]; then
  echo "ten"
else
  echo "small"
fi

[ -f file ]   # file exists
[ -d dir ]    # dir exists
[ -z "$s" ]   # string empty

Loops

for i in 1 2 3; do echo $i; done
for f in *.txt; do echo "$f"; done

while read line; do
  echo "$line"
done < file.txt

Redirection & pipes

cmd > out.txtStdout to file (overwrite)
cmd >> out.txtAppend stdout
cmd 2> err.txtRedirect stderr
cmd &> all.txtBoth streams
cmd1 | cmd2Pipe output
cmd < in.txtStdin from file

Useful commands

grep -r "text" .Recursive search
find . -name "*.js"Find files
sed "s/a/b/g" fReplace text
awk "{print $1}"Print first column
xargsBuild args from stdin
chmod +x script.shMake executable

Functions & args

greet() {
  echo "Hi, $1"      # first arg
  echo "All: $@"     # all args
  return 0
}
greet "world"

# script args: $0 name, $# count, $? last exit code