- Как узнать домашнюю директорию любого пользователя Linux
- Где хранится системная информация о домашних каталогах пользователей в Linux
- Команда pwd в Unix
- Оператор
- How to Create Home Directory for Existing User in Linux
- Create default home directory for existing user
- Conclusion
- Linux Change Default User Home Directory While Adding A New User
- How Do I Change Existing User’s Home Directory?
Как узнать домашнюю директорию любого пользователя Linux
Для того, чтобы правильно и безопасно хранить данные на сервере, (особенно, если на этом сервере несколько пользователей), следует точно знать, где располагаются их домашние папки, до которых у пользователей есть доступ (у каждого в свою, но нет доступа в чужие папки с чужими данными). Например, для того, чтобы дать пользователю доступ по ftp только к его данным или подсказать полный путь до его www-директории. В этой статье рассмотрим то, как узнать домашнюю директорию любого пользователя Linux несколькими способами.
Где хранится системная информация о домашних каталогах пользователей в Linux
При создании нового пользователя в Unix-системах, каждому пользователю обязательно домашний каталог. О том, где и как располагается запись о домашней директории пользователя в файле /etc/passwd , подробно описано в → этой статье. Для понимания вопроса сейчас требуется знать, что это предпоследнее (шестое) поле home в строке записи пользователя в этом файле:
login : password : UID : GID : GECOS : home : shell
Поэтому, можно в цикле обходить этот файл в поиске записи нужного пользователя, разбивать строку на подстроки и брать значение 6-го поля. Но это слишком длинный способ. Есть короче и проще. 😉
Команда pwd в Unix
Команда pwd выводит текущий путь к директории, в которой находится пользователь. Выполнив команду pwd , получим этот путь:
У пользователя root в Unix по умолчанию домашней директорией является /root .
Оператор
(тильда) в Debian
Другой способ того, как определить домашнюю директорию текущего пользователя. Достаточно посмотреть значение оператора
Результат не сильно отличается от предыдущего, но к
можно добавлять дополнительные пути к папкам и/или файлам пользователя, используя её как точку отсчёта в домашней директории пользователя. Что сильно облегчает работу с написанием относительных путей (относительно не только корня файловой системы, но и корня домашней папки пользователя).
Ещё одним полезным свойством
является то, что с помощью этого оператора можно получить путь до домашней директории любого пользователя в системе (если конечно пользователь есть в системе, то есть прописан в файле /etc/passwd , например посмотреть содержимое домашнего каталога пользователя ftp можно так, поставив перед ним тильду
А теперь посмотреть содержимое этого файла:
Ну и то, к чему мы стремились: посмотреть путь к домашней директории пользователя:
Так гораздо удобнее, чем парсить и разбирать файл /etc/passwd . За нас всю эту работу делает операционная система! 😉
Источник
How to Create Home Directory for Existing User in Linux
By default when you create a user in Linux, users default home directory is created under /home. If you noticed on Ubuntu and Debian derivated distribution useradd command won’t create a home directory by default.
Let’s think of s situation where you have already created a user but the home directory is missing. In this tutorial, I will show you how to create a default home directory for an existing user in Linux.
Create default home directory for existing user
Here I am using Ubuntu 20.04 and going to create a user named ‘ bob’ using useradd command:
Useradd command has added an entry home directory in /etc/passwd file
If I try to login as the user using su — , it shows that it’s logging in with Home=/ . This means the user home directory is not created.
In Linux, a user’s default home directory is /home. To create a default home directory use mkhomedir_helper command.
Make sure to run mkhomedir_helper command as root or user with sudo access.
The previous command creates a home directory named «/home/bob» and user settings files.
For a graphical environment (such as GNOME or XFCE ), if you are missing subdirectories in the home directory, the user needs to log out and log in back.
When the user login the first time all subdirectories such as Pictures, Documents, Videos, and Downloads folders can be created in the home directory.
Another method is to delete the user and create a new user using -m or —create-home option.
The following command creates a home folder (-m) and set the specified home directory (-d) as the value for the new user’s login:
Conclusion
To conclude, If you are a Ubuntu fan you should be now using adduser command, it’s recommended by Debian. If you have an existing user, now you should be able to add default directory.
Thanks for reading and please drop your suggestions on the below comment section.
Источник
Linux Change Default User Home Directory While Adding A New User
B y default base directory for the system user is set to /home directory. I’d like to add user to /iscsi/home/$
Default values for account creation defined in /etc/default/useradd file under CentOS / RHEL / Fedora / Debian / Ubuntu and other Linux distros. Simply open this file using a text editor, type:
# vi /etc/default/useradd
The default home directory defined by HOME variable, find line that read as follows:
HOME=/home
Replace with:
HOME=/iscsi/user
Save and close the file. Now you can add user using regular useradd command:
# useradd vivek
# passwd vivek
Verify user information:
# finger vivek
Output:
How Do I Change Existing User’s Home Directory?
You need to use the usermod command to set the user’s new login directory. The syntax is as follows:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
- -d dirnanme : Path to new login (home) directory.
- -m : The contents of the current home directory will be moved to the new home directory, which is created if it does not already exist.
In this example set the user’s new login directory to /users/v/vivek from /home/vivek, enter:
# usermod -m -d /users/v/vivek vivek
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
or specify the home with -d in useradd command
Nice…info…but it doesnt work ;_( it still gives same error as before changeing in /etc/default/usradd
]# useradd -d /root/lvm/ mas
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.
Hi All,
Anyone who can teach me the solution for this problem:
I add a user jayabellon using this command:
useradd -u 888 -g oinstall -G dba -d /home/jayabellon -r jayabellon
i forgot to create home directory when I log-In so it prompts me cannot go to that directory.
I deleted the user and retry to create again.
But still, when I log-In, this is what it looks like:
-bash-3.00$
I am expecting it to be
[user@hostname]$
this is my entry in /etc/passwd:
jayabellon:x:888:501:jayabellon:/home/jayabellon:/bin/bash
actually, i am only working in a test server. Nothing much critical on this one.
It’s just that its my first time to create user using command line, because i usually do it in GUI based.
Even I have the same problem. If you get any solution please mail me. One solution I can give that re-install the operating system,even I did the same.
-bash-3.00$ finger jayabellon
Login: jayabellon Name: jayabellon
Directory: /home/jayabellon Shell: /bin/bash
Never logged in.
No mail.
No Plan.
Pass -m option to useradd command to create users home dir.
it’s in man page also.
found that it’s faster to create user in command line rather than using GUI Administration tool.
Any chance you can provide a similar command for Oracle SQL?
Thanks. I’ve been wondering how to change the default home directory for a while now. Glad I found this to explain how.
Your comment is awaiting moderation.
This is just nonsense of a blog, when the same thing can be achieved with usermod command with -d option to change the home directory.
It’s really not “nonsense of a blog.” The whole point is so that it is a default, so you DON’T have to do the -d option every time. Why make things harder on yourself? Set all the defaults in the config files, and then just useradd and be done with it.
home directory already exits.
not copying any file from skel directory into it
when i login to oracle user it show me
-bash-3.00$
Thanks a lot you saved me.. since the syntax was so complicated..
what i did wrong was while trying to change existing username to new one..
I was logged as root since it’s not good to change username while being logged under it.. everything went smooth i even appended the groups to my new user but since i didn’t specify the path to the new home directory after -dm all of the old folder was moved by default to the root folder instead of home since i was logged as root.. so be careful guys to specify path or just log into any other user you have that has folder in home$ or i guess excute the command in the target folder .. here what i used to change username:
usermod -dm -Ga ,sudo -l
to understand this go to the man page..
sorry but trying to add syntax with but gets deleted.
add this to first comment
forgot to mention that combining options letters won’t work which i guess is weird since it;s used in tar -vzf … but i guess some commands don’t agree.. thanks again i’ve just moved my whole folders to the destination.. u r the best not even the man instructions since those are stupid for not giving no examples.. thanks again guys..
Thanks for the article.
When changing the default home dir in /etc/default/useradd, I suggest to change it in /etc/adduser.conf as well (variable DHOME) – otherwise users added by the command ‘adduser’ will have the wrong/old home still.
Regards
on rhel 5 I had to change the command slightly
usermod -d /users/v/vivek -m vivek
this applies to centos 5 as well
it’s working both combination of -m -d options
it’s working both combination of -m -d options
usermod -m -d
I tried too many times but it’s telling me that my user is used by a process 3284
I created a user using adduser :
useradd sacadmin
and added it to a group alcatel.
Now when I do su sacadmin it logs in, but there is no directory /sacadmin in /users.
I need a directory in users for this user and a bin in it like /users/sscadmin/bin
can we Modify Oracle_Base directory to other new directory after installation. Plz help me
change home directory in user1
cmd
#usermod -m -d /backup user1
usermod: user user1 is currently logged in
what is solve
Logout users1. Or kill user1 session:
pkill -KILL -u user1
Источник