bashrc Configuration – Echo $? After Specific Command

aliasbashecho

I'm familiar with setting simple aliases in my .bashrc, and think it might be capable of doing what I want, but not quite sure how to do it. The desire: always echo $? after a particular program finishes executing. The particular program I want to run this after prints out fairly awkward STDERR messages that look at first glance like an error even upon success. I always echo $? after as a first check before I actually read the stuff, but at least a quarter of the time mistype and lose the echo opportunity. What I'd like to do is set an alias so that when I type

$ foo --option [argument]

It actually does

$ foo --option [argument]

working blah blah blah

$ echo $?

Is this possible?

Best Answer

Using a function:

foo () {
    command foo "$@"
    echo "$?"
}

This will just execute the foo command with any arguments provided and then echo the exit status afterward.

You may also want to have the foo function return with the same exit status as the foo command with:

foo() {
  local ret
  command foo "$@"
  ret="$?"
  echo "$ret"
  return "$ret"
}
Related Question