我知道我可以通过执行以下操作来等待条件在 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
. 这是上下文:
我尝试使用以下脚本不起作用。 我的问题是关于这个脚本不起作用,而不是替代解决方案。
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)
给出了下面的结果(我把x
es放在了数据保密的地方,其他字符是真实的)。注意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)