在 bash 脚本中,我有一个长时间运行的命令(例如 rsync
),有时一段时间不显示输出,所以我想做两件事:
对该命令使用微调器以显示脚本尚未卡住(即我们只是在等待输出);并且,
在完成后获取长时间运行命令的退出状态,以便稍后在脚本中进行进一步测试。
但问题是,我不太了解将进程发送到后台的处理方式,以及退出代码的处理方式,所以我不确定如何进行这项工作。
这是我目前所拥有的,感谢 @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/