History Command Inside Shell Script Issue Resolved

Here is an Scenario that i would like to get one email from each and every Linux host with root executed commands.  Looks very easy that simply run history command and grep the output by today’s date and send an email. That’s so super but do you know history command if you run directly it works. If you embed the same as shell / bash script it does not give any output..!!! 🙂 . So in this article i will show How To Run History Command Inside Shell Script Issue Resolved. 

History Command Inside Shell Script

I tried like blelow

#!/bin/bash
## To Grep History Command Output and Send Email
## Date: 11th Aug 2017
## Author: Ankam Ravi Kumar
## WebSite: https://arkit.co.in

DATE=`date "+%a %b %Y"`

history |grep "$DATE" > /tmp/histemp
COUNT=`cat /tmp/histemp |wc -l`
if [ $COUNT -ge ` ]; then
echo "Someone Run Command(s) as Root USer cat /tmp/histemp" | mail -s "Root User Command Log `date +%D-%M-%Y`"
else
echo "No Commands run as root"
fi

when i execute above script output file does not have single command run as root, but when i executed history command as mentioned below has so many commands.

# history |grep "DATE"

Then what is missing i scratched my head i did not find a clue. Script is correct and it does not have much complex in it. If i debug this shell script does not found single error.

I read so many web articles and found history command does not provide output when you include in bash script

Here is an way History Command Inside Shell Script

#!/bin/bash
# History Command Inside Bash
set -o history
HIST=$(history);
echo "$HIST" > /tmp/history

Now execute above script as mentioned below

# source hist.sh

Schedule History Command Collection using crontab

59 23 * * * source /scripts/hist.sh

Everyday based on above script output we can correlate and get emails with root command log

#!/bin/bash
## Working History Command Inside Bash Script

# Mail list
MAILLIST="YOUREMAILID"

# Daily root history commands
DATE=`date "+%a %d %b %Y"`

# Log path
AUDLOG="/var/log/commandhistory.log"

cat /tmp/history > $AUDLOG
cat $AUDLOG |grep "$DATE" > /tmp/histemp

# Mail notification
COUNT=`cat /tmp/histemp | wc -l`
if [ $COUNT -ge 1 ]; then
/bin/egrep '/sbin|init.d|vim|vi|mv|rm|chown|chmod' /tmp/histemp |mail -s "IT DEV HOST $HOSTNAME - `whoami` DAILY COMMANDS LOG" ${MAILLIST}
else
echo "NO Command executed as root today `date "+%a %d %b %Y"`" > $AUDLOG
fi

That’s it. It worked for me.

Conclusion: 

History command is not execute in interactive shells. You have to try above method to capture history command output to another file. That’s how i resolved History Command Inside shell Script.

Related Articles

Debug Shell Script Easily

 Delete blank Lines from File AWK Script

Become an Expert in Shell Scripting Read this book

Thanks for your wonderful Support and Encouragement