Blog / Linux/ How to Move All Contents from a Directory in Linux Using the mv Command

How to Move All Contents from a Directory in Linux Using the mv Command

Linux mv 命令详解:如何移动文件夹下的所有内容

Moving All Contents from One Directory to Another in Linux

In Linux, the mv command is used to move files and directories. To move all contents (including files and subdirectories) from one folder to another, you can use the wildcard *.

Basic Command Format

mv source_directory/* target_directory

This command moves all files and folders from source_directory into target_directory, but does not move the source_directory itself.

Example Usage

To move all contents from /home/wwwroot/example.com/AAA to /home/wwwroot/example.com, use:

mv /home/wwwroot/example.com/AAA/* /home/wwwroot/example.com

Note: A trailing slash / on the target path is optional. Ensure the target directory exists.

Renaming with mv

The mv command can also rename files or directories. The syntax is the same: specify the old name as the source and the new name as the target.

Syntax and Common Options

Basic syntax:

mv [options] source target

Common options:

  • -i or --interactive: Prompt before overwriting.
  • -f or --force: Force overwrite without prompting.
  • -n or --no-clobber: Do not overwrite existing files.
  • -u or --update: Move only when source is newer than target or target is missing.
  • -v or --verbose: Show detailed output.
  • -b or --backup: Create a backup of overwritten files (default suffix: ~).

Important Considerations

  1. Permissions: The user must have read permission for the source and write permission for the target directory.
  2. Overwriting: By default, mv overwrites existing files with the same name. Use -i for interactive confirmation or -n to prevent overwrites in critical operations.
  3. Hidden Files: The * wildcard does not match hidden files (starting with .). To move hidden files, you can use mv source_directory/.* target_directory/, but be cautious as this also matches . and ... For safer handling, consider using rsync.
  4. Cross-Filesystem Moves: Moving between different filesystems (partitions) performs a copy-and-delete operation, which may take longer.

Alternative: Using rsync

For more complex or safer moves (especially with many files or when preserving permissions and symlinks), use rsync. Example to move and delete source files:

rsync -av --remove-source-files source_directory/ target_directory/

Afterward, remove the empty source directory with rmdir source_directory.

Post a Comment

Your email will not be published. Required fields are marked with *.