Changing ownership with chown
- Version
- unversioned
- Review
- Draft
Summary#
chown changes the owner, the group or both. On Linux, changing the owner requires the CAP_CHOWN capability, which root normally has. A file's owner without it can change the group only to one the owner belongs to.
Syntax#
chown user file
chown user:group file
chown :group file
chown -R user:group directory
chown -h user:group symbolic_link
Giving files to another account usually means running the command as root.
Example#
This example works without privileges because it assigns your own user and group to files that you create.
(
set -eu
dir=$(mktemp -d)
trap 'rm -rf -- "$dir"' EXIT
cd "$dir"
mkdir data
: > data/report.txt
ln -s report.txt data/latest
owner="$(id -u):$(id -g)"
chown -R "$owner" data
test "$(stat -c '%u:%g' data/report.txt)" = "$owner"
echo 'report.txt has your user and group'
chown ":$(id -g)" data/report.txt
echo 'group-only change accepted'
chown -h "$owner" data/latest
test "$(stat -c '%u:%g' data/latest)" = "$owner"
echo 'the link itself has your user and group'
)
Expected output#
report.txt has your user and group
group-only change accepted
the link itself has your user and group
Common mistakes#
A trailing colon changes the group: chown alice: file also sets it to Alice's login group, while chown alice file leaves the group alone. On a symbolic link, a non-recursive chown acts on the target; use -h to change the link itself. Check the directory before running -R. A change of owner or group can clear set-user-ID and set-group-ID bits on executables and removes file capabilities.
Version applicability#
This entry describes GNU coreutils chown on Linux. The stat -c format in the example is GNU-style.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0