
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
When working in Linux, moving files from one location to another without preserving permissions is not uncommon – for instance, when we want to reset the file permissions associated with the files during the move. Normally, the mv command is used for moving files. However, by default, it retains the file permissions of the moved files. For this reason, we’ll explore alternative methods.
In this quick tutorial, we examine two different approaches that we can use to achieve this task. First, we explore using the cp command in combination with the rm command. After that, we take a look at working with the rsync command.
The role of the cp command is to copy Linux files, whereas rm deletes files. Here, we’ll combine both commands to move files without preserving permissions.
Before we proceed, let’s first navigate into our working directory and explore the file to move:
$ ls -l Names.txt
-r--r--r-- 1 samuel samuel 30 Ago 29 01:17 Names.txt
Above, we’re detailing the permissions on the Names.txt file. In detail, this file contains read-only permissions for the owner samuel, user group samuel, and other system users as well.
Next, let’s move the Names.txt file:
$ cp --no-preserve=mode Names.txt Details/ && rm Names.txt
Let’s break down the command:
In this example, the permissions on the newly copied file are determined by the system’s umask value. To explain, umask is a command that determines the default permissions assigned to a file or directory upon creation.
Finally, let’s navigate to the Details directory and check its contents:
$ ls -l
total 0
-rw-rw-r-- 1 samuel samuel 30 Sep 10 12:52 Names.txt
At this point, we’ve managed to move the Names.txt file and also change its permissions in the process.
In Linux, the rsync command facilitates the copying and synchronizing of files and directories. So, let’s see how we can also use it to handle the task at hand. To demonstrate, we’ll use the same source file with the same permissions as in the previous example.
Now, let’s move the file:
$ rsync -a --chmod=ugo=rwX Names.txt Projects/ --remove-source-files
Let’s examine this command in detail:
Here, we moved the Names.txt file to the Projects directory while resetting its permissions.
Lastly, let’s explore the updated permissions on the Names.txt file:
$ ls -l
total 0
-rw-rw-rw- 1 samuel samuel 30 Ago 29 01:17 Names.txt
At this point, Names.txt contains read and write permissions for the owner, user group, and other system users.
In this article, we explored using both the cp and rsync commands to move a file without preserving its permissions. With cp, the copied file relies on the umask value to determine the copied file’s permissions. On the other hand, rsync allows us to specify the exact permissions we want the copied file to have.