gpt4 book ai didi

bash - 如何在 bash 脚本中重写 while 循环以防止创建临时文件?

转载 作者:行者123 更新时间:2023-11-29 09:38:30 24 4
gpt4 key购买 nike

我认为生成临时文件可能会更慢,如果用户按 ctrl+c 临时文件将变成垃圾。

这是我的原始代码

for f in bin/* ; do
ldd $f 2>/dev/null | awk '{print $1}'
done | sort -u | grep -v -e '^not$' -e 'ld-linux' > list.1
while read soname ; do
process_so_name $soname
done < list.1

是否可以删除临时文件 list.1?

最佳答案

不用临时文件就可以了。将最后一个 grep 的结果传送到 while 中。

您可以连接到 SIGINT 来检测 Ctrl+C,但如果不需要,为什么还要担心呢?您仍然无法连接到 SIGKILL。

for f in bin/* ; do
ldd $f 2>/dev/null | awk '{print $1}'
done | sort -u | grep -v -e '^not$' -e 'ld-linux' | while read soname ; do
process_so_name $soname
done

您可以通过将循环放在函数中使它看起来更容易识别(您可以在脚本文件中或直接在 shell 中执行此操作):

step_1() {
for f in bin/* ; do
ldd $f 2>/dev/null | awk '{print $1}'
done
}

step_2() {
while read soname ; do
process_so_name $soname
done
}

step_1 | grep -v -e '^not$' -e 'ld-linux' | step_2

要连接到 SIGINT,请执行以下操作:

trap "echo SIGINT; rm -f tempfile; exit -1" INT

要连接到 SIGTERM(请参阅下面的注释),请执行以下操作:

trap "echo SIGTERM; rm -f tempfile; exit -1" EXIT

关于bash - 如何在 bash 脚本中重写 while 循环以防止创建临时文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14533798/

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