While loop to test if a file exists in bash

前端 未结 8 540
旧巷少年郎
旧巷少年郎 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:35

    Like @zane-hooper, I've had a similar problem on NFS. On parallel / distributed filesystems the lag between you creating a file on one machine and the other machine "seeing" it can be very large, so I could wait up to a full minute after the creation of the file before the while loop exits (and there also is an aftereffect of it "seeing" an already deleted file).

    This creates the illusion that the script "doesn't work", while in fact it is the filesystem that is dropping the ball.

    This took me a while to figure out, hope it saves somebody some time.

    PS This also causes an annoying number of "Stale file handler" errors.

    0 讨论(0)
  • 2020-12-23 11:37

    I had the same problem, put the ! outside the brackets;

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

    Also, if you add an echo inside the loop it will tell you if you are getting into the loop or not.

    0 讨论(0)
提交回复
热议问题