* src/dd.c (flags): noatime and nofollow now depend on
[coreutils/bo.git] / src / mv.c
blob299a6acfd08ded75490e1addb152fe6c1dd6bfe1
1 /* mv -- move or rename files
2 Copyright (C) 86, 89, 90, 91, 1995-2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Written by Mike Parker, David MacKenzie, and Jim Meyering */
20 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
24 #include <assert.h>
26 #include "system.h"
27 #include "argmatch.h"
28 #include "backupfile.h"
29 #include "copy.h"
30 #include "cp-hash.h"
31 #include "error.h"
32 #include "filenamecat.h"
33 #include "quote.h"
34 #include "remove.h"
36 /* The official name of this program (e.g., no `g' prefix). */
37 #define PROGRAM_NAME "mv"
39 #define AUTHORS "Mike Parker", "David MacKenzie", "Jim Meyering"
41 /* Initial number of entries in each hash table entry's table of inodes. */
42 #define INITIAL_HASH_MODULE 100
44 /* Initial number of entries in the inode hash table. */
45 #define INITIAL_ENTRY_TAB_SIZE 70
47 /* For long options that have no equivalent short option, use a
48 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
49 enum
51 REPLY_OPTION = CHAR_MAX + 1,
52 STRIP_TRAILING_SLASHES_OPTION
55 /* The name this program was run with. */
56 char *program_name;
58 /* Remove any trailing slashes from each SOURCE argument. */
59 static bool remove_trailing_slashes;
61 /* Valid arguments to the `--reply' option. */
62 static char const* const reply_args[] =
64 "yes", "no", "query", NULL
67 /* The values that correspond to the above strings. */
68 static int const reply_vals[] =
70 I_ALWAYS_YES, I_ALWAYS_NO, I_ASK_USER
73 static struct option const long_options[] =
75 {"backup", optional_argument, NULL, 'b'},
76 {"force", no_argument, NULL, 'f'},
77 {"interactive", no_argument, NULL, 'i'},
78 {"no-target-directory", no_argument, NULL, 'T'},
79 {"reply", required_argument, NULL, REPLY_OPTION}, /* Deprecated 2005-07-03,
80 remove in 2008. */
81 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
82 {"suffix", required_argument, NULL, 'S'},
83 {"target-directory", required_argument, NULL, 't'},
84 {"update", no_argument, NULL, 'u'},
85 {"verbose", no_argument, NULL, 'v'},
86 {GETOPT_HELP_OPTION_DECL},
87 {GETOPT_VERSION_OPTION_DECL},
88 {NULL, 0, NULL, 0}
91 static void
92 rm_option_init (struct rm_options *x)
94 x->ignore_missing_files = false;
95 x->root_dev_ino = NULL;
96 x->recursive = true;
98 /* Should we prompt for removal, too? No. Prompting for the `move'
99 part is enough. It implies removal. */
100 x->interactive = 0;
101 x->stdin_tty = false;
103 x->verbose = false;
105 /* Since this program may well have to process additional command
106 line arguments after any call to `rm', that function must preserve
107 the initial working directory, in case one of those is a
108 `.'-relative name. */
109 x->require_restore_cwd = true;
112 static void
113 cp_option_init (struct cp_options *x)
115 x->copy_as_regular = false; /* FIXME: maybe make this an option */
116 x->dereference = DEREF_NEVER;
117 x->unlink_dest_before_opening = false;
118 x->unlink_dest_after_failed_open = false;
119 x->hard_link = false;
120 x->interactive = I_UNSPECIFIED;
121 x->move_mode = true;
122 x->chown_privileges = chown_privileges ();
123 x->one_file_system = false;
124 x->preserve_ownership = true;
125 x->preserve_links = true;
126 x->preserve_mode = true;
127 x->preserve_timestamps = true;
128 x->require_preserve = false; /* FIXME: maybe make this an option */
129 x->recursive = true;
130 x->sparse_mode = SPARSE_AUTO; /* FIXME: maybe make this an option */
131 x->symbolic_link = false;
132 x->set_mode = false;
133 x->mode = 0;
134 x->stdin_tty = isatty (STDIN_FILENO);
136 x->update = false;
137 x->verbose = false;
138 x->dest_info = NULL;
139 x->src_info = NULL;
142 /* FILE is the last operand of this command. Return true if FILE is a
143 directory. But report an error if there is a problem accessing FILE, other
144 than nonexistence (errno == ENOENT). */
146 static bool
147 target_directory_operand (char const *file)
149 struct stat st;
150 int err = (stat (file, &st) == 0 ? 0 : errno);
151 bool is_a_dir = !err && S_ISDIR (st.st_mode);
152 if (err && err != ENOENT)
153 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
154 return is_a_dir;
157 /* Move SOURCE onto DEST. Handles cross-file-system moves.
158 If SOURCE is a directory, DEST must not exist.
159 Return true if successful. */
161 static bool
162 do_move (const char *source, const char *dest, const struct cp_options *x)
164 bool copy_into_self;
165 bool rename_succeeded;
166 bool ok = copy (source, dest, false, x, &copy_into_self, &rename_succeeded);
168 if (ok)
170 char const *dir_to_remove;
171 if (copy_into_self)
173 /* In general, when copy returns with copy_into_self set, SOURCE is
174 the same as, or a parent of DEST. In this case we know it's a
175 parent. It doesn't make sense to move a directory into itself, and
176 besides in some situations doing so would give highly nonintuitive
177 results. Run this `mkdir b; touch a c; mv * b' in an empty
178 directory. Here's the result of running echo `find b -print`:
179 b b/a b/b b/b/a b/c. Notice that only file `a' was copied
180 into b/b. Handle this by giving a diagnostic, removing the
181 copied-into-self directory, DEST (`b/b' in the example),
182 and failing. */
184 dir_to_remove = NULL;
185 ok = false;
187 else if (rename_succeeded)
189 /* No need to remove anything. SOURCE was successfully
190 renamed to DEST. Or the user declined to rename a file. */
191 dir_to_remove = NULL;
193 else
195 /* This may mean SOURCE and DEST referred to different devices.
196 It may also conceivably mean that even though they referred
197 to the same device, rename wasn't implemented for that device.
199 E.g., (from Joel N. Weber),
200 [...] there might someday be cases where you can't rename
201 but you can copy where the device name is the same, especially
202 on Hurd. Consider an ftpfs with a primitive ftp server that
203 supports uploading, downloading and deleting, but not renaming.
205 Also, note that comparing device numbers is not a reliable
206 check for `can-rename'. Some systems can be set up so that
207 files from many different physical devices all have the same
208 st_dev field. This is a feature of some NFS mounting
209 configurations.
211 We reach this point if SOURCE has been successfully copied
212 to DEST. Now we have to remove SOURCE.
214 This function used to resort to copying only when rename
215 failed and set errno to EXDEV. */
217 dir_to_remove = source;
220 if (dir_to_remove != NULL)
222 struct rm_options rm_options;
223 enum RM_status status;
225 rm_option_init (&rm_options);
226 rm_options.verbose = x->verbose;
228 status = rm (1, &dir_to_remove, &rm_options);
229 assert (VALID_STATUS (status));
230 if (status == RM_ERROR)
231 ok = false;
235 return ok;
238 /* Move file SOURCE onto DEST. Handles the case when DEST is a directory.
239 Treat DEST as a directory if DEST_IS_DIR.
240 Return true if successful. */
242 static bool
243 movefile (char *source, char *dest, bool dest_is_dir,
244 const struct cp_options *x)
246 bool ok;
248 /* This code was introduced to handle the ambiguity in the semantics
249 of mv that is induced by the varying semantics of the rename function.
250 Some systems (e.g., Linux) have a rename function that honors a
251 trailing slash, while others (like Solaris 5,6,7) have a rename
252 function that ignores a trailing slash. I believe the Linux
253 rename semantics are POSIX and susv2 compliant. */
255 if (remove_trailing_slashes)
256 strip_trailing_slashes (source);
258 if (dest_is_dir)
260 /* Treat DEST as a directory; build the full filename. */
261 char const *src_basename = last_component (source);
262 char *new_dest = file_name_concat (dest, src_basename, NULL);
263 strip_trailing_slashes (new_dest);
264 ok = do_move (source, new_dest, x);
265 free (new_dest);
267 else
269 ok = do_move (source, dest, x);
272 return ok;
275 void
276 usage (int status)
278 if (status != EXIT_SUCCESS)
279 fprintf (stderr, _("Try `%s --help' for more information.\n"),
280 program_name);
281 else
283 printf (_("\
284 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
285 or: %s [OPTION]... SOURCE... DIRECTORY\n\
286 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
288 program_name, program_name, program_name);
289 fputs (_("\
290 Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n\
292 "), stdout);
293 fputs (_("\
294 Mandatory arguments to long options are mandatory for short options too.\n\
295 "), stdout);
296 fputs (_("\
297 --backup[=CONTROL] make a backup of each existing destination file\n\
298 -b like --backup but does not accept an argument\n\
299 -f, --force do not prompt before overwriting\n\
300 -i, --interactive prompt before overwrite\n\
301 "), stdout);
302 fputs (_("\
303 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
304 argument\n\
305 -S, --suffix=SUFFIX override the usual backup suffix\n\
306 "), stdout);
307 fputs (_("\
308 -t, --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY\n\
309 -T, --no-target-directory treat DEST as a normal file\n\
310 -u, --update move only when the SOURCE file is newer\n\
311 than the destination file or when the\n\
312 destination file is missing\n\
313 -v, --verbose explain what is being done\n\
314 "), stdout);
315 fputs (HELP_OPTION_DESCRIPTION, stdout);
316 fputs (VERSION_OPTION_DESCRIPTION, stdout);
317 fputs (_("\
319 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
320 The version control method may be selected via the --backup option or through\n\
321 the VERSION_CONTROL environment variable. Here are the values:\n\
323 "), stdout);
324 fputs (_("\
325 none, off never make backups (even if --backup is given)\n\
326 numbered, t make numbered backups\n\
327 existing, nil numbered if numbered backups exist, simple otherwise\n\
328 simple, never always make simple backups\n\
329 "), stdout);
330 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
332 exit (status);
336 main (int argc, char **argv)
338 int c;
339 bool ok;
340 bool make_backups = false;
341 char *backup_suffix_string;
342 char *version_control_string = NULL;
343 struct cp_options x;
344 char *target_directory = NULL;
345 bool no_target_directory = false;
346 int n_files;
347 char **file;
349 initialize_main (&argc, &argv);
350 program_name = argv[0];
351 setlocale (LC_ALL, "");
352 bindtextdomain (PACKAGE, LOCALEDIR);
353 textdomain (PACKAGE);
355 atexit (close_stdout);
357 cp_option_init (&x);
359 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
360 we'll actually use backup_suffix_string. */
361 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
363 while ((c = getopt_long (argc, argv, "bfit:uvS:T", long_options, NULL))
364 != -1)
366 switch (c)
368 case 'b':
369 make_backups = true;
370 if (optarg)
371 version_control_string = optarg;
372 break;
373 case 'f':
374 x.interactive = I_ALWAYS_YES;
375 break;
376 case 'i':
377 x.interactive = I_ASK_USER;
378 break;
379 case REPLY_OPTION: /* Deprecated */
380 x.interactive = XARGMATCH ("--reply", optarg,
381 reply_args, reply_vals);
382 error (0, 0,
383 _("the --reply option is deprecated; use -i or -f instead"));
384 break;
385 case STRIP_TRAILING_SLASHES_OPTION:
386 remove_trailing_slashes = true;
387 break;
388 case 't':
389 if (target_directory)
390 error (EXIT_FAILURE, 0, _("multiple target directories specified"));
391 else
393 struct stat st;
394 if (stat (optarg, &st) != 0)
395 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
396 if (! S_ISDIR (st.st_mode))
397 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
398 quote (optarg));
400 target_directory = optarg;
401 break;
402 case 'T':
403 no_target_directory = true;
404 break;
405 case 'u':
406 x.update = true;
407 break;
408 case 'v':
409 x.verbose = true;
410 break;
411 case 'S':
412 make_backups = true;
413 backup_suffix_string = optarg;
414 break;
415 case_GETOPT_HELP_CHAR;
416 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
417 default:
418 usage (EXIT_FAILURE);
422 n_files = argc - optind;
423 file = argv + optind;
425 if (n_files <= !target_directory)
427 if (n_files <= 0)
428 error (0, 0, _("missing file operand"));
429 else
430 error (0, 0, _("missing destination file operand after %s"),
431 quote (file[0]));
432 usage (EXIT_FAILURE);
435 if (no_target_directory)
437 if (target_directory)
438 error (EXIT_FAILURE, 0,
439 _("Cannot combine --target-directory (-t) "
440 "and --no-target-directory (-T)"));
441 if (2 < n_files)
443 error (0, 0, _("extra operand %s"), quote (file[2]));
444 usage (EXIT_FAILURE);
447 else if (!target_directory)
449 assert (2 <= n_files);
450 if (target_directory_operand (file[n_files - 1]))
451 target_directory = file[--n_files];
452 else if (2 < n_files)
453 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
454 quote (file[n_files - 1]));
457 if (backup_suffix_string)
458 simple_backup_suffix = xstrdup (backup_suffix_string);
460 x.backup_type = (make_backups
461 ? xget_version (_("backup type"),
462 version_control_string)
463 : no_backups);
465 hash_init ();
467 if (target_directory)
469 int i;
471 /* Initialize the hash table only if we'll need it.
472 The problem it is used to detect can arise only if there are
473 two or more files to move. */
474 if (2 <= n_files)
475 dest_info_init (&x);
477 ok = true;
478 for (i = 0; i < n_files; ++i)
479 ok &= movefile (file[i], target_directory, true, &x);
481 else
482 ok = movefile (file[0], file[1], false, &x);
484 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);