Skip to content

Instantly share code, notes, and snippets.

@danielrosehill
Created April 30, 2025 13:47
Show Gist options
  • Save danielrosehill/270d11f09729283ba2f712758f550586 to your computer and use it in GitHub Desktop.
Save danielrosehill/270d11f09729283ba2f712758f550586 to your computer and use it in GitHub Desktop.
CGPT authored NTS: overwriting files in Linux w/o manual recreation

πŸ“„ How to Efficiently Overwrite a File in Linux (Without Deleting First)

When updating a script or config file on a Linux system, you do not need to delete it first. Simply overwrite it using any of the following methods:


βœ… 1. Overwrite with cp (Most Common)

sudo cp new-version.py /usr/local/bin/fetch_waqi.py

This will replace the contents of the target file.

Make it executable if needed:

sudo chmod +x /usr/local/bin/fetch_waqi.py

βœ… 2. Overwrite with mv (Renaming or Moving)

sudo mv new-version.py /usr/local/bin/fetch_waqi.py

This moves (renames) the file and replaces the target.


βœ… 3. Overwrite via Shell Redirect (Quick from CLI)

sudo tee /usr/local/bin/fetch_waqi.py > /dev/null <<EOF
#!/usr/bin/env python3
print("Updated script here...")
EOF

This directly writes to the file with elevated privileges.


βœ… 4. Edit Locally, Overwrite Remotely (With VS Code or SCP)

Save your changes locally (e.g. in VS Code), then push to the server:

scp fetch_waqi.py daniel@home:/tmp/
ssh daniel@home "sudo mv /tmp/fetch_waqi.py /usr/local/bin/fetch_waqi.py && sudo chmod +x /usr/local/bin/fetch_waqi.py"

πŸ› οΈ Bonus: Use install for One-Liners

sudo install -m 755 fetch_waqi.py /usr/local/bin/fetch_waqi.py

This copies the file and sets permissions in one go.


βœ… Summary

Method Best Use
cp Simple replacement
mv Moving or renaming
tee Quick inline edit with sudo
scp + mv Remote workflow (esp. from VS Code)
install Permissions + copy in one line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment