Make a Quick Backup of a File from the Command Line

Jun 11, 2012 - 3 Comments

Quickly make a file backup from the command line

It’s always a good idea to backup a file if you’re going to be making some changes to it and you’re uncertain of the outcome. In the Finder this is as simple as just selecting the file and hitting Command+D to create a duplicate of the file in question, but in the command line you typically have to use the cp command, point it at the file, and then specify the copied version. Here’s a nice variation of that to make fast backups of any file through the Terminal.

The simple syntax to create an instant backup of a file at the same location (directory) would be as follows:

cp file{,.backup}

For example, to backup the file named ‘file.txt’ as ‘file.txt.backup’ in the same directory, the command string would be like so:

cp file.txt{,.backup}

Notice there are no spaces between the end of the first file and the brackets. This creates copy of “file.txt” with the added extension “.backup”, resulting in “file.txt.backup”.

Whether or not this is faster for you than typing “cp file1 file2” is going to depend on your keyboarding abilities and how much you use tab completion, but regardless of which approach you take it’s good to be in the habit of making backups so you can quickly restore things to how they were before being edited, be it htaccess, /etc/hosts, or just a plist file.

Thanks to James for the tip from commandlinefu


Related articles:

Posted by: William Pearson in Command Line, Mac OS, Tips & Tricks


» Comments RSS Feed

  1. Eric says:

    That one is so useful. A time saver. I use it with ”mv” as well.

    – – –

    It’s also good for replacing the edited file with the backup (eg original copy) by moving the comma to the end. :)

    cp file.txt{.backup,}

  2. Since I find the curly braces take my fingers too far away from the home keys, I prefer:

    cp filename.ext (Ctrl-w) (Ctrl-y) (Ctrl-y) (backspace).backup

    Ctrl-w erases the previous word and ctrl-y pastes it back again (plus a trailing space).


  3. jeff says:

    since i hate trying to quickly type {}’s, i’ll stick with my standard. using autocomplete makes it the same amount of keys about, but less to remember for me.

    cp ho ho.backup

Leave a Reply


Shop on and help support OSXDaily!

Subscribe to OSXDaily

Subscribe to RSS Subscribe to Twitter Feed Follow on Facebook Subscribe to eMail Updates

Tips & Tricks


iPhone / iPad



Shop on Amazon to help support this site