获取函数和 tee 输出的 return 值
Get return value of function and tee output
我想 运行 一些命令并让所有输出到 stdout 另外我想将最后 10K 字节连同一起发送到 hc-ping.com
状态。
我的输出正常,但我似乎丢失了状态代码。我不太确定 $?
指的是哪个命令 - 是 管道中的前一个命令 还是 开头的命令?
无论如何,我想从 main()
.
捕获 return 或 退出值
我该怎么做?
#!/usr/bin/env -S bash -fuo pipefail
hc_ping='https://hc-ping.com/xxx'
curl -fsS -m 10 -o /dev/null --retry 5 "$hc_ping/start"
main() {
echo "do stuff"
return 5
}
main |& tee /dev/tty | tail --bytes=10000 | curl -fsS -m 10 -o /dev/null --data-binary @- --retry 5 "$hc_ping/$?"
N.B。如果 bash 没有所需的功能,zsh
的解决方案也很好。
我不认为你可以把它做成单行;当时 shell 是
整合管道并解析 $?
,main()
尚未开始。
此外,管道中的后续进程(例如 curl
)可能会在 main
完成之前启动。
你能把它分成两个命令吗?
mainout=$(main |& tee /dev/tty | tail --bytes=10000; exit ${PIPESTATUS[0]})
mainret=$?
curl -fsS -m 10 -o /dev/null --data-binary @- --retry 5 \
"$hc_ping/${mainret}" <<< "${mainout}"
因为你在 10K 时切断输出,你不应该达到任何
现代 shells 中变量的实现限制。请注意,命令替换 $(...)
将 trim 任何尾随换行符。
我会按照@Gairfowl 的回答做一些事情,但使用命名管道。
mkfifo p
# Blocks until anything is written to the named pipe "p".
# Run in the background so we can call main and write to p.
tail --bytes=10000 p |
curl -fsS -m 10 -o /dev/null --data-binary @- --retry 5 "$hc_ping/$?" &
# Write both to p and standard output
main | tee p
# And get the exit status of main, not tee
echo "${PIPESTATUS[0]}"
我想 运行 一些命令并让所有输出到 stdout 另外我想将最后 10K 字节连同一起发送到 hc-ping.com
状态。
我的输出正常,但我似乎丢失了状态代码。我不太确定 $?
指的是哪个命令 - 是 管道中的前一个命令 还是 开头的命令?
无论如何,我想从 main()
.
我该怎么做?
#!/usr/bin/env -S bash -fuo pipefail
hc_ping='https://hc-ping.com/xxx'
curl -fsS -m 10 -o /dev/null --retry 5 "$hc_ping/start"
main() {
echo "do stuff"
return 5
}
main |& tee /dev/tty | tail --bytes=10000 | curl -fsS -m 10 -o /dev/null --data-binary @- --retry 5 "$hc_ping/$?"
N.B。如果 bash 没有所需的功能,zsh
的解决方案也很好。
我不认为你可以把它做成单行;当时 shell 是
整合管道并解析 $?
,main()
尚未开始。
此外,管道中的后续进程(例如 curl
)可能会在 main
完成之前启动。
你能把它分成两个命令吗?
mainout=$(main |& tee /dev/tty | tail --bytes=10000; exit ${PIPESTATUS[0]})
mainret=$?
curl -fsS -m 10 -o /dev/null --data-binary @- --retry 5 \
"$hc_ping/${mainret}" <<< "${mainout}"
因为你在 10K 时切断输出,你不应该达到任何
现代 shells 中变量的实现限制。请注意,命令替换 $(...)
将 trim 任何尾随换行符。
我会按照@Gairfowl 的回答做一些事情,但使用命名管道。
mkfifo p
# Blocks until anything is written to the named pipe "p".
# Run in the background so we can call main and write to p.
tail --bytes=10000 p |
curl -fsS -m 10 -o /dev/null --data-binary @- --retry 5 "$hc_ping/$?" &
# Write both to p and standard output
main | tee p
# And get the exit status of main, not tee
echo "${PIPESTATUS[0]}"