Bash Snippets - tnballo/notebook GitHub Wiki

Quit on error


set -ue

Force root


[ "$UID" -eq 0 ] || exec sudo "$0" "$@"

Run script from it's home dir regardless of caller dir


cd $(dirname "$0")
BASE_DIR=$(pwd)

Build a multi-line command with comments, run it


CMD_ARR=(
    ls   # Comment 1
    -a   # Comment 2
    -l   # Comment 3
)

eval "${CMD_ARR[@]}"

Print a sequence of commands


(
    set -x;
    echo "cmd 1";
    echo "cmd 2";
    echo "cmd 3";
)

Save webpage content to variable


MY_VAR=$(wget $MY_URL -q --show-progress -O -)

If env var not set, use default


PROJ_BUILD_DIR=${PROJ_BUILD_DIR:-"/abs/path/to/build/dir"}

Check for command binary


check_binary () {
    if ! [ -x "$(command -v $1)" ]; then
        echo "ERROR: missing binary $1!" >&2
        exit 1
    fi
}

Check for package


check_package () {
    if [ $(dpkg-query -W -f='${Status}' $1 2>/dev/null | grep -c "ok installed") -eq 0 ]; then
        echo "ERROR: missing package $1!" >&2
        exit 1
    fi
}

Color output


TOGGLE_COLOR='\033[0m'
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
WHITE='\033[0;37m'

echo -e "\n${RED}This is red!${TOGGLE_COLOR}"
echo -e "\n${GREEN}This is green!${TOGGLE_COLOR}"
⚠️ **GitHub.com Fallback** ⚠️