【发布时间】:2017-04-28 21:30:10
【问题描述】:
我有一个函数数组,我在 bash 的循环中调用它们。每当这些函数中的一个返回错误时,我都会跟踪它将该函数的名称存储在错误数组中以向用户显示。这是当前的工作脚本。
#!/bin/bash
funA()
{
ls -e &> /dev/null
return $?
}
funB()
{
ls -e &> /dev/null
return $?
}
funC()
{
true
return $?
}
taskNames=("task 1" "task 2" "task 3")
taskMessages=("performing task 1" "performing task 2" "performing task 3")
tasks=("funA" "funB" "funC")
progress=0
taskpercentage=33
errors=()
for i in ${!tasks[@]}; do
${tasks[i]}
if [[ $? != 0 ]]; then
errors+=(${taskNames[$i]})
fi
progress=$(expr $progress + $taskpercentage)
done
echo ${errors[@]}
exit 0
现在,我需要将循环传送到 zenity,以便向用户显示进度条。像这样的:
(
progress=0
taskpercentage=33
errors=()
for i in ${!tasks[@]}; do
echo "# ${taskMessages[$i]}"
${funcs[i]}
if [[ $? != 0 ]]; then
errors+=(${taskNames[$i]})
fi
sleep 2
progress=$(expr $progress + $taskpercentage)
echo $progress
done
echo "# All tasks completed"
) |
zenity --progress \
--no-cancel \
--title="Performing all tasks" \
--text="Performing all tasks" \
--percentage=0 \
--height 200 \
--width 500
问题是,如果我将代码包装在子 shell 中,我将无法访问 errors 变量。是否有适当的方法来执行此操作并保留对错误数组的更改?
编辑: 我不打算只打印错误数组,而是再次通过 Zenity 向用户显示,类似于:
# Show error list
message="Some of the tasks ended with errors and could not be completed."
if [[ ${#errors[@]} > 0 ]]; then
zenity --list --height 500 --width 700 --title="title" \
--text="$message" \
--hide-header --column "Tasks with errors" "${errors[@]}"
fi
【问题讨论】:
-
不需要从函数显式返回状态,默认情况下就是这样做的。