- How can I retrospectively create a default home directory for an existing user in terminal?
- 5 Answers 5
- Creating Home Directory for Existing Users in Linux
- We’ll discuss the importance of home directories, provide detailed instructions on creating them for existing users, and share valuable tips and troubleshooting advice.
- Key components of a Linux Home directory
- Why create a Home directory?
- A home directory offers several benefits:
- Create Home directory for existing users in Linux
- 1. Use the ‘usermod’ command
- 2. Use ls command to view the Home directories
- 3. Fixing missing directories and setting appropriate permissions
- 3. Copy existing data
- 4. Verify the new home directory
- Troubleshooting tips
- Conclusion
- 👥 Как создать домашний каталог для существующего пользователя Linux
- Создание домашнего каталога по умолчанию для существующего пользователя
- Заключение
How can I retrospectively create a default home directory for an existing user in terminal?
I created a user without a home directory and now I want to create a home directory for them. Not just a folder called /home/new-user , but a complete default home directory with all the normal folders and hidden files, etc. How can I do that?
When the user logs in, those subdirectories (Documents, Downloads, etc. ) will be automatically created. Although I’m searching for ways to «simulate» his login through the terminal.
@RaduRădeanu yeah I already tried that, also tried sudo -i -u new_user but it doesn’t work. I think we need to «simulate an X login». don’t know how to do that.
5 Answers 5
Use the following (as root, or with sudo if not root):
mkhomedir_helper username
For this to work, folder /home/username must not exist.
For X-related folders (Desktop, Downloads, etc), you will need to login in a graphics environment; they will be automatically generated the first time you login.
Simple and useful. This way you also can be sure that the newly created home dir is compliant with your system policies, without ever knowing them or any manual tinkering.
Don’t forget to check the directory’s permissions with ls -l /home . I found that the new directory was readable by all other users, so I removed those permissions with chmod go-r-x /home/username .
The subdirectories (Documents, Downloads, etc. ) are automatically created when the user first logs in through GNOME, provided that the home directory is created with the correct permissions. Here’s a demonstration:
alaa@aa-lu:~$ sudo useradd testinguser alaa@aa-lu:~$ sudo passwd testinguser Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully alaa@aa-lu:~$ sudo ls -l /home total 20 drwxr-xr-x 55 alaa alaa 4096 Aug 22 22:00 alaa drwx------ 2 root root 16384 Jun 5 09:46 lost+found alaa@aa-lu:~$ sudo mkdir /home/testinguser alaa@aa-lu:~$ sudo chown testinguser:testinguser /home/testinguser alaa@aa-lu:~$ ls -l /home total 24 drwxr-xr-x 55 alaa alaa 4096 Aug 22 22:00 alaa drwx------ 2 root root 16384 Jun 5 09:46 lost+found drwxr-xr-x 2 testinguser testinguser 4096 Aug 23 10:03 testinguser alaa@aa-lu:~$ ls -l /home/testinguser/ total 0 alaa@aa-lu:~$
You can check that the user’s home directory is correctly set by checking the entry in /etc/passwd . You should, by default, see the home directory set to /home/testinguser :
alaa@aa-lu:~$ grep testinguser /etc/passwd testinguser:x:1001:1001::/home/testinguser:/bin/sh
If you don’t see the home directory /home/testinguser there, you’ll need to execute the command sudo usermod -d /home/testinguser testinguser to update it, although you should not need to use this command because it should be set by default (according to useradd ‘s manpages).
I then logged out of my account, and logged back in with testinguser , and here are the subdirectories automatically created:
alaa@aa-lu:~$ ls -l /home/testinguser/ total 36 drwxr-xr-x 2 testinguser testinguser 4096 Aug 23 10:05 Desktop drwxr-xr-x 2 testinguser testinguser 4096 Aug 23 10:05 Documents drwxr-xr-x 2 testinguser testinguser 4096 Aug 23 10:05 Downloads drwxr-xr-x 2 testinguser testinguser 4096 Aug 23 10:05 Music drwxr-xr-x 2 testinguser testinguser 4096 Aug 23 10:07 Pictures drwxr-xr-x 2 testinguser testinguser 4096 Aug 23 10:05 Public drwxr-xr-x 2 testinguser testinguser 4096 Aug 23 10:05 Templates drwxr-xr-x 2 testinguser testinguser 4096 Aug 23 10:05 Videos
I didn’t need to copy the contents of /etc/skel .
If possible, can you please try following these steps, creating another new user? Once you’re done, you can remove this new user by sudo deluser testinguser && sudo rm -r /home/testinguser .
If all of this did not work with you, then I’m guessing it’s a bug.
Creating Home Directory for Existing Users in Linux
We’ll discuss the importance of home directories, provide detailed instructions on creating them for existing users, and share valuable tips and troubleshooting advice.
T oday, I’d like to share with you one of my favorite tips: creating home directories for existing users in Linux. This article will explain the purpose of creating home directories, offer tips and tricks to make the process smoother, and provide troubleshooting tips for when things go awry.
Key components of a Linux Home directory
Pop_OS Home Directory Example
A home directory in a Linux system as shown in the above screenshot is a user’s personal workspace that typically contains the following:
It’s important to note that the contents of a home directory may vary depending on the user’s preferences, installed applications, and system configuration.
Why create a Home directory?
The home directory serves as a user’s personal space on a Linux system. This is where users can store their personal files, configuration files, and other important data. By default, a home directory is created for each user when the account is created. However, there might be instances when you need to create a home directory for an existing user, such as when migrating users from one system to another or when a home directory gets deleted accidentally.
A home directory offers several benefits:
- Isolation: Each user has their own private space, which helps maintain privacy and keeps the system organized.
Create Home directory for existing users in Linux
Here are some tips and tricks to make creating home directories for existing users a breeze:
1. Use the ‘usermod’ command
To create a home directory for an existing user, use the ‘usermod’ command with the ‘-m’ (move) and ‘-d’ (directory) options.
sudo usermod -m -d /home/new_directory username
Replace ‘new_directory’ with the desired home directory name and ‘username’ with the appropriate user.
For example, I would use the following command:
sudo usermod -m -d /home/New_Projects divya
Creating New_Projects Home directories for divya
You should see no output. That’s normal behavior.
2. Use ls command to view the Home directories
You can use the ls command to view the contents of the new home directory created in Step 1:
sudo ls -la /home/New_Projects
Viewing Home directory contents
The -la option will show all files and directories, including hidden ones (those starting with a dot), and display detailed information such as permissions, ownership, and modification date. As you can notice in the example screenshot above, all those directories were automatically created. However, two directories “Documents” and “Desktop,” are missing.
3. Fixing missing directories and setting appropriate permissions
It’s possible that the “Desktop” and “Documents” directories are missing because they were not present in the user’s original home directory when I moved it using the usermod command. Alternatively, they may not have been created automatically by the desktop environment or distribution-specific settings on my Pop!_OS system. If you are curious and in the same boat as me, you can manually create these directories in the user’s new home directory with the mkdir command:
sudo mkdir /home/New_Projects/Desktop
sudo mkdir /home/New_Projects/Documents
After creating the directories, ensure they have the correct ownership:
sudo chown divya:divya /home/New_Projects/Desktop
sudo chown divya:divya /home/New_Projects/Documents
You can also set the appropriate permissions if necessary:
sudo chmod 755 /home/New_Projects/Desktop
sudo chmod 755 /home/New_Projects/Documents
The user “divya” should now have the “Desktop” and “Documents” directories in their home directory, and you should see them when running:
sudo ls -la /home/New_Projects
Desktop and Documents are now added
3. Copy existing data
If you want to copy the data from the user’s old home directory to the new one, use the ‘cp’ command with the ‘-a’ option to preserve file attributes:
sudo cp -a /home/old_directory/* /home/new_directory/
4. Verify the new home directory
After creating the home directory, you can also verify it by checking the user’s entry in the ‘/etc/passwd’ file:
So, in my illustrative example, I would use:
Here is the output showing successful home directories creation.
Home Directory created verification using grep command
Troubleshooting tips
In case you encounter issues while creating home directories for existing users, here are some troubleshooting tips:
1. Ensure the user exists: Before creating a home directory, make sure the user exists on the system. Use the ‘id’ command:
2. Check for existing home directories: If the user already has a home directory, you might want to back up the data before creating a new one.
3. Verify the new home directory: After creating the home directory, verify it by checking the user’s entry in the ‘/etc/passwd’ file:
4. Inspect system logs: If you still face issues, consult the system logs, like ‘/var/log/auth.log’, for more information.
Conclusion
In this article, we’ve explored the importance of home directories in Linux, offered tips and tricks to make the process easier, and provided troubleshooting tips for common issues. Creating a home directory for existing users is a valuable skill for any Linux user, and I hope these insights have been helpful. As always, remember to test your changes in a safe environment and always back up critical data before making any significant modifications to your system. Good luck, and happy Linux-ing!
👥 Как создать домашний каталог для существующего пользователя Linux
По умолчанию, когда вы создаете пользователя в Linux, домашний каталог создается в каталоге /home.
Возможно вы заметили, что в производных дистрибутивах Ubuntu и Debian команда useradd по умолчанию не будет создавать домашний каталог.
Давайте представим ситуацию, что вы уже создали пользователя, но домашний каталог отсутствует.
В этом руководстве я покажу вам, как создать домашний каталог по умолчанию для существующего пользователя в системах Linux.
Создание домашнего каталога по умолчанию для существующего пользователя
В примере я использую Ubuntu 20.04 и собираюсь создать пользователя с именем ‘bob’ с помощью команды useradd:
$ grep bob /etc/passwd bob:x:1003:1003::/home/bob:/bin/sh $
Если я попытаюсь войти в систему от этого пользователя, используя su -, система показывает logging in with Home=/
Это означает, что домашний каталог пользователя не создан.
$ su - bob Password: No directory, logging in with HOME=/ $
В Linux домашним каталогом пользователя по умолчанию является /home.
Чтобы создать домашний каталог по умолчанию, используйте команду mkhomedir_helper.
Обязательно запустите команду mkhomedir_helper от имени пользователя root или пользователя с доступом sudo.
$ sudo mkhomedir_helper bob
$ ls -al /home/bob total 20 drwxr-xr-x 2 bob bob 4096 Jun 1 02:26 . drwxr-xr-x 5 root root 4096 Jun 1 02:26 .. -rw-r--r-- 1 bob bob 220 Jun 1 02:26 .bash_logout -rw-r--r-- 1 bob bob 3771 Jun 1 02:26 .bashrc -rw-r--r-- 1 bob bob 807 Jun 1 02:26 .profile
В графической среде (например, GNOME или XFCE), если вам не хватает подкаталогов в домашнем каталоге, пользователь должен выйти из системы и войти обратно.
При первом входе пользователя в систему все подкаталоги, такие как папки Pictures, Documents, Videos, и Downloads , могут быть созданы в домашнем каталоге.
Другой метод – удалить пользователя и создать нового пользователя с помощью параметра -m или –create-home.
Следующая команда создает домашнюю папку (-m) и задаст указанный домашний каталог (-d) в качестве значения для входа нового пользователя:
$ sudo useradd -m -d /home/bob01 bob01
Заключение
В заключение, если вы являетесь поклонником Ubuntu, вы должны теперь использовать команду adduser.
Если у вас уже есть пользователь, теперь вы сможете добавить каталог по умолчанию.