co89757
4/28/2016 - 11:28 PM

bash strict mode and tips for debugging

bash strict mode and tips for debugging


### "bash strict mode" quit on any non-zero exit status early  
## see http://redsymbol.net/articles/unofficial-bash-strict-mode/ 
set -euo pipefail
trap "echo 'error: Script failed: see failed command above'" ERR
export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'

#For general debugging purposes you can also define a function and a variable to use:
debugme() {
 [[ $script_debug = 1 ]] && "$@" || :
 # be sure to append || : or || true here or use return 0, since the return code
 # of this function should always be 0 to not influence anything else with an unwanted
 # "false" return code (for example the script's exit code if this function is used
 # as the very last command in the script)
}

#This function does nothing when script_debug is unset or empty, but it executes the given parameters as commands when script_debug is set. Use it like this: 
script_debug=1
# to turn it off, set script_debug=0

debugme logger "Sorting the database"
database_sort
debugme logger "Finished sorting the database, exit code $?"


# Use logger to log to syslog in /var/log/ usage

#To log a message contained in the /var/log/myapp.log file, use:
logger -f /var/log/myapp.log

#Log the message to standard error (screen), as well as the system log:
logger -s "Hard disk full"

 #To display CRs (these are only a few examples)

  #in VI/VIM: :
  set list
  #with cat(1): 
  cat -v FILE


######### Colored output to console ###### 
#ANSI escape codes:

#Black        0;30     Dark Gray     1;30
#Red          0;31     Light Red     1;31
#Green        0;32     Light Green   1;32
#Brown/Orange 0;33     Yellow        1;33
#Blue         0;34     Light Blue    1;34
#Purple       0;35     Light Purple  1;35
#Cyan         0;36     Light Cyan    1;36
#Light Gray   0;37     White         1;37
#And then use them like this in your script:

RED='\033[0;31m'
NC='\033[0m' # No Color
printf "I ${RED}love${NC} Stack Overflow\n" ## print love in red 

print_err()
{
 RED='\033[0;31m'
 LITEGRAY='\033[0;37M'
 echo "${RED}ERROR: ${LITEGRAY} '$(printf $@)' ";
}