Let me give an example:
$ timeout 1 yes "GNU" > file1
$ wc -l file1
11504640 file1
$ for ((sec0=
date +%S
;sec> file2; done
$ wc -l file2
1953 file2
Here you can see that the command yes
writes 11504640
lines in a second while I can write only 1953
lines in 5 seconds using bash's for
and echo
.
As suggested in the comments, there are various tricks to make it more efficient but none come close to matching the speed of yes
:
$ ( while :; do echo "GNU" >> file3; done) & pid=$! ; sleep 1 ; kill $pid
3054
$ wc -l file3
19596 file3
$ timeout 1 bash -c 'while true; do echo "GNU" >> file4; done'
$ wc -l file4
18912 file4
These can write up to 20 thousand lines in a second. And they can be further improved to:
$ timeout 1 bash -c 'while true; do echo "GNU"; done >> file5'
$ wc -l file5
34517 file5
$ ( while :; do echo "GNU"; done >> file6 ) & pid=$! ; sleep 1 ; kill $pid
5690
$ wc -l file6
40961 file6
These get us up to 40 thousand lines in a second. Better, but still a far cry from yes
which can write about 11 million lines in a second!
So, **how does yes
write to file so quickly?**
Asked by Pandya
(25613 rep)
Jan 24, 2016, 05:22 AM
Last activity: Nov 2, 2021, 09:35 AM
Last activity: Nov 2, 2021, 09:35 AM