Skip to content

Bash

Set default values

foo=foobar
# echo ${foo:-"barfoo"}
foobar
unset foo
# echo ${foo:-"barfoo"}
barfoo

Substitution

foo=foobar
# echo ${foo/oo/öö}
fööbar

Remove Patterns

foo="/a/b/c"
# echo ${foo#*/}
a/b/c
# echo ${foo##*/}
c
# echo ${foo#/}
a/b/c
# echo ${foo##/}
a/b/c
foo="/a/b/c"
# echo ${foo%/*}
/a/b
# echo ${foo%%/*}

# echo ${foo%%/}
/a/b/c
# echo ${foo/}
/a/b/c

Case modification

# foo=fOoBaR
# echo ${foo,}
fOoBaR
# echo ${foo,,}
foobar
# foo=fOoBaR
# echo ${foo^}
FOoBaR
# echo ${foo^^}
FOOBAR

Trap for autodelete

TMPF=$(mktemp -u)
trap "rm -rf $TMPF" EXIT

Script with options/arguments

#!/bin/bash
#

function usage() {
  echo "usage $0:"
  echo " -b) A bool value"
  echo " -s) A string value"
  echo " -h) exclude tags from filter (regex)"
  exit 3
}

while getopts "bs:h" opt; do
  case $opt in
    b) BOOL=true ;;
    s) STRING="$OPTARG" ;;
    h) usage ;;
  \?) usage ;;
  esac
done
#!/bin/bash
#

function usage() {
  echo "usage $0:"
  echo " -b|--bool) A bool value"
  echo " -s|--string) A string value"
  echo " -a|--array) A string value that is written into array"
  echo " -h|--help) exclude tags from filter (regex)"
  exit 3
}

[ "$#" -eq 0 ] && usage

while (($#)); do
    case $1 in
        -b|--bool) BOOL=true ;;
        -a|--array) ARRAY+=($2) ;;
        --string|-s) STRING=$2 ;;
        -h|-\?|--help) usage ;;
    esac
    shift
done

Check for packages

#!/bin/bash

# Verify all packages are installed
function is_installed() {
  bin=$1; pkg=$2
  which $bin > /dev/null 2>&1 || \
  if [ $? -ne 0 ]; then
    echo $bin not found. Please install $pkg
    ABORT=true
  fi
}

is_installed jq jq
is_installed sendEmail sendemail
is_installed openstack python-openstackclient

[ -n "$ABORT" ] && exit 3

Generate random strings

function rnd () {
    tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w ${1:-32} | head -n 1
}
# call function
$ rnd 40
YkXShfvvT2aNplwnzic41cUEAHblkNbNgl7NZriK

ZSH and Bash (since at least version 4) can print emoji icons. You can lookup emojis on emojipedia and print them with echo -e. Look for a emoji you like an head to the Codepoints section. Replace U+ by \u and you're done.

echo -e "\u2714"
$ echo -e "\u2714"

Last update: December 27, 2020