Skip to content

Instantly share code, notes, and snippets.

@anselmobd
Last active August 11, 2022 22:55
Show Gist options
  • Save anselmobd/a8a3e2f87dd9b67121da78495093e751 to your computer and use it in GitHub Desktop.
Save anselmobd/a8a3e2f87dd9b67121da78495093e751 to your computer and use it in GitHub Desktop.
Executes a command, stores its output and prints the differences compared to the last execution (for log)
#!/bin/bash
last_out="$1"
shift
exec_cmd="$@"
script_date=$(date)
date_to_file=$(date '+%Y-%m-%d_%H.%M.%S')
base_dir=$(dirname ${last_out})
name_out=$(basename ${last_out})
file_suffix="/tmp/cmd_out_log_${name_out}"
if [[ ! -d "${base_dir}" ]] ; then
mkdir -p "${base_dir}"
fi
if [ ! -e "${last_out}" ] ; then
touch "${last_out}"
fi
out_file="${file_suffix}.out"
dif_file="${file_suffix}.dif"
rm ${out_file}.* 2> /dev/null
rm ${dif_file}.* 2> /dev/null
out_tmp=$(mktemp "${out_file}_${date_to_file}.XXXXXXXXX")
dif_tmp=$(mktemp "${dif_file}_${date_to_file}.XXXXXXXXX")
${exec_cmd} > ${out_tmp}
diff ${out_tmp} ${last_out} &> ${dif_tmp}
if (( $? == 0 )) ; then
rm ${out_tmp}
else
mv ${out_tmp} ${last_out}
echo ${script_date}
cat ${dif_tmp}
fi
rm ${dif_tmp}
@anselmobd
Copy link
Author

anselmobd commented Nov 9, 2021

Examples of use in crontab

* * * * * /opt/scripts/cmd_out_log.sh /etc/cmd_out/crontab-l /usr/bin/crontab -l >> /var/log/crontab-l.log 2>&1
* * * * * /opt/scripts/cmd_out_log.sh /etc/cmd_out/fdisk-l /sbin/fdisk -l >> /var/log/fdisk-l.log 2>&1
* * * * * /opt/scripts/cmd_out_log.sh /etc/cmd_out/blkid-olist /sbin/blkid -o list >> /var/log/blkid-olist.log 2>&1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment