cp command: Overwrite confirmation with file diff When running cp command to copy files, I would like to be prompted for overwrite confirmation, and, if possible, view the file diff confirming.

Is this possible? And if yes, how?

Ideal example:

$ cp file1.txt file2.txt
0a1,2
&gt; 1.
&gt; 
2a5,6
&gt; 2.
&gt; 
4a9,10
&gt; 3.
&gt; 
Overwrite file2.txt? [Yes/No/Keep both] (default Y):
Placing alias commands in your bash profile will gain you partial overwrite protection. As others mentioned in your comments, you will need to write a script add the diff function. 

I placed the commands below in my ~/.bash_profile.

Bash on macOS determines what file is your bash profile in this order:


~/.bash_profile
~/.bash_login
~/.profile


These commands tell cp, mv and rm to give you a warning when a file is to be overwritten or deleted:

alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'
# Placing a blank after sudo causes alias substitution 
# for sudo's inner commands . See Gordon Davisson's comments below for 
# details. 
alias sudo='sudo '


This example, assumes you have placed the above commands in your bash profile.

mac $ touch a
mac $ touch aa
mac $ cp aa a
overwrite a? (y/n [n]) n
not overwritten
mac RC=1   $ rm a
remove a? 
mac $ mv aa a
overwrite a? (y/n [n]) n
not overwritten
# demonstrate sudo protection
mac $ touch inin
mac $ sudo cp inin hihi
overwrite hihi? (y/n [n]) n
not overwritten
mac RC=1   $ sudo mv  inin hihi
overwrite hihi? (y/n [n]) n
not overwritten
mac $ sudo rm inin hihi
remove inin? y
remove hihi? y
mac $ 


These alias command do not protect you in all circumstances like when you invoke a new shell or run cp, mv or rm from within other commands like find.



P.S.: The aliases mentioned above use the same name as the original command, thereby shadowing it. To access the original un-aliased command, prepend it with a \ character (E.g., \cp, \mv, \rm etc.).