Retrieving previous command in a script

i know from the command line, the symbol $_ is used to get the last command that was run.

however, id like to replicate this within a script.

meaning, how do i do something like this:

#!/bin/sh
ps -ef | egrep talling
StoreThisLastCommandA=$_
awk '/error/ {print $3}' /tmp/test
StoreThisLastCommandB=$_

My goal is to have the variable StoreThisLastCommandA contain

 ps -ef | egrep talling 

since that is the last command ran at that point in the script.

Likewise, I want the variable StoreThisLastCommandB to contain

awk '/error/ {print $3}' /tmp/test

because, again, that is the last command kicked off at that point.

And the question is ...? You may want to refer to your shell's man page for an explanation of that special parameter.

Please become accustomed to provide decent context info of your problem.
It is always helpful to carefully and detailedly phrase a request, and to support it with system info like OS and shell, related environment (variables, options), preferred tools, adequate (representative) sample input and desired output data and the logics connecting the two, and, if existent, system (error) messages verbatim, to avoid ambiguities and keep people from guessing.

The OS is any Unix system and I intend to use it across all platforms.

But if you need me to narrow it down:

OS:
RedHat
CentOS
Fedora
AIX
Raspian
Ubuntu

Shell: 
/bin/sh

I'm afraid that with /bin/sh you're out of luck: It doesn't offer the $_ special parameter (according to its man page) nor the history command that e.g. bash provides.

Hello SkySmart,

Could you please try the following script and let me know if this helps you.

cat script.ksh
trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
ps -ef | egrep talling
StoreThisLastCommandA=$previous_command
awk '/error/ {print $3}' /tmp/test
StoreThisLastCommandB=$previous_command
##Printing the variables values here.
echo "Value of variable StoreThisLastCommandA is: " $StoreThisLastCommandA
echo "Value of variable StoreThisLastCommandB is:" $StoreThisLastCommandB

Since I don't have sh with me so I haven't tested it though I believe it should work properly, kindly do let me know on same.

Thanks,
R. Singh

2 Likes

Another technique:
Store the command first, put it into 'ticks'. A tick within ticks is escaped '\'' .
When running the command "eval" lets pipes semicolons etc. work.

#!/bin/sh
CommandA='ps -ef | egrep talling'
eval $CommandA
CommandB='awk '\''/error/ {print $3}'\'' /tmp/test'
eval $CommandB

Or, store the commands in a separate file or have them in a here document,
and read/run them line by line

#!/bin/sh
while read cmdline
do
  eval $cmdline
done <<'_EOF'
ps -ef | egrep talling
awk '/error/ {print $3}' /tmp/test
_EOF
1 Like