Now I want a file which is
foo.bar to be accessible(
rwx) only by
g1 group. I typed the following for this purpose:
sudo chown u1:g1 foo.bar
sudo chmod 700 foo.bar
This will give permissions on the file for user
u1 (only). The group you've set the file to doesn't really matter since members of the group don't have any permissions set. Or rather, they have exactly the same permissions as "others", so it doesn't matter if a given user access is determined by the "group" permissions or the "other" permissions.
Note that you can't directly require both the user and the group to match. The above file will be accessible to
u1 regardless of their group membership.
What you can do, is create a directory owned by e.g.
root.g1, accessible only by user and group; and then a file within it that is owned by
u1 and accessible only by the user. This is most often done for e.g. crontabs, which are owned by a particular user, but should only be modified by a particular (setgid) tool. See e.g.
/var/spool/cron/crontabs/ on any Debian/Ubuntu system.
What is the usage of giving a file ownership to a group where we can restrict other users using chmod command ... I only want
foo.bar to be accessible from
g1 users and not any [other] users in the system.
You set the file's group to
g1, grant any access you like to the group. E.g.
chown a.g1 file && chmod 660 file would only let user
a and members of group
g1 read and write the file. (In addition, user
a can change the permissions. If you want to prevent that, you'll need to make the file owned by some user that will not do that.)
how we can give specific permissions to a specific group ? for example I want
g1 group to have only read permission on any files which is owned by it.
You can't. The permissions are a property of the file, not the user or group. In the above case, the file was given read/write permissions to the group, so that's what happens. You'll need to take care to not let any files have write permissions for the group, if that's what you want.
[the question from the comment]
chown is mainly used for giving ownership to a group so later we can limit the group users to the file by using
chmod command yes? otherwise we can restrict all other users except the owner by using
chmod alone and there is no need to use
Well, pretty much. Of course,
root can use
chown to actually change the owning user too, if that's warranted. That will happen at least under the hood when creating a new user: the ownership of the home directory has to be set somehow.
(If the user's primary group is appropriate, you could have a use for
chown, but that's just skipping an unnecessary