While loop to test if a file exists in bash

前端 未结 8 551
旧巷少年郎
旧巷少年郎 2020-12-23 10:37

I\'m working on a shell script that does certain changes on a txt file only if it does exist, however this test loop doesn\'t work, I wonder why? Thank you!



        
8条回答
  •  佛祖请我去吃肉
    2020-12-23 11:28

    I ran into a similar issue and it lead me here so I just wanted to leave my solution for anyone who experiences the same.

    I found that if I ran cat /tmp/list.txt the file would be empty, even though I was certain that there were contents being placed immediately in the file. Turns out if I put a sleep 1; just before the cat /tmp/list.txt it worked as expected. There must have been a delay between the time the file was created and the time it was written, or something along those lines.

    My final code:

    while [ ! -f /tmp/list.txt ];
    do
        sleep 1;
    done;
    sleep 1;
    cat /tmp/list.txt;
    

    Hope this helps save someone a frustrating half hour!

提交回复
热议问题