diff --git a/src/uu/cp/src/cp.rs b/src/uu/cp/src/cp.rs index 76a7f84fb..52d59ff61 100644 --- a/src/uu/cp/src/cp.rs +++ b/src/uu/cp/src/cp.rs @@ -1510,7 +1510,7 @@ fn backup_dest(dest: &Path, backup_path: &Path) -> CopyResult { /// /// Copying to the same file is only allowed if both `--backup` and /// `--force` are specified and the file is a regular file. -fn is_forbidden_copy_to_same_file( +fn is_forbidden_to_copy_to_same_file( source: &Path, dest: &Path, options: &Options, @@ -1522,6 +1522,7 @@ fn is_forbidden_copy_to_same_file( options.dereference(source_in_command_line) || !source.is_symlink(); paths_refer_to_same_file(source, dest, dereference_to_compare) && !(options.force() && options.backup != BackupMode::NoBackup) + && !(dest.is_symlink() && options.backup != BackupMode::NoBackup) } /// Back up, remove, or leave intact the destination file, depending on the options. @@ -1533,7 +1534,7 @@ fn handle_existing_dest( ) -> CopyResult<()> { // Disallow copying a file to itself, unless `--force` and // `--backup` are both specified. - if is_forbidden_copy_to_same_file(source, dest, options, source_in_command_line) { + if is_forbidden_to_copy_to_same_file(source, dest, options, source_in_command_line) { return Err(format!("{} and {} are the same file", source.quote(), dest.quote()).into()); } diff --git a/tests/by-util/test_cp.rs b/tests/by-util/test_cp.rs index 50d2817d5..5d78c5996 100644 --- a/tests/by-util/test_cp.rs +++ b/tests/by-util/test_cp.rs @@ -731,6 +731,25 @@ fn test_cp_arg_backup_with_dest_a_symlink() { assert_eq!(original, at.resolve_link(backup)); } +#[test] +fn test_cp_arg_backup_with_dest_a_symlink_to_source() { + let (at, mut ucmd) = at_and_ucmd!(); + let source = "source"; + let source_content = "content"; + let symlink = "symlink"; + let backup = "symlink~"; + + at.write(source, source_content); + at.symlink_file(source, symlink); + + ucmd.arg("-b").arg(source).arg(symlink).succeeds(); + + assert!(!at.symlink_exists(symlink)); + assert_eq!(source_content, at.read(symlink)); + assert!(at.symlink_exists(backup)); + assert_eq!(source, at.resolve_link(backup)); +} + #[test] fn test_cp_arg_backup_with_other_args() { let (at, mut ucmd) = at_and_ucmd!();