小编jfg*_*956的帖子

避免在 bash 中忙等待,没有 sleep 命令

我知道我可以通过执行以下操作来等待条件在 bash 中变为真:

while true; do
  test_condition && break
  sleep 1
done
Run Code Online (Sandbox Code Playgroud)

但它在每次迭代(睡眠)时创建 1 个子流程。我可以通过以下方式避免它们:

while true; do
  test_condition && break
done
Run Code Online (Sandbox Code Playgroud)

但它使用大量 CPU(忙等待)。为了避免子进程和忙于等待,我想出了下面的解决方案,但我发现它很难看:

my_tmp_dir=$(mktemp -d --tmpdir=/tmp)    # Create a unique tmp dir for the fifo.
mkfifo $my_tmp_dir/fifo                  # Create an empty fifo for sleep by read.
exec 3<> $my_tmp_dir/fifo                # Open the fifo for reading and writing.

while true; do
  test_condition && break
  read -t 1 -u 3 var                     # Same as sleep 1, but without sub-process.
done

exec …
Run Code Online (Sandbox Code Playgroud)

bash sleep shell-script

25
推荐指数
3
解决办法
3万
查看次数

Bash 脚本和大文件(错误):来自重定向的 read 内置输入给出了意外的结果

我对大文件和bash. 这是上下文:

  • 我有一个大文件:75G 和​​ 400,000,000+ 行(这是一个日志文件,我的错,我让它增长)。
  • 每行的前 10 个字符是格式为 YYYY-MM-DD 的时间戳。
  • 我想拆分那个文件:每天一个文件。

我尝试使用以下脚本不起作用。 我的问题是关于这个脚本不起作用,而不是替代解决方案

while read line; do
  new_file=${line:0:10}_file.log
  echo "$line" >> $new_file
done < file.log
Run Code Online (Sandbox Code Playgroud)

经过调试,发现问题出在new_file变量上。这个脚本:

while read line; do
  new_file=${line:0:10}_file.log
  echo $new_file
done < file.log | uniq -c
Run Code Online (Sandbox Code Playgroud)

给出了下面的结果(我把xes放在了数据保密的地方,其他字符是真实的)。注意dh和较短的字符串:

...
  27402 2011-xx-x4
  27262 2011-xx-x5
  22514 2011-xx-x6
  17908 2011-xx-x7
...
3227382 2011-xx-x9
4474604 2011-xx-x0
1557680 2011-xx-x1
      1 2011-xx-x2
      3 2011-xx-x1
...
     12 2011-xx-x1
      1 2011-xx-dh
      1 2011-xx-x1
      1 208--
      1 …
Run Code Online (Sandbox Code Playgroud)

bash

16
推荐指数
1
解决办法
3864
查看次数

如何按大小和扩展名搜索文件?

我想从目录及其所有子目录中删除具有特定扩展名的所有空文件。

command-line find search

5
推荐指数
2
解决办法
2177
查看次数

标签 统计

bash ×2

command-line ×1

find ×1

search ×1

shell-script ×1

sleep ×1