如果管道中的第一个命令失败则返回

时间:2021-01-22 02:58:03

标签: bash shell pipe

如果管道中的第一个命令失败,是否有可能以某种方式返回?使用 pipefail 选项,返回值会被保留,但管道仍然运行到最后一个命令。 所以在这个例子中 read 至少执行一次。

set -o pipefail
shopt -s lastpipe

function_() {
  #I am doing read at least once even if somecmd failed
  somecmd |
  while IFS=':' read -r line || return; do
    :
  done
}

没有像这样将其保存到变量中?

function_() {
  #do something only if somecmd returned with 0
  someout=$(somecmd) || return

  while IFS=':' read -r line || return; do
    :
  done <<< "$someout"
}

0 个答案:

没有答案