Bash脚本,陷阱功能不起作用

时间:2015-04-17 23:51:19

标签: bash shell bash-trap

我编写了一个shell脚本,它运行大型模拟并将内容存储到临时文件中。收到trap后,我使用了SIGINT命令进行清理。问题是,清理工作没有发生。我使用-x选项运行调试,并且rm命令已执行。尽管如此,该文件仍然存在。

代码:

exit_prog() {
    rm tmp
    exit 0
}

print_sim_params() {
    echo "$cur_sz"
}

run_sim() {
    cur_sz="$min"
    while [ "$cur_sz" -le "$max" ]; do



        ./sim "$cur_sz"  | awk '{ print $1, " ", $11 >> "tmp" }' &
        wait
        cur_sz=`expr $step + $cur_sz`
    done
    wait
}

trap exit_prog SIGINT
trap print_sim_params SIGUSR1

当与-x选项一起使用时,这是输出的一部分,因为您可以看到exit_prog被调用。

+ run_sim
+ cur_sz=100
+ '[' 100 -le 110 ']'
+ ./sim 100 10000
+ wait
+ awk '{ print $1, " ", $11 >> "tmp" }'
++ expr 1 + 100
+ cur_sz=101
+ '[' 101 -le 110 ']'
+ ./sim 101 10000
+ wait
+ awk '{ print $1, " ", $11 >> "tmp" }'
++ exit_prog
++ rm tmp
++ exit 0

1 个答案:

答案 0 :(得分:2)

如果您向-f来电添加rm标记,该怎么办?

exit_prog() {
    rm -f tmp.state
    exit 0
}

您也可以从rm电话中退回退出代码,看看发生了什么:

exit_prog() {
    rm -f tmp.state
    exit $?
}
相关问题