4 ms·
I think its almost hilarious that something calling itself a "safe script template" doesn't even spend a couple of lines dealing with the possibility of race co
by traceroute66 6y ago
I think its almost hilarious that something calling itself a "safe script template" doesn't even spend a couple of lines dealing with the possibility of race conditions (e.g. a locking process so that if, as is almost inevitable, my script gets put in a cronjob, it doesn't run when already running).
The four lines the script wastes on setup_colors() - something that has nothing to do with "safety" - could easily be used for a basic locking process.
- michaelcampbell 6y agoWhile I find the "almost hilarious" kind of overly snarky, I have my own version of this that has the race condition check. Basically uses `mkdir $THISBIN.lock` line that gives me an atomic way to create or check for existence of a logical semaphore, and provides me with a scratch area. The trap'd cleanup function removes it (which when debugging, and I use that scratch area, is inconvenient, but <shrug>)
- twic 6y agoRead to the end before screaming. I do this: exec >>$log_file 2>&1 if ! flock --exclusive --nonblock 1 then log "unable to get exclusive lock, aborting" exit 1 fi Which redirects standard output to a log file, then tries to get an exclusive lock on it. The lock is created by the flock subprocess, but continues to exist until the script exits and closes that file descriptor. This means there can only be one process writing to a given log file at a time. For me, that is the right granularity of locking - i have several cron jobs running this script, but with different arguments, and writing to different log files.
- AdamGibbins 6y agoflock isn't all platforms unfortunately, doesn't exist on MacOS.
- twic 6y agoQuite true. On OS X, this script will do the right thing and not run until you get a proper computer.
- michaelcampbell 6y agoI like the idea of a separate lock/semaphor per input args. Haven't needed that yet but I can see where I might.
- mradzikowski 6y agoWell, I agree with your cron argument. On the other hand - sometimes I have some utility scripts, for example to trigger some processing, that I want to run multiple times at the same time, with different arguments. So lock is not a universal thing for me. (I'm the article author btw)
- michaelcampbell 6y agoSure; my template is a one-size-fits-all thing, so if I know I'm not worried about race conditions for a file I just remove that bit.
- dvfjsdhgfv 6y agoThis is my feeling, too. Race conditions, misunderstanding globbing, whitespace in path names - these are the main sources of errors in Bash scripts I come by.
- Silhouette 6y agowhitespace in path names And more generally, the arcane rules for quoting, substitutions, parameter parsing, running other processes, and how all of these interact.
- oblio 6y agoWhat's the best way to handle race conditions?