I have a bash script that makes a cURL request and writes the output to a file called resp.txt
. I need to create an exclusive lock so that I can write to that file and not worry about multiple users running the script and editing the text file at the same time.
Here is the code that I expect to lock the file, perform the request, and write to the text file:
(
flock -e 200
curl 'someurl' -H 'someHeader' > resp.txt
) 200>/home/user/ITS/resp.txt
Is this the correct way to go about this? My actual script is a bit longer than this, but it seems to break when I add the flock
syntax to the bash script.
If someone could explain how these file descriptors work and let me know if I am locking the file correctly that would be awesome!
EXAMPLES
in theflock(1)
manual page. These work well. They are:(; flock -n 9 || exit 1; # ... commands executed under lock ...; ) 9>/var/lock/mylockfile
and[ ${FLOCKER} != $0 ] && exec env FLOCKER="$0 flock -en $0 $0 $@ ||
. – Adam Monsen Nov 17 '23 at 18:27