bash - 提高此代码性能的最佳方法是什么

时间:2015-04-12 05:18:09

标签: performance bash refactoring

我现在让我的脚本工作了,我使用了cdwn,只要当前工作目录中没有文件和只有一个目录,它就是cd。否则它会打破无限循环。我有几个为这个脚本创建的泛型函数,但是会用于其他函数,我使用了几个find命令和一个egrep。请告知如何提高性能,这主要是审查和学习bash的练习,但我想利用它。

以下函数用于检查wd中是否存在任何文件。

function checkForFilesInCurrentDir(){
    # check if there are files in the current directory
    doFilesExist=`find . -maxdepth 1 -type f`
    if [ -z "$doFilesExist" ]; then
    #   echo "no files"
        return 0 
    else
    #   echo "some files"
        return 1
    fi
}

以下函数检查dirs,然后在单独的行上打印字符串,然后使用egrep计算发生该模式的行数,有效地计算wd中的目录数。

function numOfDirsInWD(){
    # check number of dirs in working directory and return that num
    checkForDirs=`find . -mindepth 1 -maxdepth 1 -type d`
    numOfDirs=$(echo "$checkForDirs" | egrep -c "./")
    return $numOfDirs
}

以下函数是脚本本身。它打开一个无限循环,检查文件,如果它们被检测到它中断,那么它检查wd中有多少dirs,如果有多于或少于1,它就会突破循环。否则它会对唯一的目录执行ls和cd。然后在下一个目录重复。上去

function cdwn (){
    while :
    do
        # check for files
        checkForFilesInCurrentDir
        filesExist="$?"
        if [[ filesExist -eq 1 ]]; then
            echo "files exist"
            break
        fi

        # check that only one dir
        numOfDirsInWD
        numOfDirs="$?"
        if [[ numOfDirs -eq 1 ]]; then
            # cd to it
            echo "only one dir"
            name=`ls`
            cd "$name"
        else
            # break out of the loop
            echo "there is not a sole dir"
            break
        fi
    done
}

在我当前糟糕的计算机上,大约需要18秒才能关闭十个空目录...主延迟似乎是在开始时。我会在早上检查回复,被这些东西带走,现在早上6点,我就是...感谢帮助。

1 个答案:

答案 0 :(得分:2)

首先,获取这样的文件数量:

function numOfDirsInWD(){
    # check number of dirs in working directory and return that num
    checkForDirs=`find . -mindepth 1 -maxdepth 1 -type d`
    return ${checkForDirs[#]}
}

这将更快更容易。

其次,你忘了一个美元符号。用这一行替换你的:

if [[ $numOfDirs -eq 1 ]]; then

如果您遇到其他问题,请发布。

您也可以使用以下代码立即更改目录:

cd $(ls)

即如果只有一个目录。

至于你为什么陷入无限循环:如果dir中有多个文件,你会继续前进。检查文件数是否为ge 1并相应中断。因此,请将此行更改为if [[ filesExist -eq 1 ]]; thenif [[ filesExist -ge 1 ]]; then

相关问题