Tuesday, April 20, 2010

Linux Command: cp -f, --force, Not Working

Today, when I tried to copy some files from one dirctory to the other in my Linux server, I issued the following Linux command:

#>cp -rf /dir1/* /dir2

However, the -f, --force switch, which was to tell cp command to overwrite the existing files (it meas if an existing destination file cannot be opened, remove it and try again), did not seen to work. I kept getting the following message:

cp: overwrite ‘/dir1/subdir1/file.dat with /dir2/subdir1/file.dat’

Since I had about 300 files to copy, it was not easy for me to keep typing ‘y’. So, I did some searches and found the following solution.

1. Run the alias command to check if cp was set to alias with a different command.

#> alias

alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'

Which you can see, cp was acturaly alias as 'cp –i'. -i, --interactive, which means prompt before overwrite. Therefore, -f was ignored.

I want to remove the alias so I could copy the files. To do so, I needed to issue the following command:

#>unalias cp

However, in normally situation, we do want to use cp –i to prevent accidentally override files. Therefore, I issued the following command after done with copying the files:

#>alias ‘cp=cp –I’

One more detail, to perform the above steps, it required root access. So, what happen if we don’t have root access? Well, the following command works:

Command:
#> /bin/cp -rf /dir1/* /dir2

It is because that the /bin/cp copy is not alias to any other command switch.


1 comment:

Anonymous said...

Hi,

(Posting here because you're the first result about it enabling anonymous comments (*too lazy to register*)).

Four other ways to do it I found on other webpages:

$ \cp -f example1 example2
$ 'cp' -f example1 example2
$ yes|cp example1 example2
$ cp -a example1 example2

(Note the last one is short for "--archive", and will preserve permissions, and owner/group if you have the necessary permissions).

I didn't test any of them though. I decided to use a more simple:

alias cpf='/bin/cp -f'

... in my ~/.bashrc (well, ~/.bash_aliases in my case, sourced from my ~/.bashrc).

(Note you have to specify '/bin/cp', otherwise the 'cp -i' alias will be called afterward, and you'll end up with 'cp -i -f' as before...).


I'm thinking of maybe using `alias cpi='cp -i'`, instead of aliasing `cp` directly, too... 'have to get used to it though...


Note that `mv` causes the very same issue. Not `rm` (yet?) though.


(Concerning your article, you don't need root access for alias/unalias. And you wrote `cp –I` instead of `cp –i`, when talking about reestablishing the alias :p).


Bye.