I want a Bash one-liner that atomically creates a file if it doesn't exist. That means essentially "if file doesn't exist, create it" but ensuring that no one else manages to create the file in the small space between doing the if and creating the file.
Stealing an answer from various comments and links to [SO]. It seems there is a POSIX compliant method that doesn't involve
mkdir
as I mentioned in my original answer belowThis redirect to file returns 0 or fails and returns non-zero if the file already exists.
Original answer
You'll have to use
mkdir
- that's atomic, either the directory gets created and you can continue or it doesn't created so you take appropriate action.Of course,
mkdir
doesn't create a file but once you know you have exclusive access to the directory then you can make the file you want in it.As to a one liner - I'll leave that up to you. Personally I'd write it over a few lines, as that'll be more maintainable.
Try this one. The
ln
provides the test-and-set functionality.Is it file or directory? If file, you can use simple command touch - if file exists, it just modify last access time. If file doesn't exists, is created.
If you don't care about the filename, you can delegate this task to a utility, for example mktemp
Invocation: