SoFunction
Updated on 2025-03-09

Specific use of mv in shell command

The operating system is macOS 10.12.4

The mv command of the shell means moving (moving), which can actually be divided into moving between files, moving files to directories, and moving directories to directories.

mv parameter settings and operation results

Command format Running results
mv file name file name Change the source file name to the target file name
mv file name directory name Move the file to the target directory v
mv directory name directory name The target directory already exists, move the source directory to the target directory; if the target directory does not exist, change the name
mv directory name file name An error occurred

Move between files

mv source_file target_file

Move the file source_file to target_file, which actually means renaming and other unchanged, such as inode information, recent modification time point, etc.

In fact, there is no rename command, only the rename function.

If the file target_file already exists, you can add the -i parameter, and the system will prompt whether to overwrite it. You can also add the -n parameter to prevent the overwrite from happening.

The -f parameter is forced to overwrite, and there is no prompt. This is the same as mv without any parameters.

Move files to directories

mv source_file target_directory

This is relatively simple. But if the directory target_directory does not exist, then the move cannot be completed.

Move directory to directory

mv source_directory target_directory

This needs to be divided into two categories
- If the target_directory does not exist, it is equivalent to re-name the directory.
- If the target_directory exists, the entire source_directory directory will be moved to the target_directory directory, which is equivalent to cutting the entire directory and then pasting it.

However, if you want to move the contents in the source_directory directory to target_directory, mv source_directory/* target_directory

Example

# Rename file aaa to bbb$ mv aaa bbb

# Move file test2 test3 to directory testdr$ mv test2 test3 testdr

# Put the info directory into the logs directory.  Note that if the logs directory does not exist, the command renames info to logs.mv info/ logs 

# Move all files and directories under /usr/student to the current directory, and the command behavior is:$ mv /usr/student/*  . 

think

The mv command is actually done with cp and rm.

This is the article about the specific use of mv in shell commands. For more relevant shell commands, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!