Shell 脚本:&/&&/wait/sleep/pkill -HUP -P 的复杂用法

Shell script: Complex usage with &/&&/wait/sleep/pkill -HUP -P

我正在尝试理解这个项目中的代码:https://github.com/benoitfragit/google2ubuntu/blob/master/record.sh

#!/bin/sh
# configuration file
CONFIGURATION="$HOME/.config/google2ubuntu/google2ubuntu.conf"

# default recording time
recording=5
if [ -f "$CONFIGURATION" ]; 
then
{
    # load the configuration
    . "$CONFIGURATION"

    # small security test
    if [ "$recording" = "" ];
    then
        recording=5
    fi
}
fi

# get the pid 
PID=
# kill the previous instance of rec to cascade commands
killall rec 2>/dev/null

# record during fixed seconds
( rec -r 16000 -d /tmp/voix_$PID.flac ) & pid=$!
( sleep "$recording"s && kill -HUP $pid ) 2>/dev/null & watcher=$!
wait $pid 2>/dev/null && pkill -HUP -P $watcher
exit 0;

我没看懂:. "$CONFIGURATION" # load the configuration 加载什么,运行 .conf 文件?但这不是程序?

而且最后五行我也没看懂。

( rec -r 16000 -d /tmp/voix_$PID.flac ) & pid=$! 

确定录制一个音频文件,保存到tmp/目录&什么? :)

( sleep "$recording"s && kill -HUP $pid ) 2>/dev/null & watcher=$!
wait $pid 2>/dev/null && pkill -HUP -P $watcher

这两行我没看懂

exit 0;

我认为它的意思是 "return 0",它类似于编程语言中的 "return True"。正确吗?

.命令(在C shell中也称为sourcesource也被移植到Bash中,读取在当前 shell 的上下文中以其参数命名的文件。这意味着文件中设置的任何变量都在当前 shell.

中设置

从概念上讲,登录 shell 可以:

[ -f /etc/profile ] && . /etc/profile
[ -f $HOME/.profile ] && . $HOME/.profile

等(详细信息因您的 shell 而异)。

您显示的脚本中使用了此机制。请注意,包含的文件是通过 $PATH 找到的(如果名称中没有斜线),但该文件不需要可执行(可读性就足够了)。


行:

( rec -r 16000 -d /tmp/voix_$PID.flac ) & pid=$!

运行在子shell中执行rec命令并在变量$pid中捕获子shell的PID。

( sleep "$recording"s && kill -HUP $pid ) 2>/dev/null & watcher=$!
wait $pid 2>/dev/null && pkill -HUP -P $watcher

第一行 运行s 一个子 shell 休眠一段时间 $recording 然后 运行s kill -HUP $pid 挂断 rec 命令之前在后台 运行。标准错误被发送到 /dev/null,PID 被捕获到变量 $watcher.

第二行等待 $pid 结束,将错误重定向到 /dev/null,当 returns 成功时,对 pkill -HUP -P 标识的进程执行 pkill -HUP -P =24=].

因此,第一行设置了一个看门狗定时器,以确保 rec 不会持续太久。第二行等待 rec 进程结束,并在它结束时杀死看门狗。

exit 0;

分号是多余的,但退出状态 0 表示成功,任何非零值(在 1..255 范围内)表示某种失败。另见 Exit codes bigger than 255 — possible?