You can do it easily, but it is an 3 step process. First, you must setup your bash for executing precmd
. Copying form this question, and from here you should do:
1st step - save the next into any file e.g. makelastcomm.sh
set -o functrace > /dev/null 2>&1
shopt -s extdebug > /dev/null 2>&1
preexec () {
temp=$(tty); echo "$1" >/tmp/lastcommand.${temp:5}
}
preexec_invoke_exec () {
[ -n "$COMP_LINE" ] && return # do nothing if completing
local this_command=`history 1 | sed -e "s/^[ ]*[0-9]*[ ]*//g"`;
preexec "$this_command"
}
trap 'preexec_invoke_exec' DEBUG
2nd step - source it into the current bash
source makelastcomm.sh
3rd step - you script should start as (in my examples it is called hhhqst
)
#!/bin/bash
temp=$(tty)
cat << EOF
---------------------------
SYSTEM TESTING FILE for BEPO
TIMESTAMP $( date +"%Y%m%d%H%M" )
PWD: $( pwd )
COMMAND: $(cat /tmp/lastcommand.${temp:5})
---------------------------
EOF
#your main script here
echo "running the the main script for example the date command"
LC_ALL=C date
The result. When will run hhhqst
as
bash hhhqst
will get
---------------------------
SYSTEM TESTING FILE for BEPO
TIMESTAMP 201305041939
PWD: /Users/jm/tmp
COMMAND: bash hhhqst
---------------------------
running the the main script for example the date command
Sat May 4 19:39:13 CEST 2013
when will run with a redirect for example as
./hhhqst >/tmp/hhh.out
the /tmp/hhh.out
will contain
---------------------------
SYSTEM TESTING FILE for BEPO
TIMESTAMP 201305041940
PWD: /Users/jm/tmp
COMMAND: ./hhhqst >/tmp/hhh.out
---------------------------
running the the main script for example the date command
Sat May 4 19:40:39 CEST 2013
done.
The principe. Hooking bash debug trap we put into the /tmp/lastcomm.your_terminal
the last command from the history. So, when you run the script the script only read the content from the above file.