vimtricks.wiki Concise Vim tricks, one at a time.

How do I save a file only if it has unsaved changes, without touching the file timestamp if nothing changed?

Answer

:update

Explanation

The :update command (abbreviated :up) writes the buffer to disk only if it has been modified since the last save. Unlike :w, which always writes the file, :update is a no-op when there are no changes — preserving the file's modification timestamp.

How it works

  • :w — always writes the buffer to disk, updating the file's timestamp even if nothing changed
  • :update — writes the buffer only if it has been modified (:set modified is true); otherwise does nothing

This distinction matters because many tools (build systems, make, inotify watchers, CI triggers) react to file timestamp changes. Unnecessary writes can trigger false rebuilds.

Example

When doing a bulk operation across many files, only files that were actually changed will be written:

:argdo %s/old_func/new_func/ge | update

Compare to using :w:

:argdo %s/old_func/new_func/ge | w    " writes ALL files, even unchanged ones
:argdo %s/old_func/new_func/ge | up   " writes only files that matched

Tips

  • :up is the shortest abbreviation
  • Pair with :bufdo, :windo, or :cdo for targeted batch operations without unnecessary disk writes
  • :wall always writes all modified buffers; :update only affects the current buffer
  • In your mappings, consider <leader>w mapped to :update<CR> instead of :w<CR> to avoid phantom file touches

Next

How do I add more keystrokes to the end of an existing macro without re-recording the whole thing?