Bash 脚本每个函数的时间和总脚本执行持续时间

Bash 脚本每个函数的时间和总脚本执行持续时间

我编写了一个 bash 脚本,并希望实现一个计时器,该计时器还将获取脚本执行持续时间的总时间以及每个循环迭代所花费的时间。例如,如果用户指定 -f 标志,该标志将在文件中的每个 IP 地址上运行脚本,而不是使用 -t 标志仅在 1 个目标上运行,我如何重置计时器,以便它返回每次 IP 扫描并返回所有 IP 扫描的总时间?这是我目前的计时器功能

#!/bin/bash

NICE='\e[1;32;92m[+]\e[0m'
TEAL='\e[96m'
END='\e[0m'
SECONDS=0

timer() {

    echo -e "${TEAL}~~~~~~~~~~~~~~~~~~~~~~~ All Scans for Completed ~~~~~~~~~~~~~~~~~~~~~~~${END}"
    echo ""

    if (($SECONDS > 3600)); then
        hours=SECONDS/3600
        let "minutes=(SECONDS%3600)/60"
        let "seconds=(SECONDS%3600)%60"
        echo -e "${NICE} Scans Completed in $hours hour(s), $minutes minute(s) and $seconds second(s)"
    elif (($SECONDS > 60)); then
        let "minutes=(SECONDS%3600)/60"
        let "seconds=(SECONDS%3600)%60"
        echo -e "${NICE} Scans Completed in $minutes minute(s) and $seconds second(s)"
    else
        echo -e "${NICE} Scans Completed in $SECONDS seconds"
    fi
    echo -e ""
}

我创建了一个 ResetTimer 函数,它只是将 SECONDS 重置为 0

resetTimer() {
    SECONDS=0
}

这几乎可以工作,因为它会显示每次扫描的单独时间,但是,由于我将 SECONDS 重置为 0,所以如果我使用重置功能,我不确定如何获取所有扫描的总时间。我确信可能有一个非常简单的解决方案,但是我一直无法找到它/弄清楚如何正确地做到这一点。

这是从文件中循环 IP 时脚本其余部分流程的非常简化的伪代码

totalTimeFunction() {
        ## ToDo: Create Total Time function that keeps track of original Starting SECONDS
        }

for target in $target_list; do
    # do stuff
    timer
    resetTimer
done
totalTimeFunction

答案1

再次感谢。我现在开始工作了。这是工作定时器功能。

timer() {

    echo -e "${TEAL}~~~~~~~~~~~~~~~~~~~~~~~ Scanning for $rhost Completed ~~~~~~~~~~~~~~~~~~~~~~~${END}"
    echo ""

    duration=$((duration + SECONDS))
    if (($SECONDS > 3600)) || (($duration > 3600)); then
        hours=SECONDS/3600
        totalhours=$duration/3600
        let "minutes=(SECONDS%3600)/60"
        let "seconds=(SECONDS%3600)%60"
        echo -e "${NICE} Scans Completed in $hours hour(s), $minutes minute(s) and $seconds second(s)"
        let "totalminutes=($duration%3600)/60"
        let "totalseconds=($duration%3600)%60"
        echo -e "${NICE} Scans Completed in $totalhours hour(s), $totalminutes minute(s) and $totalseconds second(s)"
    elif (($SECONDS > 60)) || (($duration > 60)); then
        let "minutes=(SECONDS%3600)/60"
        let "seconds=(SECONDS%3600)%60"
        echo -e "${NICE} This Scan Completed in $minutes minute(s) and $seconds second(s)"
        let "totalminutes=($duration%3600)/60"
        let "totalseconds=($duration%3600)%60"
        echo -e "${NICE} All Scans Completed in $totalminutes minute(s) and $totalseconds second(s)"
    else
        echo -e "${NICE} This Scan Completed in $SECONDS seconds"
        echo -e "${NICE} All Scans Completed in $duration seconds"
    fi
    echo -e ""
}

相关内容