*** empty log message ***
[coreutils.git] / src / mv.c
bloba4295587107179d2a45dd9cecb3a792220a46a0b
1 /* mv -- move or rename files
2 Copyright (C) 86, 89, 90, 91, 1995-2001 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)
7 any later version.
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 */
20 #ifdef _AIX
21 #pragma alloca
22 #endif
24 #include <config.h>
25 #include <stdio.h>
26 #include <getopt.h>
27 #include <sys/types.h>
28 #include <assert.h>
30 #include "system.h"
31 #include "backupfile.h"
32 #include "copy.h"
33 #include "cp-hash.h"
34 #include "error.h"
35 #include "path-concat.h"
36 #include "quote.h"
37 #include "remove.h"
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "mv"
42 #define AUTHORS "Mike Parker, David MacKenzie, and Jim Meyering"
44 /* Initial number of entries in each hash table entry's table of inodes. */
45 #define INITIAL_HASH_MODULE 100
47 /* Initial number of entries in the inode hash table. */
48 #define INITIAL_ENTRY_TAB_SIZE 70
50 /* For long options that have no equivalent short option, use a
51 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
52 enum
54 TARGET_DIRECTORY_OPTION = CHAR_MAX + 1,
55 STRIP_TRAILING_SLASHES_OPTION
58 int euidaccess ();
59 int full_write ();
60 int isdir ();
61 int lstat ();
62 int yesno ();
64 /* The name this program was run with. */
65 char *program_name;
67 /* Remove any trailing slashes from each SOURCE argument. */
68 static int remove_trailing_slashes;
70 static struct option const long_options[] =
72 {"backup", optional_argument, NULL, 'b'},
73 {"force", no_argument, NULL, 'f'},
74 {"interactive", no_argument, NULL, 'i'},
75 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
76 {"suffix", required_argument, NULL, 'S'},
77 {"target-directory", required_argument, NULL, TARGET_DIRECTORY_OPTION},
78 {"update", no_argument, NULL, 'u'},
79 {"verbose", no_argument, NULL, 'v'},
80 {"version-control", required_argument, NULL, 'V'},
81 {GETOPT_HELP_OPTION_DECL},
82 {GETOPT_VERSION_OPTION_DECL},
83 {NULL, 0, NULL, 0}
86 static void
87 rm_option_init (struct rm_options *x)
89 x->unlink_dirs = 0;
91 x->ignore_missing_files = 0;
93 x->recursive = 1;
95 /* Should we prompt for removal, too? No. Prompting for the `move'
96 part is enough. It implies removal. */
97 x->interactive = 0;
98 x->stdin_tty = 0;
100 x->verbose = 0;
103 static void
104 cp_option_init (struct cp_options *x)
106 x->copy_as_regular = 0; /* FIXME: maybe make this an option */
107 x->dereference = DEREF_NEVER;
108 x->unlink_dest_before_opening = 0;
109 x->unlink_dest_after_failed_open = 0;
110 x->failed_unlink_is_fatal = 1;
111 x->hard_link = 0;
112 x->interactive = 0;
113 x->move_mode = 1;
114 x->myeuid = geteuid ();
115 x->one_file_system = 0;
116 x->preserve_owner_and_group = 1;
117 x->preserve_chmod_bits = 1;
118 x->preserve_timestamps = 1;
119 x->require_preserve = 0; /* FIXME: maybe make this an option */
120 x->recursive = 1;
121 x->sparse_mode = SPARSE_AUTO; /* FIXME: maybe make this an option */
122 x->symbolic_link = 0;
123 x->set_mode = 0;
124 x->mode = 0;
126 /* Find out the current file creation mask, to knock the right bits
127 when using chmod. The creation mask is set to be liberal, so
128 that created directories can be written, even if it would not
129 have been allowed with the mask this process was started with. */
130 x->umask_kill = ~ umask (0);
132 x->update = 0;
133 x->verbose = 0;
134 x->xstat = lstat;
137 /* If PATH is an existing directory, return nonzero, else 0. */
139 static int
140 is_real_dir (const char *path)
142 struct stat stats;
144 return lstat (path, &stats) == 0 && S_ISDIR (stats.st_mode);
147 static int
148 strip_trailing_slashes_2 (char *path)
150 char *end_p = path + strlen (path) - 1;
151 char *slash = end_p;
153 while (slash > path && *slash == '/')
154 *slash-- = '\0';
156 return slash < end_p;
159 /* Move SOURCE onto DEST. Handles cross-filesystem moves.
160 If SOURCE is a directory, DEST must not exist.
161 Return 0 if successful, non-zero if an error occurred. */
163 static int
164 do_move (const char *source, const char *dest, const struct cp_options *x)
166 static int first = 1;
167 int copy_into_self;
168 int rename_succeeded;
169 int fail;
171 if (first)
173 first = 0;
175 /* Allocate space for remembering copied and created files. */
176 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
179 fail = copy (source, dest, 0, x, &copy_into_self, &rename_succeeded);
181 if (!fail)
183 const char *dir_to_remove;
184 if (copy_into_self)
186 /* In general, when copy returns with copy_into_self set, SOURCE is
187 the same as, or a parent of DEST. In this case we know it's a
188 parent. It doesn't make sense to move a directory into itself, and
189 besides in some situations doing so would give highly nonintuitive
190 results. Run this `mkdir b; touch a c; mv * b' in an empty
191 directory. Here's the result of running echo `find b -print`:
192 b b/a b/b b/b/a b/c. Notice that only file `a' was copied
193 into b/b. Handle this by giving a diagnostic, removing the
194 copied-into-self directory, DEST (`b/b' in the example),
195 and failing. */
197 dir_to_remove = NULL;
198 fail = 1;
200 else if (rename_succeeded)
202 /* No need to remove anything. SOURCE was successfully
203 renamed to DEST. */
204 dir_to_remove = NULL;
206 else
208 /* This may mean SOURCE and DEST referred to different devices.
209 It may also conceivably mean that even though they referred
210 to the same device, rename wasn't implemented for that device.
212 E.g., (from Joel N. Weber),
213 [...] there might someday be cases where you can't rename
214 but you can copy where the device name is the same, especially
215 on Hurd. Consider an ftpfs with a primitive ftp server that
216 supports uploading, downloading and deleting, but not renaming.
218 Also, note that comparing device numbers is not a reliable
219 check for `can-rename'. Some systems can be set up so that
220 files from many different physical devices all have the same
221 st_dev field. This is a feature of some NFS mounting
222 configurations.
224 We reach this point if SOURCE has been successfully copied
225 to DEST. Now we have to remove SOURCE.
227 This function used to resort to copying only when rename
228 failed and set errno to EXDEV. */
230 dir_to_remove = source;
233 if (dir_to_remove != NULL)
235 struct rm_options rm_options;
236 struct File_spec fs;
237 enum RM_status status;
239 rm_option_init (&rm_options);
240 rm_options.verbose = x->verbose;
242 remove_init ();
244 fspec_init_file (&fs, dir_to_remove);
246 /* Remove any trailing slashes. This is necessary if we
247 took the else branch of movefile. */
248 strip_trailing_slashes_2 (fs.filename);
250 status = rm (&fs, 1, &rm_options);
251 assert (VALID_STATUS (status));
252 if (status == RM_ERROR)
253 fail = 1;
255 remove_fini ();
257 if (fail)
258 error (0, errno, _("cannot remove %s"), quote (dir_to_remove));
262 return fail;
265 /* Move file SOURCE onto DEST. Handles the case when DEST is a directory.
266 DEST_IS_DIR must be nonzero when DEST is a directory or a symlink to a
267 directory and zero otherwise.
268 Return 0 if successful, non-zero if an error occurred. */
270 static int
271 movefile (char *source, char *dest, int dest_is_dir,
272 const struct cp_options *x)
274 int dest_had_trailing_slash = strip_trailing_slashes_2 (dest);
275 int fail;
277 /* This code was introduced to handle the ambiguity in the semantics
278 of mv that is induced by the varying semantics of the rename function.
279 Some systems (e.g., Linux) have a rename function that honors a
280 trailing slash, while others (like Solaris 5,6,7) have a rename
281 function that ignores a trailing slash. I believe the Linux
282 rename semantics are POSIX and susv2 compliant. */
284 if (remove_trailing_slashes)
285 strip_trailing_slashes_2 (source);
287 /* In addition to when DEST is a directory, if DEST has a trailing
288 slash and neither SOURCE nor DEST is a directory, presume the target
289 is DEST/`basename source`. This converts `mv x y/' to `mv x y/x'.
290 This change means that the command `mv any file/' will now fail
291 rather than performing the move. The case when SOURCE is a
292 directory and DEST is not is properly diagnosed by do_move. */
294 if (dest_is_dir || (dest_had_trailing_slash && !is_real_dir (source)))
296 /* DEST is a directory; build full target filename. */
297 char *src_basename;
298 char *new_dest;
300 /* Remove trailing slashes before taking base_name.
301 Otherwise, base_name ("a/") returns "". */
302 strip_trailing_slashes_2 (source);
304 src_basename = base_name (source);
305 new_dest = path_concat (dest, src_basename, NULL);
306 if (new_dest == NULL)
307 xalloc_die ();
308 fail = do_move (source, new_dest, x);
310 /* Do not free new_dest. It may have been squirreled away by
311 the remember_copied function. */
313 else
315 fail = do_move (source, dest, x);
318 return fail;
321 void
322 usage (int status)
324 if (status != 0)
325 fprintf (stderr, _("Try `%s --help' for more information.\n"),
326 program_name);
327 else
329 printf (_("\
330 Usage: %s [OPTION]... SOURCE DEST\n\
331 or: %s [OPTION]... SOURCE... DIRECTORY\n\
332 or: %s [OPTION]... --target-directory=DIRECTORY SOURCE...\n\
334 program_name, program_name, program_name);
335 printf (_("\
336 Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n\
338 --backup[=CONTROL] make a backup of each existing destination file\n\
339 -b like --backup but does not accept an argument\n\
340 -f, --force never prompt before overwriting\n\
341 -i, --interactive prompt before overwrite\n\
342 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
343 argument\n\
344 -S, --suffix=SUFFIX override the usual backup suffix\n\
345 --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY\n\
346 -u, --update move only older or brand new non-directories\n\
347 -v, --verbose explain what is being done\n\
348 --help display this help and exit\n\
349 --version output version information and exit\n\
351 "));
352 printf (_("\
353 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
354 The version control method may be selected via the --backup option or through\n\
355 the VERSION_CONTROL environment variable. Here are the values:\n\
357 none, off never make backups (even if --backup is given)\n\
358 numbered, t make numbered backups\n\
359 existing, nil numbered if numbered backups exist, simple otherwise\n\
360 simple, never always make simple backups\n\
361 "));
362 puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
364 exit (status);
368 main (int argc, char **argv)
370 int c;
371 int errors;
372 int make_backups = 0;
373 int dest_is_dir;
374 char *backup_suffix_string;
375 char *version_control_string = NULL;
376 struct cp_options x;
377 char *target_directory = NULL;
378 int target_directory_specified;
379 unsigned int n_files;
380 char **file;
382 program_name = argv[0];
383 setlocale (LC_ALL, "");
384 bindtextdomain (PACKAGE, LOCALEDIR);
385 textdomain (PACKAGE);
387 atexit (close_stdout);
389 cp_option_init (&x);
391 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
392 we'll actually use backup_suffix_string. */
393 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
395 errors = 0;
397 while ((c = getopt_long (argc, argv, "bfiuvS:V:", long_options, NULL)) != -1)
399 switch (c)
401 case 0:
402 break;
404 case 'V': /* FIXME: this is deprecated. Remove it in 2001. */
405 error (0, 0,
406 _("warning: --version-control (-V) is obsolete; support for\
407 it\nwill be removed in some future release. Use --backup=%s instead."
408 ), optarg);
409 /* Fall through. */
411 case 'b':
412 make_backups = 1;
413 if (optarg)
414 version_control_string = optarg;
415 break;
416 case 'f':
417 x.interactive = 0;
418 break;
419 case 'i':
420 x.interactive = 1;
421 break;
422 case STRIP_TRAILING_SLASHES_OPTION:
423 remove_trailing_slashes = 1;
424 break;
425 case TARGET_DIRECTORY_OPTION:
426 target_directory = optarg;
427 break;
428 case 'u':
429 x.update = 1;
430 break;
431 case 'v':
432 x.verbose = 1;
433 break;
434 case 'S':
435 make_backups = 1;
436 backup_suffix_string = optarg;
437 break;
438 case_GETOPT_HELP_CHAR;
439 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
440 default:
441 usage (1);
445 n_files = argc - optind;
446 file = argv + optind;
448 target_directory_specified = (target_directory != NULL);
449 if (target_directory == NULL && n_files != 0)
450 target_directory = file[n_files - 1];
452 dest_is_dir = (n_files > 0 && isdir (target_directory));
454 if (n_files == 0 || (n_files == 1 && !target_directory_specified))
456 error (0, 0, _("missing file argument"));
457 usage (1);
460 if (target_directory_specified)
462 if (!dest_is_dir)
464 error (0, 0, _("specified target, %s is not a directory"),
465 quote (target_directory));
466 usage (1);
469 else if (n_files > 2 && !dest_is_dir)
471 error (0, 0,
472 _("when moving multiple files, last argument must be a directory"));
473 usage (1);
476 if (backup_suffix_string)
477 simple_backup_suffix = xstrdup (backup_suffix_string);
479 x.backup_type = (make_backups
480 ? xget_version (_("backup type"),
481 version_control_string)
482 : none);
484 /* Move each arg but the last into the target_directory. */
486 unsigned int last_file_idx = (target_directory_specified
487 ? n_files - 1
488 : n_files - 2);
489 unsigned int i;
490 for (i = 0; i <= last_file_idx; ++i)
491 errors |= movefile (file[i], target_directory, dest_is_dir, &x);
494 exit (errors);