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.

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="".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.