How to Create a Shared Directory for All Users in Linux
As a system administrator, you may have a certain directory that you want to give read/write access to every user on a Linux server. In this guide, we will review how to enable write access to all users on a particular directory (shared directory) in Linux.
This calls for setting the appropriate access permissions, and the most effective as well as reliable method to allocating a common group for all the users who will share or have write access to the specific directory.
So, start by creating the directory and common group in case it doesn’t already exist on the system as follows:
$ sudo mkdir -p /var/www/reports/ $ sudo groupadd project
Then add an existing user who will have write access to the directory: /var/www/reports/ to the group project as below.
$ sudo usermod -a -G project tecmint
The flags and arguments used in the above command are:
- -a – which adds the user to the supplementary group.
- -G – specifies the group name.
- project – group name.
- tecmint – existing username.
Afterwards, proceed to configure the appropriate permissions on the directory, where the option -R enables recursive operations into subdirectories:
$ sudo chgrp -R project /var/www/reports/ $ sudo chmod -R 2775 /var/www/reports/
Explaining the permissions 2775 in the chmod command above:
- 2 – turns on the setGID bit, implying–newly created subfiles inherit the same group as the directory, and newly created subdirectories inherit the set GID bit of the parent directory.
- 7 – gives rwx permissions for owner.
- 7 – gives rwx permissions for group.
- 5 – gives rx permissions for others.
You can create more system users and add them to the directory group as follows:
$ sudo useradd -m -c "Aaron Kili" -s/bin/bash -G project aaronkilik $ sudo useradd -m -c "John Doo" -s/bin/bash -G project john $ sudo useradd -m -c "Ravi Saive" -s/bin/bash -G project ravi
Then create subdirectories where the new users above will store their project reports:
$ sudo mkdir -p /var/www/reports/aaronkilik_reports $ sudo mkdir -p /var/www/reports/johndoo_reports $ sudo mkdir -p /var/www/reports/ravi_reports
Now you can create files/folders and share with other users on the same group.
That’s it! In this tutorial, we reviewed how to enable write access to all users on a particular directory. To understand more about users/groups in Linux, read How to Manage Users/Groups File Permissions and Attributes.
Remember to offer us your thoughts about this article via the feedback form below.
Aaron Kili is a Linux and F.O.S.S enthusiast, an upcoming Linux SysAdmin, web developer, and currently a content creator for TecMint who loves working with computers and strongly believes in sharing knowledge.
Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.
Related Posts
15 thoughts on “How to Create a Shared Directory for All Users in Linux”
“The standard behavior for new files and sub-directories is to ALWAYS receive the creator’s GROUP” – RHCSA RHEL 8, A. Ghori, 1st edition. In the example of this tutorial, I do not understand why we enabled setgid for the directory SINCE all the system users created (aaronkilik, john, and ravi) belong to the same group (called “project“) as the group of the parent directory “reports” (sudo chgrp -R project /var/www/reports/). I mean if the user aaronkilik or any other of the two users create a file or sub-directory in “reports“, since the aaronkilik belongs to the group called “project“, the file/sub-directory created receives the creator’s group like stated in the first phase, that is the group “project“. Why is it needed to enabled setgid for the “project” directory? Maybe there is a reason but I do not see it now. I could see the reason to enable setgid in case the three system users created belonged to different groups (in this case chmod -R 2777 /var/www/reports/ would be needed too). Thank you. Reply
Hi, Need help to set up multiple project-wise Shared Directory via GUI panel on Ubuntu on currently running the server? Reply
What if a user copies or moves a directory tree from his home directory to the shared one?
I don’t think the subdirs will magically change their group, let atone recursivelyy because they are not newly created… Reply
@Evi1 That’s correct, including the recursive option allows subdirectories to be get top directory permissions automatically. Many thanks for the heads up. Reply
Hi, I think that you do not need 2775. More secure is to use chmod -R 2770. In this case only the desired users/group can access this shared folder, and any others will not have access. Reply
@lulian Yap, your correct, we should have used chmod -R 2770, other system users will be blocked from accessing a shared directory. However, always set permissions depending on your environment needs. Reply
In my case, i needed the shared folder were shared also with apache. I had to use “chmod -R 2775”. If I used “chmod -R 2770”, apache couldn’t access to the folders. Reply
Как сделать общую сетевую папку в Linux (настройка SMB в Linux)
Начните с установки пакетов samba и smbclient.
В Debian, Linux Mint, Ubuntu, Kali Linux и их производных для установки samba выполните команду:
sudo apt install samba smbclient
В Arch Linux, BlackArch и их производных выполните команду:
sudo pacman -S samba smbclient
Следующая команда не сработает, если отсутствует файл /etc/samba/smb.conf. Если у вас тоже нет этого файла, то создаёте его заглушку — к настройке самого файла smb.conf мы вернёмся позже:
sudo touch /etc/samba/smb.conf
Теперь нужно добавить пароль для пользователя Samba. Действует следующее правило: имя пользователя должно быть таким же, как у вашего текущего пользователя, а пароль можно установить иной, отличный от вашего системного пароля.
Для установки пароля Samba, выполните следующую команду:
Если вы хотите, чтобы у пользователя не было пароля, то укажите опцию -n.
Создайте папку, которая станет совместно используемой:
Узнаем абсолютный путь до папки ~/linuxshare:
Откройте для редактирования файл /etc/samba/smb.conf:
sudo gedit /etc/samba/smb.conf
Добавьте туда строки вида:
[ИМЯ_ПАПКИ] comment = Samba на Linux path = /home/ИМЯ_ПОЛЬЗОВАТЕЛЯ/ИМЯ_ПАПКИ valid users = ИМЯ_ПОЛЬЗОВАТЕЛЯ read only = no browsable = yes
Обратите внимание, что все пробелы в строках выше являются обязательными.
Для моих данных это строки:
[linuxshare] comment = Samba на Linux path = /home/mial/linuxshare valid users = mial read only = no browsable = yes
Теперь запустим службу SMB:
sudo systemctl start smb.service
Для добавления службы в автозагрузку выполните:
sudo systemctl enable smb.service
Для подключения к этой общей сетевой папке на Linux нужно использовать IP адреса компьютера Linux.
Создадим файл, чтобы сетевая папка не была пустой:
echo "Документ на Linux" > ~/linuxshare/document.txt
Посмотрите локальный IP адрес компьютера, на котором запущена Linux:
У меня этим IP является 192.168.0.89, а папку, как мы помним, я создал с именем linuxshare, тогда в Windows я перехожу в проводнике во вкладку «Сеть» и подключаюсь к этой папке следующим образом:
Вводим учётные данные (которые мы установили командой smbpasswd):
Видим содержимое совместно используемой папки, размещённой на Linux с помощью SMB:
Для подключения к сетевой папке из консоли Linux, запустите команду вида:
sudo smbclient //IP_АДРЕС/Папка -U ПОЛЬЗОВАТЕЛЬ
sudo smbclient //192.168.0.89/linuxshare -U mial
После ввода пароля нам становится доступным содержимое сетевой папки.
get full path to shared directory
Purpose of the script is to enter in shared folder and trigger another script within it, but the script newscript doesn’t work if it do not get full path. Here $HOST is machine name, projects is shared folder on my machine. Its actual path is C:\Users\vikram\HOME\share . I have shared it with advanced sharing options where we can share the folder with some different name. (Here it’s projects .) After entering in the directory and after doing pwd I get //VIKRAM/projects . Here I want its actual absolute path in any way. I am using Windows 10 as OS and Cygwin as terminal.
1 Answer 1
If you want to execute your script in current directory. Add to your script this:
source $/newscript or . $/newscript
Hi spybull, thanks for answering ; but my issue is I need complete expanded path of $PROJDIR to correctly run the newscript. newscript will not work unless it knows the absolute path of projects, newscripts validates the path ; if it is not like : C:\Users\vikram\HOME\share then it will give error, see; projects is shared directory on all my networked machines, it’s net share path is //$HOST/projects but on client machine actual absolute path may vary!
so the prior script need to be such that it will find shared projects directory and then will get it’s absolute path on any machine.
you can try readlink -f $