| #!/bin/bash |
| # Copyright 2025 The Fuchsia Authors. All rights reserved. |
| # Use of this source code is governed by a BSD-style license that can be |
| # found in the LICENSE file. |
| |
| # This script wraps a command and verifies that it exits with an expected |
| # code. |
| |
| set -euo pipefail |
| |
| EXPECTED_EXIT_CODE=0 |
| COMMAND=() |
| |
| usage() { |
| cat <<EOF |
| Usage: $0 [options] -- <command> |
| |
| Wraps a command and checks its exit code. |
| |
| Options: |
| -h, --help Show this help message. |
| --expected_exit_code <code> The expected exit code of the command. [default: 0] |
| EOF |
| } |
| |
| while [[ $# -gt 0 ]]; do |
| case "$1" in |
| -h|--help) |
| usage |
| exit 0 |
| ;; |
| --expected_exit_code) |
| EXPECTED_EXIT_CODE="$2" |
| shift 2 |
| ;; |
| --expected_exit_code=*) |
| EXPECTED_EXIT_CODE="${1#--expected_exit_code=}" |
| shift |
| ;; |
| --) |
| shift |
| COMMAND=("$@") |
| break |
| ;; |
| *) |
| echo "Unknown option: $1" >&2 |
| usage >&2 |
| exit 1 |
| ;; |
| esac |
| done |
| |
| if [[ ${#COMMAND[@]} -eq 0 ]]; then |
| echo "Error: Missing command. Use '--' to separate options from the command." >&2 |
| usage >&2 |
| exit 1 |
| fi |
| |
| actual_exit_code=0 |
| "${COMMAND[@]}" || actual_exit_code=$? |
| |
| if [[ "${actual_exit_code}" -ne "${EXPECTED_EXIT_CODE}" ]]; then |
| echo "Command returned exit code ${actual_exit_code}, but expected ${EXPECTED_EXIT_CODE}" >&2 |
| echo "Command: ${COMMAND[@]}" >&2 |
| exit 1 |
| fi |
| |
| exit 0 |