4

I have a Problem to find a good concept on locking files in bash,

Basically I want to achieve the following:

  1. Lock File
  2. Read in the data in the file (multiple times)
  3. Do stuff with the data.
  4. Write new stuff to the file (not necessarily to the end)
  5. Unlock that file

Doing this with flock seems not possible to me, because the file descriptor will just move once to the end of the file.

Also creating a Tempfile fails, because I might overwrite already read lines which is also not possible.

Edit:
Also note that other scripts I do not control might try to write to that file.

So my question is how can I create a lock in step 1 so it will span over steps 2,3,4 till I unlock it again in step 5?

4
  • Given a file, you can create a temp file.lock in the step 1 and remove it on step 5. In steps 2-4, check if file.lock exists.
    – fedorqui
    Mar 19, 2014 at 13:10
  • hmm maybe I need to edit this question a bit! I cannot be sure that another tool not my script is accessing it!
    – mjb4
    Mar 19, 2014 at 13:11
  • if the file is there and "another tool" has valid permission to read/write it, you cannot avoid that to happen in your script. You may consider changing the permission of the file, if you could, or rename/mv the file to a safe place and do your operation on it, after all things done, move/rename the file to its original name/location.
    – Kent
    Mar 19, 2014 at 13:16
  • @Kent I know that I cannot block a programm as locks are not mandatory. But I still want to lock that file. Althought a move might work there might be unwanted side effects like loosing that file if the script is stopped or the computer shuts down
    – mjb4
    Mar 19, 2014 at 13:20

1 Answer 1

3

You can do this with the flock utility. You just need to get flock to use a separate read-only file descriptor, i.e. open the file twice. E.g. to sort a file using a intermediate temporary file:

(
    flock -x -w 10 100 || exit 1

    tmp=$(mktemp)

    sort <"$file" >"$tmp"

    cat "$tmp" > "$file"

    rm -f "$tmp"
) 100<"$file"

flock will issue the flock() system call for your file and block if it is already locked. If the timeout is exceeded then the script will just abort with an error code.

1
  • interessting was looking into flock yesterday already but it did not work. Anyway altering your solution worked fine!
    – mjb4
    Mar 19, 2014 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.