Lirt
3/16/2017 - 8:08 AM

Bash specific function and syntax cheatsheet

Bash specific function and syntax cheatsheet

# Redirect stderr to stdout
find / -name foo > output.txt 2>&1
find -name test.sh 2>&1 | tee /tmp/output.txt
# Loop over array
services=(postfix dovecot saslauthd postfwd)
for s in ${services[@]}; do
  echo "$s"
done

# Infinite loop
a=0; 
while [ 1 ]; do 
  let 'a+=1'
  echo "$a"
  sleep 1
done

# Replace in bash curly substitution
echo ${VAR/test/string}    # replaces only first occurence
echo ${VAR//test/string}   # replaces all occurences

# Length of a string
echo ${#TEST}

# Trims png and appends jpg
echo "${FILENAME%png}jpg"

# Variable setting
TEST="test"
echo ${TEST-not set}       # output "test"
unset TEST
echo ${TEST-not set}       # output "not set"
echo ${TEST+set}           # outputs $TEST if it is set

# Use as separate arguments
echo {one,two,red,blue}
echo {one,two,red,blue}

# Remove extension
${filename%.*} (remove extension)

# Sequences
echo {1..10..2}
> 1 3 5 7 9
echo {10..1..2}
> 10 8 6 4 2
echo {a..z..3}
> a d g j m p s v y

# Create 2 files with one line (brace expansion)
mkdir -p /srv/{salt,pillar}

# Resources:
# http://stackoverflow.com/questions/8748831/when-do-we-need-curly-braces-in-variables-using-bash
# http://wiki.bash-hackers.org/syntax/expansion/brace
# https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html
# http://www.thegeekstuff.com/2010/06/bash-shell-brace-expansion/
# http://mfitzp.io/article/use-bash-brace-expansion-to-save-hoursdays/
# http://www.linuxjournal.com/article/7385
# http://ryanuber.com/05-12-2010/bash-variable-expansion-tricks.html
# Show timestamps in bash history
HISTTIMEFORMAT="%d/%m/%y %T "
# Exit on error
set -e
# Exit if variable was not set
set -u
# Exit when command in pipe fails
set -o pipefail
# Print every command executed with variable interpolation
set -x