summaryrefslogtreecommitdiff
path: root/eclass/eapi9-pipestatus.eclass
blob: f92afe42ef14e475349a40fd40e9832628ea1256 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Copyright 2024 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

# @ECLASS: eapi9-pipestatus.eclass
# @MAINTAINER:
# Ulrich Müller <ulm@gentoo.org>
# @AUTHOR:
# Ulrich Müller <ulm@gentoo.org>
# @SUPPORTED_EAPIS: 7 8
# @BLURB: check the PIPESTATUS array
# @DESCRIPTION:
# A stand-alone implementation of a possible future pipestatus command
# (which would be aimed for EAPI 9).  It is meant as a replacement for
# "assert".  In its simplest form it can be called like this:
#
# @CODE
# foo | bar
# pipestatus || die
# @CODE
#
# With the -v option, the command will also echo the pipe status array,
# so it can be assigned to a variable like in the following example:
#
# @CODE
# local status
# foo | bar
# status=$(pipestatus -v) || die "foo | bar failed, status ${status}"
# @CODE
#
# Caveat: "pipestatus" must be the next command following the pipeline.
# In particular, the "local" declaration must be before the pipeline,
# otherwise it would reset the status.

case ${EAPI} in
	7|8) ;;
	*) die "${ECLASS}: EAPI ${EAPI:-0} not supported" ;;
esac

# @FUNCTION: pipestatus
# @USAGE: [-v]
# @RETURN: last non-zero element of PIPESTATUS, or zero if all are zero
# @DESCRIPTION:
# Check the PIPESTATUS array, i.e. the exit status of the command(s)
# in the most recently executed foreground pipeline.  If called with
# option -v, also output the PIPESTATUS array.
pipestatus() {
	local status=( "${PIPESTATUS[@]}" )
	local s ret=0 verbose=""

	[[ ${1} == -v ]] && { verbose=1; shift; }
	[[ $# -ne 0 ]] && die "usage: ${FUNCNAME} [-v]"

	for s in "${status[@]}"; do
		[[ ${s} -ne 0 ]] && ret=${s}
	done

	[[ ${verbose} ]] && echo "${status[@]}"

	return "${ret}"
}