advanced/link-f.py#
The file advanced/link-f.py
is a Python script that creates hard links,
forcefully overwriting the destination if it exists.
#!/usr/bin/env python3
# Creates a link to SRC with the name DST, overwriting DST if it exists.
# This is similar to the following GNU coreutils command: ln -f SRC DST
import os
import sys
from tempfile import TemporaryDirectory
def main():
if len(sys.argv) != 3:
print("Usage: ", sys.argv[0], "SRC DST", file=sys.stderr)
return
dst = sys.argv[2]
with TemporaryDirectory(dir=os.path.dirname(dst)) as tmpdir:
tmp = os.path.join(tmpdir, os.path.basename(dst))
os.link(sys.argv[1], tmp)
os.replace(tmp, dst)
if __name__ == '__main__':
main()