1 /* mv -- move or rename files
2 Copyright (C) 86, 89, 90, 91, 1995-2002 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. */
18 /* Written by Mike Parker, David MacKenzie, and Jim Meyering */
27 #include <sys/types.h>
32 #include "backupfile.h"
37 #include "path-concat.h"
41 /* The official name of this program (e.g., no `g' prefix). */
42 #define PROGRAM_NAME "mv"
44 #define AUTHORS N_ ("Mike Parker, David MacKenzie, and Jim Meyering")
46 /* Initial number of entries in each hash table entry's table of inodes. */
47 #define INITIAL_HASH_MODULE 100
49 /* Initial number of entries in the inode hash table. */
50 #define INITIAL_ENTRY_TAB_SIZE 70
52 /* For long options that have no equivalent short option, use a
53 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
56 TARGET_DIRECTORY_OPTION = CHAR_MAX + 1,
57 STRIP_TRAILING_SLASHES_OPTION,
66 /* The name this program was run with. */
69 /* Remove any trailing slashes from each SOURCE argument. */
70 static int remove_trailing_slashes;
72 /* Valid arguments to the `--reply' option. */
73 static char const* const reply_args[] =
75 "yes", "no", "query", 0
78 /* The values that correspond to the above strings. */
79 static int const reply_vals[] =
81 I_ALWAYS_YES, I_ALWAYS_NO, I_ASK_USER
84 static struct option const long_options[] =
86 {"backup", optional_argument, NULL, 'b'},
87 {"force", no_argument, NULL, 'f'},
88 {"interactive", no_argument, NULL, 'i'},
89 {"reply", required_argument, NULL, REPLY_OPTION},
90 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
91 {"suffix", required_argument, NULL, 'S'},
92 {"target-directory", required_argument, NULL, TARGET_DIRECTORY_OPTION},
93 {"update", no_argument, NULL, 'u'},
94 {"verbose", no_argument, NULL, 'v'},
95 {"version-control", required_argument, NULL, 'V'},
96 {GETOPT_HELP_OPTION_DECL},
97 {GETOPT_VERSION_OPTION_DECL},
102 rm_option_init (struct rm_options *x)
106 x->ignore_missing_files = 0;
110 /* Should we prompt for removal, too? No. Prompting for the `move'
111 part is enough. It implies removal. */
119 cp_option_init (struct cp_options *x)
121 x->copy_as_regular = 0; /* FIXME: maybe make this an option */
122 x->dereference = DEREF_NEVER;
123 x->unlink_dest_before_opening = 0;
124 x->unlink_dest_after_failed_open = 0;
126 x->interactive = I_UNSPECIFIED;
128 x->myeuid = geteuid ();
129 x->one_file_system = 0;
130 x->preserve_ownership = 1;
131 x->preserve_links = 1;
132 x->preserve_mode = 1;
133 x->preserve_timestamps = 1;
134 x->require_preserve = 0; /* FIXME: maybe make this an option */
136 x->sparse_mode = SPARSE_AUTO; /* FIXME: maybe make this an option */
137 x->symbolic_link = 0;
140 x->stdin_tty = isatty (STDIN_FILENO);
142 /* Find out the current file creation mask, to knock the right bits
143 when using chmod. The creation mask is set to be liberal, so
144 that created directories can be written, even if it would not
145 have been allowed with the mask this process was started with. */
146 x->umask_kill = ~ umask (0);
155 /* If PATH is an existing directory, return nonzero, else 0. */
158 is_real_dir (const char *path)
162 return lstat (path, &stats) == 0 && S_ISDIR (stats.st_mode);
165 /* Move SOURCE onto DEST. Handles cross-filesystem moves.
166 If SOURCE is a directory, DEST must not exist.
167 Return 0 if successful, non-zero if an error occurred. */
170 do_move (const char *source, const char *dest, const struct cp_options *x)
172 static int first = 1;
174 int rename_succeeded;
181 /* Allocate space for remembering copied and created files. */
185 fail = copy (source, dest, 0, x, ©_into_self, &rename_succeeded);
189 const char *dir_to_remove;
192 /* In general, when copy returns with copy_into_self set, SOURCE is
193 the same as, or a parent of DEST. In this case we know it's a
194 parent. It doesn't make sense to move a directory into itself, and
195 besides in some situations doing so would give highly nonintuitive
196 results. Run this `mkdir b; touch a c; mv * b' in an empty
197 directory. Here's the result of running echo `find b -print`:
198 b b/a b/b b/b/a b/c. Notice that only file `a' was copied
199 into b/b. Handle this by giving a diagnostic, removing the
200 copied-into-self directory, DEST (`b/b' in the example),
203 dir_to_remove = NULL;
206 else if (rename_succeeded)
208 /* No need to remove anything. SOURCE was successfully
210 dir_to_remove = NULL;
214 /* This may mean SOURCE and DEST referred to different devices.
215 It may also conceivably mean that even though they referred
216 to the same device, rename wasn't implemented for that device.
218 E.g., (from Joel N. Weber),
219 [...] there might someday be cases where you can't rename
220 but you can copy where the device name is the same, especially
221 on Hurd. Consider an ftpfs with a primitive ftp server that
222 supports uploading, downloading and deleting, but not renaming.
224 Also, note that comparing device numbers is not a reliable
225 check for `can-rename'. Some systems can be set up so that
226 files from many different physical devices all have the same
227 st_dev field. This is a feature of some NFS mounting
230 We reach this point if SOURCE has been successfully copied
231 to DEST. Now we have to remove SOURCE.
233 This function used to resort to copying only when rename
234 failed and set errno to EXDEV. */
236 dir_to_remove = source;
239 if (dir_to_remove != NULL)
241 struct rm_options rm_options;
243 enum RM_status status;
244 static int first_rm = 1;
245 static struct dev_ino cwd_dev_ino;
250 if (lstat (".", &cwd_sb))
251 error (EXIT_FAILURE, errno, _("cannot lstat `.'"));
254 cwd_dev_ino.st_dev = cwd_sb.st_dev;
255 cwd_dev_ino.st_ino = cwd_sb.st_ino;
258 rm_option_init (&rm_options);
259 rm_options.verbose = x->verbose;
263 fspec_init_file (&fs, dir_to_remove);
265 /* Remove any trailing slashes. This is necessary if we
266 took the else branch of movefile. */
267 strip_trailing_slashes (fs.filename);
269 status = rm (&fs, 1, &rm_options, &cwd_dev_ino);
270 assert (VALID_STATUS (status));
271 if (status == RM_ERROR)
277 error (0, errno, _("cannot remove %s"), quote (dir_to_remove));
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 (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 (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 strip_trailing_slashes (source);
320 src_basename = base_name (source);
321 new_dest = path_concat (dest, src_basename, NULL);
322 if (new_dest == NULL)
324 fail = do_move (source, new_dest, x);
329 fail = do_move (source, dest, x);
339 fprintf (stderr, _("Try `%s --help' for more information.\n"),
344 Usage: %s [OPTION]... SOURCE DEST\n\
345 or: %s [OPTION]... SOURCE... DIRECTORY\n\
346 or: %s [OPTION]... --target-directory=DIRECTORY SOURCE...\n\
348 program_name, program_name, program_name);
350 Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n\
354 Mandatory arguments to long options are mandatory for short options too.\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 do not prompt before overwriting\n\
360 equivalent to --reply=yes\n\
361 -i, --interactive prompt before overwrite\n\
362 equivalent to --reply=query\n\
365 --reply={yes,no,query} specify how to handle the prompt about an\n\
366 existing destination file\n\
367 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
369 -S, --suffix=SUFFIX override the usual backup suffix\n\
372 --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY\n\
373 -u, --update move only when the SOURCE file is newer\n\
374 than the destination file or when the\n\
375 destination file is missing\n\
376 -v, --verbose explain what is being done\n\
378 fputs (HELP_OPTION_DESCRIPTION, stdout);
379 fputs (VERSION_OPTION_DESCRIPTION, stdout);
382 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
383 The version control method may be selected via the --backup option or through\n\
384 the VERSION_CONTROL environment variable. Here are the values:\n\
388 none, off never make backups (even if --backup is given)\n\
389 numbered, t make numbered backups\n\
390 existing, nil numbered if numbered backups exist, simple otherwise\n\
391 simple, never always make simple backups\n\
393 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
399 main (int argc, char **argv)
403 int make_backups = 0;
405 char *backup_suffix_string;
406 char *version_control_string = NULL;
408 char *target_directory = NULL;
409 int target_directory_specified;
410 unsigned int n_files;
413 program_name = argv[0];
414 setlocale (LC_ALL, "");
415 bindtextdomain (PACKAGE, LOCALEDIR);
416 textdomain (PACKAGE);
418 atexit (close_stdout);
422 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
423 we'll actually use backup_suffix_string. */
424 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
428 while ((c = getopt_long (argc, argv, "bfiuvS:V:", long_options, NULL)) != -1)
435 case 'V': /* FIXME: this is deprecated. Remove it in 2001. */
437 _("warning: --version-control (-V) is obsolete; support for\
438 it\nwill be removed in some future release. Use --backup=%s instead."
445 version_control_string = optarg;
448 x.interactive = I_ALWAYS_YES;
451 x.interactive = I_ASK_USER;
454 x.interactive = XARGMATCH ("--reply", optarg,
455 reply_args, reply_vals);
457 case STRIP_TRAILING_SLASHES_OPTION:
458 remove_trailing_slashes = 1;
460 case TARGET_DIRECTORY_OPTION:
461 target_directory = optarg;
471 backup_suffix_string = optarg;
473 case_GETOPT_HELP_CHAR;
474 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
480 n_files = argc - optind;
481 file = argv + optind;
483 target_directory_specified = (target_directory != NULL);
484 if (target_directory == NULL && n_files != 0)
485 target_directory = file[n_files - 1];
487 dest_is_dir = (n_files > 0 && isdir (target_directory));
489 if (n_files == 0 || (n_files == 1 && !target_directory_specified))
491 error (0, 0, _("missing file argument"));
495 if (target_directory_specified)
499 error (0, 0, _("specified target, %s is not a directory"),
500 quote (target_directory));
504 else if (n_files > 2 && !dest_is_dir)
507 _("when moving multiple files, last argument must be a directory"));
511 if (backup_suffix_string)
512 simple_backup_suffix = xstrdup (backup_suffix_string);
514 x.backup_type = (make_backups
515 ? xget_version (_("backup type"),
516 version_control_string)
519 /* Move each arg but the last into the target_directory. */
521 unsigned int last_file_idx = (target_directory_specified
526 /* Initialize the hash table only if we'll need it.
527 The problem it is used to detect can arise only if there are
528 two or more files to move. */
532 for (i = 0; i <= last_file_idx; ++i)
533 errors |= movefile (file[i], target_directory, dest_is_dir, &x);