Bash and CLI

In this page

Commands

Redirect output

uptime > log.txt 2>&1
# same as
uptime 2> log.txt >&2

awk

cat /etc/passwd | awk -F: '{print $1}'

xargs

find . -name "*.js" | xargs cat | wc -l

tee

echo "hello" | tee /path/to/file

tr

$ echo "abc" | tr '[a-z]' '[A-Z]'
ABC

sed examples

$ echo "hello world" | sed 's/\([a-z]*\) \([a-z]*\)/\2 \1/'
world hello

See also Sed - An Introduction and Tutorial by Bruce Barnett

Array

$ arr=("one"
      "two")

$ echo ${arr[0]}
one

$ echo ${#arr[@]}
2

$ echo ${arr[@]}
one two

example usage:

CURL_PARAMS=( "-L"
              "-#")

WGET_PARAMS=( "--no-check-certificate"
              "-q"
              "-O-")

CURL_PARAMS+=("-u $HTTP_USER:$HTTP_PASSWORD")
WGET_PARAMS+=("--http-password=$HTTP_PASSWORD"
              "--http-user=$HTTP_USER")

command -v wget > /dev/null && GET="wget ${WGET_PARAMS[@]}"

command -v curl > /dev/null && GET="curl ${CURL_PARAMS[@]}" && QUIET=false

test -z "$GET" && abort "curl or wget required"

Variables

  • $? last exit value
  • $* all input params, "$*" => "$1 $2 ... $n"
  • $@ all input params, "$@" => "$1" "$2" ... "$n"
  • $# number of input params
  • $$ own PID
  • $! PID of last job run in background

see also ABS Internal Variables

Substitution

${parameter-default}, ${parameter:-default} - If parameter not set, use default.

see also ABS Parameter Substitution

Snippets

getopts

#!/bin/bash

prog=`basename ${0}`

usage_exit() {
  if [ ! -z "${1}" ]; then echo ${1}; echo; fi
  cat <<EOF
${prog} [-m SIZE] [-h]

${prog} by haishanh

    -m SIZE
        Specify xx size
    -h
        Show this help message
EOF
  if [ ! -z "${1}" ]; then exit 1; fi
}

while getopts :hm: arg; do
 case ${arg} in
  h)
    usage_exit
    ;;
  m)
    echo "-m enabeld"
    echo "${OPTARG}"
    ;;
  \?)
    usage_exit "Oops, unkown arg..."
    ;;
 esac
done

while read

Transverse space seperated file

while read _ mnt fstype options; do
  echo $fstype $options
done < /proc/mounts

Grouping commands

[ -n "$IPADDR" ] || [ -n "$HOSTNAME" ] || {
  echo "ip addr"
  echo "or hostname is needed"
  exit 1
}

Trapping signals

#!/bin/bash

do_cleanup()
{
  echo "Clean up"
  exit 1
}

trap "do_cleanup" INT EXIT

for i in {1..100}; do
  echo -n "${i}%"
  echo -ne "\r"
  sleep 0.5
done

System

# linux
ps -elf

# macOS
ps -e
# I have this alias in my rc file
alias pps="ps -eo pid,%cpu,command"