如何分析bash shell脚本启动缓慢? [英] How to profile a bash shell script slow startup?

查看:258
本文介绍了如何分析bash shell脚本启动缓慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的bash shell最多需要3-4秒才能启动,而如果我使用--norc启动它,它将立即运行.

My bash shell takes up to 3-4 seconds to start up, while if I start it with --norc it runs immediately.

我通过手动插入return语句并寻求提高速度来开始分析" /etc/bash.bashrc~/.bashrc,但这不是一个定量过程,而且效率不高.

I started "profiling" /etc/bash.bashrc and ~/.bashrc by manually inserting return statements and seeking for speed improvements, but it is not a quantitative process and it is not efficient.

我如何配置我的bash脚本并查看哪些命令花费最多的时间来启动?

How can I profile my bash scripts and see which commands take most time to start up?

推荐答案

如果您有GNU date(或其他可以输出纳秒的版本),请在/etc/bash.bashrc的开头(或您想要的任何位置)执行此操作在任何Bash脚本中开始跟踪):

If you have GNU date (or another version that can output nanoseconds), do this at the beginning of /etc/bash.bashrc (or wherever you'd like to begin a trace in any Bash script):

PS4='+ $(date "+%s.%N")\011 '
exec 3>&2 2>/tmp/bashstart.$$.log
set -x

添加

set +x
exec 2>&3 3>&-

~/.bashrc的末尾(或在您希望停止跟踪的任何Bash脚本的本节的末尾). \011是八进制制表符.

at the end of ~/.bashrc (or at the end of the section of any Bash script you'd like tracing to stop). The \011 is an octal tab character.

您应该在/tmp/bashstart.PID.log中获得一个跟踪日志,该日志显示已执行的每个命令的秒.nanoseconds时间戳.一次到下一次的差异是干预步骤所花费的时间.

You should get a trace log in /tmp/bashstart.PID.log that shows the seconds.nanoseconds timestamp of each command that was executed. The difference from one time to the next is the amount of time that the intervening step took.

当您缩小范围时,可以将set -x稍后和set +x稍早移动(或选择性地将几个感兴趣的部分括起来).

As you narrow things down, you can move set -x later and set +x earlier (or bracket several sections of interest selectively).

尽管它不如GNU date的纳秒级细粒度,但Bash 5包含一个以微秒为单位给出时间的变量.使用它可以避免您为每一行生成外部可执行文件,并且可以在Mac或其他没有GNU date的地方使用-当然,只要您拥有Bash 5.更改PS4的设置:

Although it's not as fine-grained as GNU date's nanoseconds, Bash 5 includes a variable which gives the time in microseconds. Using it saves you from spawning an external executable for every line and works on Macs or elsewhere that doesn't have GNU date - as long as you have Bash 5, of course. Change the setting of PS4:

PS4='+ $EPOCHREALTIME\011 '

@pawamoy指出,如果您具有Bash 4.1或更高版本,则可以使用BASH_XTRACEFD将跟踪的输出发送到单独的文件描述符.来自此答案:

As pointed out by @pawamoy, you can use BASH_XTRACEFD to send the output of the trace to a separate file descriptor if you have Bash 4.1 or later. From this answer:

#!/bin/bash

exec 5> command.txt
BASH_XTRACEFD="5"

echo -n "hello "

set -x
echo -n world
set +x

echo "!"

这将导致跟踪输出转到文件command.txt,而使stdoutstdout正常输出(或单独重定向).

This will cause the trace output to go to the file command.txt leaving stdout and stdout to be output normally (or be redirected separately).

这篇关于如何分析bash shell脚本启动缓慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆