bash script: how to save return value of first command in a pipeline?

送分小仙女□ 提交于 2019-12-10 02:41:51

问题


Bash: I want to run a command and pipe the results through some filter, but if the command fails, I want to return the command's error value, not the boring return value of the filter:

E.g.:

if !(cool_command | output_filter); then handle_the_error; fi

Or:

set -e
cool_command | output_filter

In either case it's the return value of cool_command that I care about -- for the 'if' condition in the first case, or to exit the script in the second case.

Is there some clean idiom for doing this?


回答1:


Use the PIPESTATUS builtin variable.

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).




回答2:


If you didn't need to display the error output of the command, you could do something like

if ! echo | mysql $dbcreds mysql; then
    error "Could not connect to MySQL. Did you forget to add '--db-user=' or '--db-password='?"
    die "Check your credentials or ensure server is running with /etc/init.d/mysqld status"
fi

In the example, error and die are defined functions. elsewhere in the script. $dbcreds is also defined, though this is built from command line options. If there is no error generated by the command, nothing is returned. If an error occurs, text will be returned by this particular command.

Correct me if I'm wrong, but I get the impression you're really looking to do something a little more convoluted than

[ `id -u` -eq '0' ] || die "Must be run as root!"

where you actually grab the user ID prior to the if statement, and then perform the test. Doing it this way, you could then display the result if you choose. This would be

UID=`id -u`
if [ $UID -eq '0' ]; then
    echo "User is root"
else
    echo "User is not root"
    exit 1 ##set an exit code higher than 0 if you're exiting because of an error
fi



回答3:


The following script uses a fifo to filter the output in a separate process. This has the following advantages over the other answers. First, it is not bash specific. In particular it does not rely on PIPESTATUS. Second, output is not stalled until the command has completed.

$ cat >test_filter.sh <<EOF
#!/bin/sh

cmd()
{  
    echo $1
    echo $2 >&2
    return $3
}

filter()
{  
    while read line
    do     
            echo "... $line"
    done
}

tmpdir=$(mktemp -d)
fifo="$tmpdir"/out
mkfifo "$fifo"

filter <"$fifo" &
pid=$!
cmd a b 10 >"$fifo" 2>&1
ret=$?
wait $pid
echo exit code: $ret
rm -f "$fifo"
rmdir "$tmpdir"
EOF
$ sh ./test_filter.sh
... a
... b
exit code: 10


来源:https://stackoverflow.com/questions/5955644/bash-script-how-to-save-return-value-of-first-command-in-a-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!