Just a collection of oneliners often use, but always forget 🙂 The following can be used from the terminal, or be used as a script.
#!/bin/bash
# ^^ Always start with a shebang!
# -e = immediately exit if any command has non-zero exit status
# -o pipefail = prevents masking of errors in a pipeline
# -u = error when using reference that has not been defined
set -eou pipefail
# Check if directory is present before creating to avoid annoying warning.
[ ! -d /tmp/whatever ] && mkdir -p /tmp/whatever
# Check if file exists before performing operation on it.
[ -f file.txt ] && echo "blah" >> file.txt
# Check that script is NOT run as root
[[ $EUID -ne 0 ]] || {
echo "[ERROR] Do not run as root!"
exit 1
}
# Check that script is run as root
[[ $EUID -ne 0 ]] && {
echo "[ERROR] This script must be run as root"
}
# Location of the script (not the location from where it is executed from
THISDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
# Grep, but do not match grep itself -> put first character of grep match in square brackets []. Suppose we want to see if blender is still running:
ps ax | grep [b]lender
# Kill application by name (when pkill is absent ;) ) Suppose we want to kill "my-awesome-app"
ps ax | grep -i [m]y-awesome-app | awk '{ print $2 }'
# Install only if not installed.
APP=bindfs; [ -x "`which ${APP}`" ] || sudo apt install ${APP}
# Use default if first argument on command line is not set.
FIRST_ARG="${1:-some_default_var}"
# Get the amount of CPUs on the device (-1, to use for parallel jobs)
cpus=$(($(nproc) -1))
# Or
cpus=$(($(grep -c "^processor" /proc/cpuinfo) - 1))
Geef een reactie