Let's say we run this script on Linux:


After running it, is there any way to retrieve the name of the last command executed?

expected output


closed as unclear what you're asking by Anthony Geoghegan, RalfFriedl, Romeo Ninov, Rui F Ribeiro, Jeff Schaller Dec 17 '18 at 23:53

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • Do you mean the last commnd to be executed or specifically the last shell script? If you run /tmp/start.sh; ls will you want ls as output or start.sh? – terdon Dec 17 '18 at 10:45
  • yes I mean - the last command that executed – yael Dec 17 '18 at 10:46
  • 2
    @yael Huh? Could you elaborate on what it is that you actually want to do, exactly? Please do so in the question itself. – Kusalananda Dec 17 '18 at 11:23
  • 1
    Can you explain what you are trying to do. This seems like an AB question. That is you are trying to do A, can see that you can do it via B, and ask how to do B. It may be easier to just do A. – ctrl-alt-delor Dec 17 '18 at 12:01
  • 1
    It really isn't simple. For one thing, how do you define previous? What if another user ran something in a different session? What if the same user ran something but in a different session (e.g. another terminal)? Which command should be found then? – terdon Dec 17 '18 at 13:36

Using history expansion in an interactive bash shell:

$ /some/path/script.sh
$ printf 'Basename of last command line: %s\n' "$(basename "!!")"
printf 'Basename of last command line: %s\n' "$(basename "/some/path/script.sh")"
Basename of last command line: script.sh

The !! is a history expansion event designator, which will be replaced by the last command. See the "HISTORY EXPANSION" section in your bash manual.

Note that !! will expand to the full command line.

In a shell script, you always know what the previous script was called, because you just typed it in.


echo 'script.sh just finished'
  • Note also that this will only work in an interactive shell. – terdon Dec 17 '18 at 10:54

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