How to use file permissions and ownership?

  1. Understanding file permissions and ownership: File permissions and ownership are important aspects of managing files in a UNIX/Linux system. File permissions specify who can read, write, or execute a file, while ownership specifies the user and group that have access to the file.

  2. Check the current permissions and ownership of a file: You can use the ls -l command to check the current permissions and ownership of a file. Here’s an example:

    1
    2
    $ ls -l myfile.txt
    -rw-r--r-- 1 user group 1024 Aug 31 22:24 myfile.txt

    In this example, the -rw-r--r-- part specifies the permissions of the file. The first letter (-) indicates that this is a file, and not a directory. The next three letters (rw-) indicate that the file owner (user in this case) has read and write permission, but not execute permission. The next three letters (r--) indicate that the group (group in this case) has only read permission, and the last three letters indicate that other users also have only read permission.

    The 1 after the permissions specifies the number of links pointing to this file, and the user and group after that specify the file owner and group, respectively. The 1024 specifies the file size, and the Aug 31 22:24 specifies the last modification time.

  3. Changing file ownership: You can use the chown command to change the ownership of a file. Here’s an example:

    1
    $ chown newuser myfile.txt

    This command changes the ownership of myfile.txt to newuser. You can also specify a group along with the user, like this:

    1
    $ chown newuser:newgroup myfile.txt

    This command changes the ownership of myfile.txt to newuser and the group to newgroup.

  4. Changing file permissions: You can use the chmod command to change the permissions of a file. Here’s an example:

    1
    $ chmod 644 myfile.txt

    This command changes the permissions of myfile.txt to -rw-r--r--, which means that the file owner has read and write permission, and everyone else has only read permission. You can also use letters to specify the permissions, like this:

    1
    $ chmod u=rw,g=r,o=r myfile.txt

    This command does the same thing as the previous example - it sets the owner permission to read and write (u=rw), sets the group permission to read (g=r), and sets the other permission to read (o=r).

  5. Combining ownership and permission changes: You can combine ownership and permission changes in a single command, like this:

    1
    $ chown newuser:newgroup myfile.txt && chmod 640 myfile.txt

    This command changes the ownership of myfile.txt to newuser:newgroup, and then changes the permissions of myfile.txt to -rw-r-----, which means that the file owner has read and write permission, the group has read permission, and others have no permission.

That’s it! With these basic commands, you can easily manage file permissions and ownership in a UNIX/Linux system.