Locking Files in Bash

陌路散爱 提交于 2019-12-01 21:17:42

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!