0

Followup to "whatis" returns 0 for missing commands, I am trying to modify /usr/bin/whatis to return a non-zero exit code after an inappropriate command has been entered. My approach to doing this is to add a return variable in the following segment, and return that variable after the end of the loop

while [ "$1" != "" ]
do
    found=0
    for d in /var/cache/man $manpath /usr/lib
    do
        if [ -f $d/whatis ]
        then
            if grep -"$grepopt1" "$grepopt2""$1" $d/whatis
            then
                found=1
            fi
        fi
    done

    if [ $found = 0 ]
    then
        echo "$1: nothing appropriate"
        **code=1**
    fi

    shift
done | eval ${PAGER:-more -E}
**return $code**

However, since the while loop is piped into eval, it is run in a subshell so code will not be assigned outside the while loop. I have tried multiple different methods, however, these are all about piping a value INTO the while loop, not piping a value out of the while loop.

A workaround I found is simply removing the entire eval statement, but I would like a method that preserves the original extensibility of whatis

1

PIPESTATUS is an array. Since you only need $[PIPESTATUS[0]}, the subscript can be omitted.

(
    code=0
    while [ "$1" != "" ]
    do
        found=0
        for d in /var/cache/man $manpath /usr/lib
        do
            if [ -f $d/whatis ]
            then
                if grep -"$grepopt1" "$grepopt2""$1" $d/whatis
                then
                    found=1
                fi
            fi
        done

        if [ $found = 0 ]
        then
            echo "$1: nothing appropriate"
            code=1
        fi

        shift
    done
    exit $code
) | eval ${PAGER:-more -E}
return $PIPESTATUS

From man bash:

   PIPESTATUS
          An array variable (see Arrays below) containing a list  of  exit
          status  values  from the processes in the most-recently-executed
          foreground pipeline (which may contain only a single command).
  • Trying to return $PIPESTATUS gives the following error $ whatis hi hi: nothing appropriate /usr/local/bin/whatis: line 92: return: can only `return' from a function or sourced script However, doing exit $PIPESTATUS instead of return works fine – Max Coplan Jan 30 at 15:25
  • I never ran your script. Nor did I attempt to correct any errors you may have made. I did not think you ask me to. You asked how to read the value of the variable code after the pipe completes, which is what I put in my answer. If you want someone to write your script, ask a new question. Also, if you desire, feel free to edit both your question and/or my answer. Or, post your own answer. – David Anderson Jan 30 at 17:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .