1

I'm using Linux for a while and today I found an interesting thing.

Saying that I have an infinite task, which keeps writing strings into a file.

At some moment, I delete the file, and in several seconds, I recreate the file. To my surprise, I won't lose any string.

Here is how I test with bash script:

#!/bin/bash

i=0
while :
do
    echo ${i}>>./target
    sleep 1
    i=$((i+1))
done

I execute this script for 4 seconds and I can get a file name target, which contains 0, 1, 2 and 3. Then I remove the file target. And I execute touch target to create a new file in 5 seconds. To my surprise, in the new file, I get the contents 4, 5, 6, 7, 8 immediately.

So why can I get back all of the strings, which are generated during deleting the file?

1 Answer 1

6

Because touch target isn’t creating the file in this instance. The >> shell operator appends to the named file, creating if necessary. You delete the file after “3”, and the subsequent echo 4>>./target creates it.

Trying listing the file after you delete it:

rm target; sleep 1; ls -l target

and you’ll see that it’s been re-created.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .