使用变量时获取子shell的PID

使用变量时获取子shell的PID

我基本上试图在脚本中添加一个进度轮,以便在从数据库中提取数据时显示。

我正在调用一个通用数据库函数,该函数会回显结果,然后将结果存储在结果变量中。我能否以任何方式将其置于后台,获取 PID,然后在旋转器等待中使用该 PID?

loading_wheel(){
local process_id="$1"

spin[0]="-"; spin[1]="\\"; spin[2]="|"; spin[3]="/"

echo -n "[ Working ] ${spin[0]}"
while kill -0 $process_id 2> /dev/null
do
    for i in "${spin[@]}"
    do
        echo -ne "\b$i"
        sleep 0.1
    done
    done
    echo ""
}

# This is the command I want to background and use whilst still populating the variable.
result=$(get_db_val "$conn" "select 'test' from dual;")

# An example that works but no variable or subshell.
sleep 10 & PID=$!

loading_wheel "$PID"

答案1

foo=$(some_value_of_bar_that_takes_a_while) &您无法使用诸如;之类的构造将子 shell 设置为后台并将其输出捕获到可靠的变量中。您需要解决此限制。为了简洁起见:

loading_wheel() {
    # is defined here
}
scratch=$(mktemp); trap "rm -f $scratch" EXIT
get_db_val "$conn" "select 'test' from dual;" > $scratch &
loading_wheel $!
result="$( cat scratch )"

相关内容