1 /* mv -- move or rename files
2 Copyright (C) 86, 89, 90, 91, 1995-2000 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
19 -f, --force Assume a 'y' answer to all questions it would
20 normally ask, and not ask the questions.
22 -i, --interactive Require confirmation from the user before
23 performing any move that would destroy an
26 -u, --update Do not move a nondirectory that has an
27 existing destination with the same or newer
30 -v, --verbose List the name of each file as it is moved, and
31 the name it is moved to.
38 Written by Mike Parker, David MacKenzie, and Jim Meyering */
47 #include <sys/types.h>
51 #include "backupfile.h"
55 #include "path-concat.h"
58 /* The official name of this program (e.g., no `g' prefix). */
59 #define PROGRAM_NAME "mv"
61 #define AUTHORS "Mike Parker, David MacKenzie, and Jim Meyering"
63 /* Initial number of entries in each hash table entry's table of inodes. */
64 #define INITIAL_HASH_MODULE 100
66 /* Initial number of entries in the inode hash table. */
67 #define INITIAL_ENTRY_TAB_SIZE 70
69 /* For long options that have no equivalent short option, use a
70 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
73 TARGET_DIRECTORY_OPTION = CHAR_MAX + 1,
74 STRIP_TRAILING_SLASHES_OPTION
83 /* The name this program was run with. */
86 /* Remove any trailing slashes from each SOURCE argument. */
87 static int remove_trailing_slashes;
89 static struct option const long_options[] =
91 {"backup", optional_argument, NULL, 'b'},
92 {"force", no_argument, NULL, 'f'},
93 {"interactive", no_argument, NULL, 'i'},
94 {"strip-trailing-slash", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
95 {"suffix", required_argument, NULL, 'S'},
96 {"target-directory", required_argument, NULL, TARGET_DIRECTORY_OPTION},
97 {"update", no_argument, NULL, 'u'},
98 {"verbose", no_argument, NULL, 'v'},
99 {"version-control", required_argument, NULL, 'V'},
100 {GETOPT_HELP_OPTION_DECL},
101 {GETOPT_VERSION_OPTION_DECL},
106 rm_option_init (struct rm_options *x)
110 /* FIXME: maybe this should be 1. The POSIX spec doesn't specify. */
111 x->ignore_missing_files = 0;
115 /* Should we prompt for removal, too? No. Prompting for the `move'
116 part is enough. It implies removal. */
124 cp_option_init (struct cp_options *x)
126 x->copy_as_regular = 0; /* FIXME: maybe make this an option */
129 x->failed_unlink_is_fatal = 1;
133 x->myeuid = geteuid ();
134 x->one_file_system = 0;
135 x->preserve_owner_and_group = 1;
136 x->preserve_chmod_bits = 1;
137 x->preserve_timestamps = 1;
138 x->require_preserve = 0; /* FIXME: maybe make this an option */
140 x->sparse_mode = SPARSE_AUTO; /* FIXME: maybe make this an option */
141 x->symbolic_link = 0;
145 /* Find out the current file creation mask, to knock the right bits
146 when using chmod. The creation mask is set to be liberal, so
147 that created directories can be written, even if it would not
148 have been allowed with the mask this process was started with. */
149 x->umask_kill = ~ umask (0);
156 /* If PATH is an existing directory, return nonzero, else 0. */
159 is_real_dir (const char *path)
163 return lstat (path, &stats) == 0 && S_ISDIR (stats.st_mode);
166 /* Move SOURCE onto DEST. Handles cross-filesystem moves.
167 If SOURCE is a directory, DEST must not exist.
168 Return 0 if successful, non-zero if an error occurred. */
171 do_move (const char *source, const char *dest, const struct cp_options *x)
173 static int first = 1;
175 int rename_succeeded;
182 /* Allocate space for remembering copied and created files. */
183 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
186 fail = copy (source, dest, 0, x, ©_into_self, &rename_succeeded);
190 const char *dir_to_remove;
193 /* In general, when copy returns with copy_into_self set, SOURCE is
194 the same as, or a parent of DEST. In this case we know it's a
195 parent. It doesn't make sense to move a directory into itself, and
196 besides in some situations doing so would give highly nonintuitive
197 results. Run this `mkdir b; touch a c; mv * b' in an empty
198 directory. Here's the result of running echo `find b -print`:
199 b b/a b/b b/b/a b/c. Notice that only file `a' was copied
200 into b/b. Handle this by giving a diagnostic, removing the
201 copied-into-self directory, DEST (`b/b' in the example),
204 dir_to_remove = NULL;
206 _("cannot move `%s' to a subdirectory of itself, `%s'"),
209 else if (rename_succeeded)
211 /* No need to remove anything. SOURCE was successfully
213 dir_to_remove = NULL;
217 /* This may mean SOURCE and DEST referred to different devices.
218 It may also conceivably mean that even though they referred
219 to the same device, rename wasn't implemented for that device.
221 E.g., (from Joel N. Weber),
222 [...] there might someday be cases where you can't rename
223 but you can copy where the device name is the same, especially
224 on Hurd. Consider an ftpfs with a primitive ftp server that
225 supports uploading, downloading and deleting, but not renaming.
227 Also, note that comparing device numbers is not a reliable
228 check for `can-rename'. Some systems can be set up so that
229 files from many different physical devices all have the same
230 st_dev field. This is a feature of some NFS mounting
233 We reach this point if SOURCE has been successfully copied
234 to DEST. Now we have to remove SOURCE.
236 This function used to resort to copying only when rename
237 failed and set errno to EXDEV. */
239 dir_to_remove = source;
242 if (dir_to_remove != NULL)
244 struct rm_options rm_options;
246 enum RM_status status;
248 rm_option_init (&rm_options);
249 rm_options.verbose = x->verbose;
253 fspec_init_file (&fs, dir_to_remove);
254 status = rm (&fs, 1, &rm_options);
255 assert (VALID_STATUS (status));
256 if (status == RM_ERROR)
262 error (0, errno, _("cannot remove `%s'"), dir_to_remove);
273 strip_trailing_slashes_2 (char *path)
275 char *end_p = path + strlen (path) - 1;
278 while (slash > path && *slash == '/')
281 return slash < end_p;
284 /* Move file SOURCE onto DEST. Handles the case when DEST is a directory.
285 DEST_IS_DIR must be nonzero when DEST is a directory or a symlink to a
286 directory and zero otherwise.
287 Return 0 if successful, non-zero if an error occurred. */
290 movefile (char *source, char *dest, int dest_is_dir,
291 const struct cp_options *x)
293 int dest_had_trailing_slash = strip_trailing_slashes_2 (dest);
296 /* This code was introduced to handle the ambiguity in the semantics
297 of mv that is induced by the varying semantics of the rename function.
298 Some systems (e.g., Linux) have a rename function that honors a
299 trailing slash, while others (like Solaris 5,6,7) have a rename
300 function that ignores a trailing slash. I believe the Linux
301 rename semantics are POSIX and susv2 compliant. */
303 if (remove_trailing_slashes)
304 strip_trailing_slashes_2 (source);
306 /* In addition to when DEST is a directory, if DEST has a trailing
307 slash and neither SOURCE nor DEST is a directory, presume the target
308 is DEST/`basename source`. This converts `mv x y/' to `mv x y/x'.
309 This change means that the command `mv any file/' will now fail
310 rather than performing the move. The case when SOURCE is a
311 directory and DEST is not is properly diagnosed by do_move. */
313 if (dest_is_dir || (dest_had_trailing_slash && !is_real_dir (source)))
315 /* DEST is a directory; build full target filename. */
319 /* Remove trailing slashes before taking base_name.
320 Otherwise, base_name ("a/") returns "". */
321 strip_trailing_slashes_2 (source);
323 src_basename = base_name (source);
324 new_dest = path_concat (dest, src_basename, NULL);
325 if (new_dest == NULL)
326 error (1, 0, _("virtual memory exhausted"));
327 fail = do_move (source, new_dest, x);
329 /* Do not free new_dest. It may have been squirelled away by
330 the remember_copied function. */
334 fail = do_move (source, dest, x);
344 fprintf (stderr, _("Try `%s --help' for more information.\n"),
349 Usage: %s [OPTION]... SOURCE DEST\n\
350 or: %s [OPTION]... SOURCE... DIRECTORY\n\
351 or: %s [OPTION]... --target-directory=DIRECTORY SOURCE...\n\
353 program_name, program_name, program_name);
355 Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n\
357 --backup[=CONTROL] make a backup of each existing destination file\n\
358 -b like --backup but does not accept an argument\n\
359 -f, --force remove existing destinations, never prompt\n\
360 -i, --interactive prompt before overwrite\n\
361 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
363 -S, --suffix=SUFFIX override the usual backup suffix\n\
364 --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY\n\
365 -u, --update move only older or brand new non-directories\n\
366 -v, --verbose explain what is being done\n\
367 --help display this help and exit\n\
368 --version output version information and exit\n\
372 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
373 The version control method may be selected via the --backup option or through\n\
374 the VERSION_CONTROL environment variable. Here are the values:\n\
376 none, off never make backups (even if --backup is given)\n\
377 numbered, t make numbered backups\n\
378 existing, nil numbered if numbered backups exist, simple otherwise\n\
379 simple, never always make simple backups\n\
381 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
387 main (int argc, char **argv)
391 int make_backups = 0;
393 char *backup_suffix_string;
394 char *version_control_string = NULL;
396 char *target_directory = NULL;
397 int target_directory_specified;
398 unsigned int n_files;
401 program_name = argv[0];
402 setlocale (LC_ALL, "");
403 bindtextdomain (PACKAGE, LOCALEDIR);
404 textdomain (PACKAGE);
406 atexit (close_stdout);
410 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
411 we'll actually use backup_suffix_string. */
412 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
416 while ((c = getopt_long (argc, argv, "bfiuvS:V:", long_options, NULL)) != -1)
423 case 'V': /* FIXME: this is deprecated. Remove it in 2001. */
425 _("warning: --version-control (-V) is obsolete; support for\
426 it\nwill be removed in some future release. Use --backup=%s instead."
433 version_control_string = optarg;
443 case STRIP_TRAILING_SLASHES_OPTION:
444 remove_trailing_slashes = 1;
446 case TARGET_DIRECTORY_OPTION:
447 target_directory = optarg;
457 backup_suffix_string = optarg;
459 case_GETOPT_HELP_CHAR;
460 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
466 n_files = argc - optind;
467 file = argv + optind;
469 target_directory_specified = (target_directory != NULL);
470 if (target_directory == NULL && n_files != 0)
471 target_directory = file[n_files - 1];
473 dest_is_dir = (n_files > 0 && isdir (target_directory));
475 if (target_directory_specified)
479 error (0, 0, _("specified target, `%s' is not a directory"),
486 error (0, 0, "%s", _("missing file argument"));
494 error (0, 0, "%s", (n_files == 0
495 ? _("missing file arguments")
496 : _("missing file argument")));
500 if (n_files > 2 && !dest_is_dir)
503 _("when moving multiple files, last argument must be a directory"));
508 if (backup_suffix_string)
509 simple_backup_suffix = xstrdup (backup_suffix_string);
511 x.backup_type = (make_backups
512 ? xget_version (_("backup type"),
513 version_control_string)
516 /* Move each arg but the last into the target_directory. */
518 unsigned int last_file_idx = (target_directory_specified
522 for (i = 0; i <= last_file_idx; ++i)
523 errors |= movefile (file[i], target_directory, dest_is_dir, &x);