linux下bash脚本常用的十个技巧:显示执行脚本花费的时间,在脚本退出时杀死后台运行的程序,在脚本退出时跳出循环,读取命令行参数来决定循环次数

1.显示执行脚本花费的时间

网址:bash - How to get execution time of a script effectively? - Unix & Linux Stack Exchange
一种方法是在脚本外部统计花费的时间:

time yourscript.sh

另一种方法是在脚本内部进行统计:

start=`date +%s`
sleep 1
end=`date +%s`
runtime=$((end-start))
echo " total time passed : " $runtime "s"

2.在脚本退出时杀死后台运行的程序

有时候一个脚本中会运行后台程序,如:
test.py:

import time
while True:
    print("running")
    time.sleep(1)

test.sh:

python3 test.py  &
python3 test.py &
wait 

如果你按ctrl-c终止脚本,那么后台运行的这2个Python程序都不会停止,你只能手动kill:
参考:Find and kill a process in one line using bash and regex - Stack Overflow

kill $(ps aux | grep '[p]ython3 test'| awk '{print $2}')

你需要在脚本第一行加上如下内容:

trap 'kill $(ps aux | grep '"'"'[p]ython3 test'"'"' | awk '"'"'{print $2}'"'"')' EXIT

这样在脚本结束的时候,就会自动kill掉后台运行的程序

然后我看到了另外一个解决方法,在脚本的最前面加上:

trap 'kill $(jobs -p)' EXIT

这个方法比上面的还好用。

3.在脚本退出时跳出循环


代码如下:
参考网址:bash + how to exit from secondary script and from the main script on both time - Unix & Linux Stack Exchange

#trap "echo Exited!; exit;" SIGINT SIGTERM
for (( i = 0; i < 10; i++ )); do
    sleep 10  || break;
#    wait $! 
done

如果想要程序后台运行,代码如下:
参考网址:linux - How to write loop in Bash that will break on CTRL+C? - Stack Overflow

#trap "echo Exited!; exit;" SIGINT SIGTERM
for (( i = 0; i < 10; i++ )); do
    sleep 10  &
    wait $! 
done

我还看到一个有趣的回答:
按Ctrl-Z暂停脚本
kill %%
参考网址:signals - How to stop the loop bash script in terminal? - Unix & Linux Stack Exchange

4.读取命令行参数来决定循环次数

其实命令行参数是很好用的,尤其在你需要调整线程的时候,示例如下:

trap 'echo exit && kill $(ps aux | grep '"'"'[p]ython3 test'"'"' | awk '"'"'{print $2}'"'"')' EXIT
if [ "$1" != "" ]; then
    echo "Positional parameter 1 contains something"
    for ((i=1; i<=$1; i++)); do
        python3 test2.py &
    done
else
    echo "Positional parameter 1 is empty"
    exit
fi
wait 

这段代码会根据你输入的参数决定循环次数。
参考:bash - Using a variable in brace expansion range fed to a for loop - Stack Overflow

发布了502 篇原创文章 · 获赞 145 · 访问量 48万+

猜你喜欢

转载自blog.csdn.net/zhangpeterx/article/details/96278020
今日推荐