Is there any way to create backup copy of a file, without type its name twice? [duplicate]

Solution 1:

You could use brace expansion like this:

cp example_file{,.bak}

Solution 2:

1. What you asked for

You can create a small shellscript file bupper:

I have a directory ~/bin, where I keep such help files.

#!/bin/bash

if [ $# -eq 1 ]
then
 cp -pvi "$1" "${1}.bak"
else
 echo "Info:  $0 copies to a backup file"
 echo "Usage: $0 <file to be backed up with .bak extension>"
fi

Make it executable,

chmod ugo+x bupper

When in ~/bin, it will be in PATH and you can run it like any executable program anywhere (where you have write permissions).

Example:

$ bupper hello.txt 
'hello.txt' -> 'hello.txt.bak'
$ bupper hello.txt 
cp: overwrite 'hello.txt.bak'? n
$ bupper hello.txt 
cp: overwrite 'hello.txt.bak'? y
'hello.txt' -> 'hello.txt.bak'

2. Alternative - let the editor do the job automatically

Some editors have an option to create a backup copy of the file before you save a new version. This backup has often a tilde as the last character (tilde is the extension, but there is no dot before it).

Gedit, the standard editor in Ubuntu is one of them.

enter image description here

After setting gedit to save such a backup copy:

gedit hello.txt

And check afterwards

$ ls hello.txt*
hello.txt  hello.txt~  hello.txt.bak

Now hello.txt~ has been added to hello.txt and the backup created by bupper.

This works with nano too, with the option -B

nano -B hello.txt

so you can do it with a command line editor for 'sudo' tasks :-)