Bash - Snippets

Page content

some Bash snippets

Change Working Directory

Switch the Working Directory to the Base Path where the Scripts remains. Helpfull for Includes, Log Files, Relative Path and so on …

#!/usr/bin/env bash
script_path=$(dirname "$0")
cd "$script_path"

Check Return Code

Run a Command, store the Return Code, and check if it was successfull or failed

#!/usr/bin/env sh

check_ret () {
  if [[ "$ret" == "0" ]]; then
    echo "Command terminated sucessfully"
  else
    echo "Command returned an Error: ${ret}"
  fi
}

which bash > /dev/null 2>&1
ret=$?
check_ret $ret


which BASH > /dev/null 2>&1
ret=$?
check_ret $ret

exit 0

Source or Execute

You can Source a Script or Execute it. On Different Shells and on different Operation Systems.

#!/usr/bin/env bash

# Var
os=$(uname -mrs)

# Helper function
is_sourced() {
if [ -n "$ZSH_VERSION" ]; then 
    mysh="zsh"
    case $ZSH_EVAL_CONTEXT in *:file:*) return 0;; esac
else  # Add additional POSIX-compatible shell names here, if needed.
    mysh="bash"
    case ${0##*/} in dash|-dash|bash|-bash|ksh|-ksh|sh|-sh) return 0;; esac
fi
return 1  # NOT sourced.
}

# Sample call.
echo
is_sourced && sourced=1 || sourced=0

if [[ $sourced == 0 ]]; then
    echo "sourced: 0"
    mysh=$(echo $SHELL |sed 's#/bin/##')
else
    echo "sourced: 1"
fi

echo "shell:   ${mysh}"
echo "\$SHELL:  ${SHELL}"
echo "os:      ${os}"
echo

Any Comments ?

sha256: 14702c6f56acf7fb0c71b5e04b7c9de9264ed0dbbef43c34e34ec12fbd6e8baa