tags:

views:

112

answers:

3

I've written (well, remixed to arrive at) this Bash script

# pkill.sh
trap onexit 1 2 3 15 ERR

function onexit() {
    local exit_status=${1:-$?}
    echo Problem killing $kill_this
    exit $exit_status
}

export kill_this=$1
for X in `ps acx | grep -i $1 | awk {'print $1'}`; do
  kill $X;
done

it works fine but any errors are shown to the display. I only want the echo Problem killing... to show in case of error. How can I "catch" (hide) the error when executing the kill statement?

Disclaimer: Sorry for the long example, but when I make them shorter I inevitably have to explain "what I'm trying to do."

+2  A: 

You can redirect stderr and stdout to /dev/null via something like pkill.sh > /dev/null 2>&1. If you only want to suppress the output from the kill command, only apply it to that line, e.g., kill $X > /dev/null 2>&1;

What this does is take send the standard output (stdout) from kill $X to /dev/null (that's the > /dev/null), and additionally send stderr (the 2) into stdout (the 1).

Hank Gay
Thanks Hank. I want the echo, I just don't want the output from the kill statement if it fails.
Yar
Then what if you change the line with the kill to `kill $X > /dev/null 2>` ?
Hank Gay
Hank: To redirect *only* `stderr` the proper way would be `2>/dev/null`.
Joey
Thanks Hank, I'm marking this as plus one, marking Johannes' comment as +1 and marking Creasey's answer as best answer because it worked (though it came later).
Yar
+2  A: 
# pkill.sh
trap onexit 1 2 3 15 ERR

function onexit() {
    local exit_status=${1:-$?}
    echo Problem killing $kill_this
    exit $exit_status
}

export kill_this=$1
for X in `ps acx | grep -i $1 | awk {'print $1'}`; do
    kill $X 2>/dev/null
    if [ $? -ne 0 ]
    then
        onexit $?
    fi
done
Paul Creasey
That worked, though I don't know what the 2> does instead of the semicolon in the original....?
Yar
Sorry, I get it: to redirect only stderr. Thanks!
Yar
A: 

For my own notes, here's my new code using Paul Creasey's answer:

# pkill.sh: this is dangerous and should not be run as root!
trap onexit 1 2 3 15 ERR

#--- onexit() -----------------------------------------------------
#  @param $1 integer  (optional) Exit status.  If not set, use `$?'
function onexit() {
    local exit_status=${1:-$?}
    echo Problem killing $kill_this
    exit $exit_status
}

export kill_this=$1
for X in `ps acx | grep -i "$1" | awk {'print $1'}`; do
  kill $X 2>/dev/null
done

Thanks all!

Yar
Just as a side note, for X in `ps acx | grep -i "$1" | awk {'print $1'}`; docould be better written as for X in $(ps acx | awk '/$1/ {print $1}); do
Raphink
Thanks, I'll have to modify this script quite soon to incorporate your changes (which got eaten by the comments formatting) and the one on the question itself.
Yar