Files
oam/knowledge base/bash.md
2023-02-07 16:04:57 +01:00

2.4 KiB

Bourne Again SHell

TL;DR

# Declare functions.
functionName () {}
function functionName {}

# Declare functions on a single line.
functionName () { command1 ;; command N ; }

# Print exported variables only.
export -p

# Run a command or function on exit, kill or error.
trap "rm -f $tempfile" EXIT SIGTERM ERR
trap function-name EXIT SIGTERM ERR

# Disable CTRL-C.
trap "" SIGINT

# Re-enable CTRL-C.
trap - SIGINT

# Bash 3 and `sh` have no built-in means to convert case of a string, but the
# `awk`, `sed` or `tr` tools can be used instead.
echo $(echo "$name" |  tr '[:upper:]' '[:lower:]' )
echo $(tr '[:upper:]' '[:lower:]' <<< "$name")

# Bash 5 has a special parameter expansion for upper- and lowercasing strings.
echo ${name,,}
echo ${name^^}

# Add a clock to the top-right part of the terminal.
while sleep 1
do
  tput sc;
  tput cup 0 $(($(tput cols)-29))
  date
  tput rc
done &

# Show a binary clock.
watch -n 1 'echo "obase=2; `date +%s`" | bc'

# Fork bomb.
:(){ :|: & };:

Startup files loading order

On startup:

  1. (if login shell) /etc/profile
  2. (if interactive and non login shell) /etc/bashrc
  3. (if login shell) ~/.bash_profile
  4. (if login shell and ~/.bash_profile not found) ~/.bash_login
  5. (if login shell and no ~/.bash_profile nor ~/.bash_login found) ~/.profile
  6. (if interactive and non login shell) ~/.bashrc

Upon exit:

  1. (if login shell) ~/.bash_logout
  2. (if login shell) /etc/bash_logout

Functions

A function automatically returns the exit code of the last command in it.

Check if a script is sourced by another

(return 0 2>/dev/null) && echo "this script is not sourced" || echo "this script is sourced"

Further readings

Sources