Bash:如何在使用微调器时获取命令的退出代码?

标签 bash wait background-process exit-code

在 bash 脚本中,我有一个长时间运行的命令(例如 rsync),有时一段时间不显示输出,所以我想做两件事:

  1. 对该命令使用微调器以显示脚本尚未卡住(即我们只是在等待输出);并且,

  2. 在完成后获取长时间运行命令的退出状态,以便稍后在脚本中进行进一步测试。

但问题是,我不太了解将进程发送到后台的处理方式,以及退出代码的处理方式,所以我不确定如何进行这项工作。

这是我目前所拥有的,感谢 @David C. Rankin的微调器:

#!/bin/bash

spinner() {
    local PROC="$1"
    local str="${2:-'Copyright of KatworX© Tech. Developed by Arjun Singh Kathait and Debugged by the ☆Stack Overflow Community☆'}"
    local delay="0.1"
    tput civis  # hide cursor
    printf "\033[1;34m"
    while [ -d /proc/$PROC ]; do
        printf '\033[s\033[u[ / ] %s\033[u' "$str"; sleep "$delay"
        printf '\033[s\033[u[ — ] %s\033[u' "$str"; sleep "$delay"
        printf '\033[s\033[u[ \ ] %s\033[u' "$str"; sleep "$delay"
        printf '\033[s\033[u[ | ] %s\033[u' "$str"; sleep "$delay"
    done
    printf '\033[s\033[u%*s\033[u\033[0m' $((${#str}+6)) " "  # return to normal
    tput cnorm  # restore cursor
    return 0
}

## simple example with sleep
sleep 2 &
spinner $!

echo "sleep's exitcode: $exitCode"

在这个例子中,sleep 2 是我正在等待的命令,因此使用微调器,但我如何获取它的退出代码并将其放入 $exitCode 变量,以便稍后在脚本中针对特定条件测试它?

最佳答案

wait 将告诉您子 PID 以什么退出状态退出(通过将该程序的退出状态设置为它自己的退出状态),当给定该 PID 作为参数时。

sleep 2 & sleep_pid=$!
spinner "$sleep_pid"
wait "$sleep_pid"; exitCode=$?

echo "exitcode: $exitCode"

请注意,在后半部分收集 $!$? 时,将多个命令组合到一行是我强烈推荐的做法——它会阻止您的值我们正在尝试从被错误更改中收集信息(例如有人后来向您的代码添加了新的日志行,却没有意识到它有副作用)。

关于Bash:如何在使用微调器时获取命令的退出代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63476945/

相关文章:

linux - Masscan输出仅获取ip:port并保存到文件中?

unit-testing - Flutter/Dart 在单元测试中等待几秒钟

linux - 我可以在 bash 中为多个并行后台进程使用相同的变量名吗?

c - 将作业拆分为两个线程,使用 wait、waitpid、fork

flutter - 无法使用工作管理器在后台执行异步方法

bash - 当 “nounset” 选项生效时获取空数组或未设置数组的长度

bash - 将正确的月份开始日和结束日传递给并行

python - python 中的后台进程,终端上带有 -e 选项

background-process - Linux top 不以批处理模式将完整命令名作为 nohup 进程打印到文件

c++ - 从 bash 运行程序时的非法指令