chown 改变文件的属主或属组

作用

chown 命令用来改变文件的属主或属组。

文件的属性包括文件属主或属组,文件的创建者默认为文件的属主(所有者),文件的属组默认为文件创建者所属的工作组。属主用户对自己创建的文件具有最大的权限,操作权限可以和操作用户相媲美。

一个用户可以位于多个组内,因此一个文件可以位于多个组内,同一组内的用户对文件具有共享的权限。

注意:设置属组的格式为“属主名:属组名”,如:“hxstrive:root”将文件属主设置为 hxstrive,属组设置为 root。如果我们省略属组,如:“hxstrive:”那么属组将采用属主所属的用户组;如果我们省略属主,如:“:root”则仅仅修改属组。

语法

chown [-cfhRv][--dereference][--help][--version][拥有者:<所属群组>][文件或目录..]
chown [-chfRv][--dereference][--help][--version][:所属群组][文件或目录... ...]
chown [-cfhRv][--dereference][--help][--reference=<参考文件或目录>][--version][文件或目录...]

参数

  • -c或--changes  效果类似"-v"参数,但仅回报更改的部分。 

  • -f或--quite或--silent  不显示错误信息。 

  • -h或--no-dereference  只对符号连接的文件作修改,而不更动其他任何相关文件。 

  • -R或--recursive  递归处理,将指定目录下的所有文件及子目录一并处理。 

  • -v或--version  显示指令执行过程。 

  • --dereference  效果和"-h"参数相同。 

  • --help  在线帮助。 

  • --reference=<参考文件或目录>  把指定文件或目录的拥有者与所属群组全部设成和参考文件或目 录的拥有者与所属群组相同。 

  • --version  显示版本信息。

更多其他选项:

  • -H  如果命令行的参数是指定到一个目录的符号链接,则递归访问该符号链接指向的目录

  • -L  在递归处理一个目录时,若遇到符号链接文件,则进行处理

  • -P  不处理符号链接文件

注意:如果在命令行指定多个选项,命令行则按照最后一个选项进行处理。

示例

(1)假如当前目录下面存在 demo.txt 文件,该文件的属主和属组均为 hxstrive。通过 chown 将属主修改为 root,属组还是保持为 hxstrive。命令如下:

# 查看 demo.txt 文件的属主和属组
[hxstrive@localhost ~]$ ll demo.txt 
-rwxrwxrwx. 1 hxstrive hxstrive 173 May 26 22:32 demo.txt

# 使用 sudo chown 修改文件属主
[hxstrive@localhost ~]$ sudo chown -v root demo.txt 

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for hxstrive: 
changed ownership of 'demo.txt' from hxstrive to root

# 查看结果
[hxstrive@localhost ~]$ ll demo.txt 
-rwxrwxrwx. 1 root hxstrive 173 May 26 22:32 demo.txt

(2)假如当前目录下面存在 demo.txt 文件,属主为 root,属组为 hxstrive。通过 chown 命令将 demo.txt 文件的属主和属组均设置为 root。如下:

# 查看 demo.txt 文件属主/属组信息
[hxstrive@localhost ~]$ ll demo.txt 
-rwxrwxrwx. 1 root hxstrive 173 May 26 22:32 demo.txt

# 通过 chown 命令修改属主和属组
[hxstrive@localhost ~]$ sudo chown -v root:root demo.txt
[sudo] password for hxstrive: 
changed ownership of 'demo.txt' from root:hxstrive to root:root

# 验证修改后的属主和属组
[hxstrive@localhost ~]$ ll demo.txt
-rwxrwxrwx. 1 root root 173 May 26 22:32 demo.txt

(3)假如当前目录下面存在 demo.txt 文件,使用 chown 修改文件属主,并且将文件属组修改为属主所属的用户组。如下:

# 查看 demo.txt 文件的属主和属组
[hxstrive@localhost ~]$ ll demo.txt 
-rwxrwxrwx. 1 root root 173 May 26 22:32 demo.txt

# 修改文件的属主和属组
[hxstrive@localhost ~]$ sudo chown -v hxstrive: demo.txt
changed ownership of 'demo.txt' from root:root to hxstrive:hxstrive

# 验证结果
[hxstrive@localhost ~]$ ll demo.txt 
-rwxrwxrwx. 1 hxstrive hxstrive 173 May 26 22:32 demo.txt

更多关于命令详细参考手册,请使用 man 命令或者 --help 参数获取帮助信息

关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号