Carlos Sanchez
Carlos Sanchez

Reputation: 81

How can I replace "bash: $COMMAND: command not found" message?

Any help would be appreciated.

Basically, I want to replace:

~]$ obvfake
bash: obvfake: command not found

With:

~]$ obvfake
[*] command not found

Thanks.

Upvotes: 8

Views: 3380

Answers (4)

Rajiv Sharma
Rajiv Sharma

Reputation: 1

As suggested by chepner... you can customize the default message by replacing the bash function (handles Signal 127 or command-not-found functionality) with the one designed by you and include that function in .bashrc script.

# function that handles command-not-found message.
command_not_found_handle() {

 echo -e "My Friend, '$1' is a typo. Please correct it and re-enter the command."  
  return 127

}

You also can check this at: http://bitdiffferent.com/command-not-found/

Upvotes: -1

Saucier
Saucier

Reputation: 4360

I'd simply redirect errors to /dev/null. If obvfake returns an exit code greater than 0 then it will echo your custom error message.

obvfake 2>/dev/null || echo "[*] command not found"

This might be a little be too general since it will not distinguish between error codes. So we could check for a specific exit code.

obvfake 2>/dev/null || {
    if (( $? == 127 )); then
        echo "[*] command not found"
    fi
}

If I'd want to check a lot of error codes I'd replace the if expression with a case statement. For the ease of use you could integrate that functionality inside your script and maybe wrap it up into a function to reuse it at various points of failure.

You pretty much want to know more about redirection in bash. :)

EDIT: I guess I misinterpreted the original question. I thought obvfake is a custom script complaining about commands being called but not found on the system.

Upvotes: 0

chepner
chepner

Reputation: 531125

bash version 4 introduces a hook for handling missing commands; add the following to your .bashrc file.

command_not_found_handle () {
    printf "[*] command not found\n"
    return 127
}

Upvotes: 9

perreal
perreal

Reputation: 97948

You can write this to your .bashrc:

function error_handler {
  if [ $? -eq 127 ]; then
      echo "[*] command not found"
  fi  
}

trap 'error_handler' ERR 

This will still show the bash: obvfake: command not found though. You can suppress this by doing:

obvfake 2> /dev/null

Upvotes: 3

Related Questions