It is somewhat desirable to have a Bash script run forever; typical use case is for a long-running Docker container that backgrounds the service, and the startup script (e.g., invoked via the ENTRYPOINT
command) needs to be kept alive (terminating the script would result in the process known-as “the container” to terminate too).
I have seen very often this pattern:
# Run forever tail -f /dev/null
Now, don’t get me wrong, it does the job and once you know what it does, I guess one goes, “oh, yeah, I see” – but it’s a “hack” in the sense that one is using two meaningful features (the ability of “following” a file’s tail; and a “null sink” for file reads/writes) and mashing them to do something they never were intended to.
It also causes “cognitive burden” on the reader of your code – not to mention, it’s just plain ugly (at least to me).
IMHO it is much preferable to be explicit in your coding intentions, as it makes the code easier to read, maintain and upgrade: this works equally well, and I am sure no-one ever will be in any doubt as to what it does:
while (true);do sleep 5 done
Sure, it is a few keystrokes more, but it saves the dumb comment, and is also future-proof.
Of course, even better, would be to give your co-workers, and users, a much better experience:
#!/bin/bash # Trap Ctrl-c trap terminate INT function terminate() { echo "Exiting now." exit 0 } echo "Running forever (hit Ctrl-C to exit) ..." while(true); do sleep 5 done
Code is usually written once (hopefully!) but read and modified many (many!) times: it is always worth to make a little bit of extra effort to be kind to your future self and the folks who will be inheriting your code one day.
Not to mention, have a bit of self-respect, dude, won’t ya? 🙂
Leave a Reply