dd: output final progress before syncing
[coreutils.git] / src / mv.c
blobb5eb169f380b8bc94d849d84dcb042ee0177bac0
1 /* mv -- move or rename files
2 Copyright (C) 1986-2022 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 3 of the License, or
7 (at your option) 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, see <https://www.gnu.org/licenses/>. */
17 /* Written by Mike Parker, David MacKenzie, and Jim Meyering */
19 #include <config.h>
20 #include <stdio.h>
21 #include <getopt.h>
22 #include <sys/types.h>
23 #include <assert.h>
24 #include <selinux/label.h>
26 #include "system.h"
27 #include "backupfile.h"
28 #include "copy.h"
29 #include "cp-hash.h"
30 #include "die.h"
31 #include "error.h"
32 #include "filenamecat.h"
33 #include "remove.h"
34 #include "renameatu.h"
35 #include "root-dev-ino.h"
36 #include "priv-set.h"
38 /* The official name of this program (e.g., no 'g' prefix). */
39 #define PROGRAM_NAME "mv"
41 #define AUTHORS \
42 proper_name ("Mike Parker"), \
43 proper_name ("David MacKenzie"), \
44 proper_name ("Jim Meyering")
46 /* For long options that have no equivalent short option, use a
47 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
48 enum
50 STRIP_TRAILING_SLASHES_OPTION = CHAR_MAX + 1
53 /* Remove any trailing slashes from each SOURCE argument. */
54 static bool remove_trailing_slashes;
56 static struct option const long_options[] =
58 {"backup", optional_argument, NULL, 'b'},
59 {"context", no_argument, NULL, 'Z'},
60 {"force", no_argument, NULL, 'f'},
61 {"interactive", no_argument, NULL, 'i'},
62 {"no-clobber", no_argument, NULL, 'n'},
63 {"no-target-directory", no_argument, NULL, 'T'},
64 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
65 {"suffix", required_argument, NULL, 'S'},
66 {"target-directory", required_argument, NULL, 't'},
67 {"update", no_argument, NULL, 'u'},
68 {"verbose", no_argument, NULL, 'v'},
69 {GETOPT_HELP_OPTION_DECL},
70 {GETOPT_VERSION_OPTION_DECL},
71 {NULL, 0, NULL, 0}
74 static void
75 rm_option_init (struct rm_options *x)
77 x->ignore_missing_files = false;
78 x->remove_empty_directories = true;
79 x->recursive = true;
80 x->one_file_system = false;
82 /* Should we prompt for removal, too? No. Prompting for the 'move'
83 part is enough. It implies removal. */
84 x->interactive = RMI_NEVER;
85 x->stdin_tty = false;
87 x->verbose = false;
89 /* Since this program may well have to process additional command
90 line arguments after any call to 'rm', that function must preserve
91 the initial working directory, in case one of those is a
92 '.'-relative name. */
93 x->require_restore_cwd = true;
96 static struct dev_ino dev_ino_buf;
97 x->root_dev_ino = get_root_dev_ino (&dev_ino_buf);
98 if (x->root_dev_ino == NULL)
99 die (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
100 quoteaf ("/"));
103 x->preserve_all_root = false;
106 static void
107 cp_option_init (struct cp_options *x)
109 bool selinux_enabled = (0 < is_selinux_enabled ());
111 cp_options_default (x);
112 x->copy_as_regular = false; /* FIXME: maybe make this an option */
113 x->reflink_mode = REFLINK_AUTO;
114 x->dereference = DEREF_NEVER;
115 x->unlink_dest_before_opening = false;
116 x->unlink_dest_after_failed_open = false;
117 x->hard_link = false;
118 x->interactive = I_UNSPECIFIED;
119 x->move_mode = true;
120 x->install_mode = false;
121 x->one_file_system = false;
122 x->preserve_ownership = true;
123 x->preserve_links = true;
124 x->preserve_mode = true;
125 x->preserve_timestamps = true;
126 x->explicit_no_preserve_mode= false;
127 x->preserve_security_context = selinux_enabled;
128 x->set_security_context = NULL;
129 x->reduce_diagnostics = false;
130 x->data_copy_required = true;
131 x->require_preserve = false; /* FIXME: maybe make this an option */
132 x->require_preserve_context = false;
133 x->preserve_xattr = true;
134 x->require_preserve_xattr = false;
135 x->recursive = true;
136 x->sparse_mode = SPARSE_AUTO; /* FIXME: maybe make this an option */
137 x->symbolic_link = false;
138 x->set_mode = false;
139 x->mode = 0;
140 x->stdin_tty = isatty (STDIN_FILENO);
142 x->open_dangling_dest_symlink = false;
143 x->update = false;
144 x->verbose = false;
145 x->dest_info = NULL;
146 x->src_info = NULL;
149 /* FILE is the last operand of this command. Return true if FILE is a
150 directory. But report an error if there is a problem accessing FILE, other
151 than nonexistence (errno == ENOENT). */
153 static bool
154 target_directory_operand (char const *file)
156 struct stat st;
157 int err = (stat (file, &st) == 0 ? 0 : errno);
158 bool is_a_dir = !err && S_ISDIR (st.st_mode);
159 if (err && err != ENOENT)
160 die (EXIT_FAILURE, err, _("failed to access %s"), quoteaf (file));
161 return is_a_dir;
164 /* Move SOURCE onto DEST. Handles cross-file-system moves.
165 If SOURCE is a directory, DEST must not exist.
166 Return true if successful. */
168 static bool
169 do_move (char const *source, char const *dest, const struct cp_options *x)
171 bool copy_into_self;
172 bool rename_succeeded;
173 bool ok = copy (source, dest, AT_FDCWD, dest, 0, x,
174 &copy_into_self, &rename_succeeded);
176 if (ok)
178 char const *dir_to_remove;
179 if (copy_into_self)
181 /* In general, when copy returns with copy_into_self set, SOURCE is
182 the same as, or a parent of DEST. In this case we know it's a
183 parent. It doesn't make sense to move a directory into itself, and
184 besides in some situations doing so would give highly nonintuitive
185 results. Run this 'mkdir b; touch a c; mv * b' in an empty
186 directory. Here's the result of running echo $(find b -print):
187 b b/a b/b b/b/a b/c. Notice that only file 'a' was copied
188 into b/b. Handle this by giving a diagnostic, removing the
189 copied-into-self directory, DEST ('b/b' in the example),
190 and failing. */
192 dir_to_remove = NULL;
193 ok = false;
195 else if (rename_succeeded)
197 /* No need to remove anything. SOURCE was successfully
198 renamed to DEST. Or the user declined to rename a file. */
199 dir_to_remove = NULL;
201 else
203 /* This may mean SOURCE and DEST referred to different devices.
204 It may also conceivably mean that even though they referred
205 to the same device, rename wasn't implemented for that device.
207 E.g., (from Joel N. Weber),
208 [...] there might someday be cases where you can't rename
209 but you can copy where the device name is the same, especially
210 on Hurd. Consider an ftpfs with a primitive ftp server that
211 supports uploading, downloading and deleting, but not renaming.
213 Also, note that comparing device numbers is not a reliable
214 check for 'can-rename'. Some systems can be set up so that
215 files from many different physical devices all have the same
216 st_dev field. This is a feature of some NFS mounting
217 configurations.
219 We reach this point if SOURCE has been successfully copied
220 to DEST. Now we have to remove SOURCE.
222 This function used to resort to copying only when rename
223 failed and set errno to EXDEV. */
225 dir_to_remove = source;
228 if (dir_to_remove != NULL)
230 struct rm_options rm_options;
231 enum RM_status status;
232 char const *dir[2];
234 rm_option_init (&rm_options);
235 rm_options.verbose = x->verbose;
236 dir[0] = dir_to_remove;
237 dir[1] = NULL;
239 status = rm ((void *) dir, &rm_options);
240 assert (VALID_STATUS (status));
241 if (status == RM_ERROR)
242 ok = false;
246 return ok;
249 /* Move file SOURCE onto DEST. Handles the case when DEST is a directory.
250 Treat DEST as a directory if DEST_IS_DIR.
251 Return true if successful. */
253 static bool
254 movefile (char *source, char *dest, bool dest_is_dir,
255 const struct cp_options *x)
257 bool ok;
259 /* This code was introduced to handle the ambiguity in the semantics
260 of mv that is induced by the varying semantics of the rename function.
261 Some systems (e.g., GNU/Linux) have a rename function that honors a
262 trailing slash, while others (like Solaris 5,6,7) have a rename
263 function that ignores a trailing slash. I believe the GNU/Linux
264 rename semantics are POSIX and susv2 compliant. */
266 if (remove_trailing_slashes)
267 strip_trailing_slashes (source);
269 if (dest_is_dir)
271 /* Treat DEST as a directory; build the full filename. */
272 char const *src_basename = last_component (source);
273 char *new_dest = file_name_concat (dest, src_basename, NULL);
274 strip_trailing_slashes (new_dest);
275 ok = do_move (source, new_dest, x);
276 free (new_dest);
278 else
280 ok = do_move (source, dest, x);
283 return ok;
286 void
287 usage (int status)
289 if (status != EXIT_SUCCESS)
290 emit_try_help ();
291 else
293 printf (_("\
294 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
295 or: %s [OPTION]... SOURCE... DIRECTORY\n\
296 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
298 program_name, program_name, program_name);
299 fputs (_("\
300 Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n\
301 "), stdout);
303 emit_mandatory_arg_note ();
305 fputs (_("\
306 --backup[=CONTROL] make a backup of each existing destination file\
308 -b like --backup but does not accept an argument\n\
309 -f, --force do not prompt before overwriting\n\
310 -i, --interactive prompt before overwrite\n\
311 -n, --no-clobber do not overwrite an existing file\n\
312 If you specify more than one of -i, -f, -n, only the final one takes effect.\n\
313 "), stdout);
314 fputs (_("\
315 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
316 argument\n\
317 -S, --suffix=SUFFIX override the usual backup suffix\n\
318 "), stdout);
319 fputs (_("\
320 -t, --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY\n\
321 -T, --no-target-directory treat DEST as a normal file\n\
322 -u, --update move only when the SOURCE file is newer\n\
323 than the destination file or when the\n\
324 destination file is missing\n\
325 -v, --verbose explain what is being done\n\
326 -Z, --context set SELinux security context of destination\n\
327 file to default type\n\
328 "), stdout);
329 fputs (HELP_OPTION_DESCRIPTION, stdout);
330 fputs (VERSION_OPTION_DESCRIPTION, stdout);
331 emit_backup_suffix_note ();
332 emit_ancillary_info (PROGRAM_NAME);
334 exit (status);
338 main (int argc, char **argv)
340 int c;
341 bool ok;
342 bool make_backups = false;
343 char const *backup_suffix = NULL;
344 char *version_control_string = NULL;
345 struct cp_options x;
346 char *target_directory = NULL;
347 bool no_target_directory = false;
348 int n_files;
349 char **file;
350 bool selinux_enabled = (0 < is_selinux_enabled ());
352 initialize_main (&argc, &argv);
353 set_program_name (argv[0]);
354 setlocale (LC_ALL, "");
355 bindtextdomain (PACKAGE, LOCALEDIR);
356 textdomain (PACKAGE);
358 atexit (close_stdin);
360 cp_option_init (&x);
362 /* Try to disable the ability to unlink a directory. */
363 priv_set_remove_linkdir ();
365 while ((c = getopt_long (argc, argv, "bfint:uvS:TZ", long_options, NULL))
366 != -1)
368 switch (c)
370 case 'b':
371 make_backups = true;
372 if (optarg)
373 version_control_string = optarg;
374 break;
375 case 'f':
376 x.interactive = I_ALWAYS_YES;
377 break;
378 case 'i':
379 x.interactive = I_ASK_USER;
380 break;
381 case 'n':
382 x.interactive = I_ALWAYS_NO;
383 break;
384 case STRIP_TRAILING_SLASHES_OPTION:
385 remove_trailing_slashes = true;
386 break;
387 case 't':
388 if (target_directory)
389 die (EXIT_FAILURE, 0, _("multiple target directories specified"));
390 else
392 struct stat st;
393 if (stat (optarg, &st) != 0)
394 die (EXIT_FAILURE, errno, _("failed to access %s"),
395 quoteaf (optarg));
396 if (! S_ISDIR (st.st_mode))
397 die (EXIT_FAILURE, 0, _("target %s is not a directory"),
398 quoteaf (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 = optarg;
414 break;
415 case 'Z':
416 /* As a performance enhancement, don't even bother trying
417 to "restorecon" when not on an selinux-enabled kernel. */
418 if (selinux_enabled)
420 x.preserve_security_context = false;
421 x.set_security_context = selabel_open (SELABEL_CTX_FILE, NULL, 0);
422 if (! x.set_security_context)
423 error (0, errno, _("warning: ignoring --context"));
425 break;
426 case_GETOPT_HELP_CHAR;
427 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
428 default:
429 usage (EXIT_FAILURE);
433 n_files = argc - optind;
434 file = argv + optind;
436 if (n_files <= !target_directory)
438 if (n_files <= 0)
439 error (0, 0, _("missing file operand"));
440 else
441 error (0, 0, _("missing destination file operand after %s"),
442 quoteaf (file[0]));
443 usage (EXIT_FAILURE);
446 if (no_target_directory)
448 if (target_directory)
449 die (EXIT_FAILURE, 0,
450 _("cannot combine --target-directory (-t) "
451 "and --no-target-directory (-T)"));
452 if (2 < n_files)
454 error (0, 0, _("extra operand %s"), quoteaf (file[2]));
455 usage (EXIT_FAILURE);
458 else if (!target_directory)
460 assert (2 <= n_files);
461 if (n_files == 2)
462 x.rename_errno = (renameatu (AT_FDCWD, file[0], AT_FDCWD, file[1],
463 RENAME_NOREPLACE)
464 ? errno : 0);
465 if (x.rename_errno != 0 && target_directory_operand (file[n_files - 1]))
467 x.rename_errno = -1;
468 target_directory = file[--n_files];
470 else if (2 < n_files)
471 die (EXIT_FAILURE, 0, _("target %s is not a directory"),
472 quoteaf (file[n_files - 1]));
475 if (x.interactive == I_ALWAYS_NO)
476 x.update = false;
478 if (make_backups && x.interactive == I_ALWAYS_NO)
480 error (0, 0,
481 _("options --backup and --no-clobber are mutually exclusive"));
482 usage (EXIT_FAILURE);
485 x.backup_type = (make_backups
486 ? xget_version (_("backup type"),
487 version_control_string)
488 : no_backups);
489 set_simple_backup_suffix (backup_suffix);
491 hash_init ();
493 if (target_directory)
495 /* Initialize the hash table only if we'll need it.
496 The problem it is used to detect can arise only if there are
497 two or more files to move. */
498 if (2 <= n_files)
499 dest_info_init (&x);
501 ok = true;
502 for (int i = 0; i < n_files; ++i)
504 x.last_file = i + 1 == n_files;
505 ok &= movefile (file[i], target_directory, true, &x);
508 #ifdef lint
509 dest_info_free (&x);
510 #endif
512 else
514 x.last_file = true;
515 ok = movefile (file[0], file[1], false, &x);
518 return ok ? EXIT_SUCCESS : EXIT_FAILURE;