How to create shell script for a cron job with hidden debug information

Create shell script for a cron job with hidden debug information that will be shown only when execudted inside terminal.

The idea behind this is quite simple as we need to verify if stdin (file descriptor 0), stdout (file descriptor 1) or stderr (file descriptor 2) is associated with the terminal. If not then shell script is executed as a cron job, so any debug message can be omitted.

# cron job template with debug information

# display debug information 
# only if $terminal variable is set to 1
emit() {
  if [ "$terminal" -eq "1" ]; then
    printf "%s\n" "$*" 

# determine if standard input (file descriptor) is opened on a terminal
# and set $terminal variable accordingly
if [ -t 0 ] ; then

emit "Script name is $(basename $0)" 
emit "Script location is $(readlink -f $0)" 
emit "Script is executed on $TERM"
emit "Script is executed from $PWD directory"
emit "Script is executed with $USER permissions"
if [ -n "$SUDO_USER" ]; then
  emit "Script is executed using sudo by $SUDO_USER ($SUDO_UID:$SUDO_GID)"
emit "Script is using path defined as $PATH"
emit "Script LANG variable is $(locale | awk -F '=' '/LANG=/ {print $2}')"
emit "Execution start: $(date)"

# perform real operations here

emit "Execution end: $(date)"

Sample output inside terminal.

~# bash bin/
Script name is
Script location is /root/bin/
Script is executed on screen
Script is executed from /root directory
Script is executed with root permissions

Script is using path defined as /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Script LANG variable is C.UTF-8

Execution start: Tue Dec 26 13:25:50 UTC 2017
Execution end: Tue Dec 26 13:25:50 UTC 2017
Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.