To move a file or rename a file you would use the mv command. Here the file name gets changed from first.txt to second.txt.
$ mv first.txt second.txt
move the file file1 from the current working directory to the /tmp directory you would run:
mv file1 /tmp
To rename a file you need to specify the destination file name:
mv file1 file2
The syntax for moving directories is the same as when moving files. In the following example, if the dir2
directory exists, the command will move dir1
inside dir2
. If dir2
doesn’t exist, dir1
will be renamed to dir2
:
mv dir1 dir2
To move multiple files and directories, specify the files you want to move as the source. For example, to move the files file1
and file2
to the dir1
directory you would type:
mv file1 file2 dir1
The mv
command also allows you to use pattern matching. For example, to move all pdf
files from the current directory to the ~/Documents
directory, you would use:
mv *.pdf ~/Documents
In some Linux distributions, mv
may be an alias to the mv
command with a custom set of options. For example, in CentOS mv
is an alias to mv -i
. You can find whether mv
is an alias using the type
command:
type mv
If mv
is alias the output will look something like this:
mv is aliased to `mv -i'
If you try to overwrite a read-only file, the mv
command will prompt you whether you want to overwrite the file
mv -i file1 /tmp
mv: replace '/tmp/file1', overriding mode 0400 (r--------)?
To avoid being prompted use the -f
options
mv -f file1 /tmp
The -n
option tells mv
never to overwrite any existing file
mv -n file1 /tmp
If the destination file exists you can create a backup of it using the -b
option
mv -b file1 /tmp
The backup file will have the same name as the original file with a tilde (~
) appended to it.
Use the ls command to verify that the backup was created
The backup file will have the same name as the original file with a tilde (~
) appended to it.
Use the ls command to verify that the backup was created
ls /tmp/file1*
/tmp/file1 /tmp/file1~
Another option that can be useful is -v
. When this option is used, the command prints the name of each moved file:
mv -i file1 /tmp
renamed 'file1' -> '/tmp/file1'
By default, if the destination file exists, it will be overwritten. To prompt for confirmation, use the -i
option
mv -i file1 /tmp
mv: overwrite '/tmp/file1'?
Create backup of destination file
--backup [=CONTROL]
Create backup file without argument
-b
Do not prompt before overwriting
-f
Prompt before overwriting files
-i, interactive
Not overwrite an existing fileNot overwrite an existing file
-n, --no-clobber
Move all source arguments into directory
-t, --target-directory=DIRECTORY
Treat destination as a normal file
-T, --no-target-directory
Move when source file is newer than the destination file either destination file is missing
-u, --update
Prompt what is happening
-v, --verbose
Displays a help message and then exits
--help