2

Similar to this: Return last command executed in shell-script.

 lastCommand=$(some command here)

Is it possible to achieve same result, but instead used inside a bash function, not a bash script?

P.S.

lastCommand mean previous command inside the function.

Bash 4.2+ solution suffices.

qeatzy
  • 226
  • 1
  • 6

1 Answers1

2

You could use xtrace, i.e. set -x to do get a history of all commands the shell executes:

setup:

xtracefile=$(mktemp)
exec 9>"$xtracefile"
BASH_XTRACEFD=9
set -x

then run whatever

foo() { echo foo; echo bar; }
foo

Now $xtracefile should contain the lines

+ echo foo
+ echo bar

and you can work with that to pick whatever you want. Note that this doesn't clear or clean up the file at any point, it'll grow indefinitely.

If you want to get rid of the + signs, assign PS4="".

ilkkachu
  • 133,243
  • 15
  • 236
  • 397