gpt4 book ai didi

linux - Bash : Adding thread-capability to this bash function, 所以它更快

转载 作者:太空宇宙 更新时间:2023-11-04 12:57:59 25 4
gpt4 key购买 nike

我有一个 bash 函数,我经常用它以一种很好的格式列出文件和目录。问题是,每次我执行该功能时,数据列表最终完成大约需要 2-3 秒。

因为我调用了两次查找命令,所以需要双倍的时间。我想问一下,如何将 find 命令作为线程并行启动,然后获取输出。我认为这将使函数输出加载更快。我错了吗?

脚本:

function lsa
{
# Function to stat files and folders in current dir
# Takes first argument as directory to stat
# If no directory supplied, current dir assumed
if [ -z "$1" ];then
DIR="."
else
DIR="$1"
fi

# print directories first
printf "*** DIRECTORIES *** \n"
find "$DIR" -maxdepth 1 -type d ! -name "." -printf "%M %u %g " -exec du -sh {} \; 2> /dev/null
# print non-directories second
printf "*** FILES *** \n"

find "$DIR" -maxdepth 1 ! -type d ! -name "." -printf "%M %u %g " -exec du -sh {} \; 2> /dev/null
}

请告诉我。谢谢。

更新

随着变化:

*** DIRECTORIES *** 
[1] 6882
*** FILES ***
[2] 6883
[1]- Done find . -maxdepth 1 -type d ! -name "." -printf "%M %u %g " -exec du -sh {} \; 2> /dev/null > dirs
[2]+ Done find "$DIR" -maxdepth 1 ! -type d ! -name "." -printf "%M %u %g " -exec du -sh {} \; 2> /dev/null > non-dirs
// And then the files and dirs one after other

没有变化:

borg@borg-cube:~$lsa
*** DIRECTORIES ***
// All directories
*** FILES ***
// All files

最佳答案

通过在后台运行两个查找命令并将它们的输出保存到不同的文件,您不能拥有多线程,而是多进程。然后 wait 找到命令完成并连接输出(首先是 dirs)。

这样...

find .  -maxdepth 1 -type d ! -name "."   -printf "%M %u %g "  -exec du -sh  {} \; 2> /dev/null > dirs &
...
find "$DIR" -maxdepth 1 ! -type d ! -name "." -printf "%M %u %g " -exec du -sh {} \; 2> /dev/null > non-dirs &
...
wait
cat dirs non-dirs
....

**更新**

将末尾的 cat dirs non-dirs 替换为:

printf "*** DIRECTORIES *** \n"
cat dirs
printf "*** FILES *** \n"
cat non-dirs

关于linux - Bash : Adding thread-capability to this bash function, 所以它更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35080941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com