0

Is it possible to trap error (unknown command) from the CLI, and do something in the case an error occured ?

To be more precise, I search a way to do something like this:

if [ previousCommandFails ] ; then
  echo lastCommand >> somewhere.txt
fi

Echo is just an example to say that I need to access this lastCommand.

I want it to be a default behaviour in my computer, so the code must be placed somewhere like ~/.bashrc.

Bonlou
  • 472
  • 2
  • 9
  • You should check if the command exists before using it with `command -v`. Possible duplicate of [How to check if a program exists from a Bash script?](https://stackoverflow.com/q/592620/608639), [How to check if command exists in a shell script?](https://stackoverflow.com/q/7522712/608639), etc. – jww Apr 17 '19 at 10:36

2 Answers2

1

You can try the following solution. I don't guarantee that it's a good solution but it may help with your case.

Create a small script which can test the previous command i.e. test.sh with content:

if [ $? -ne 0 ] then history 1 >> /path/to/failed_commands.txt fi

Then set this variable:

PROMPT_COMMAND+="source /path/to/test.sh"

PROMPT_COMMAND If set, the value is executed as a command prior to issuing each primary prompt.

Ardit
  • 1,522
  • 17
  • 23
0

It depends on what you call fail. If it is just returning a non 0 value, I am afraid that you have to explicitely test it after each command, or use a specialized shell (*).

But trap can be used to execute a specific command when a signal is received:

trap action signal

If this is not enough, you will have to get the source of a shell (posix shell or bash) and tweak it for meet you needs...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • I should take a look at `trap`, thanks ! I want it to catch `unknown command` to be more precise. – Bonlou Apr 17 '19 at 10:16