Linux изменить домашнюю директорию пользователя

Command to change the default home directory of a user [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

I would like to know whether there is any simple shell command to change the user home directory in Linux/Unix (one similar to chsh which changes the default login shell of an existing valid user) without touching the /etc/passwd file. Thanks

stackoverflow.com/questions/20071714/…, says that usermod -d /home/userxx /home/useryy to change linux default login directory to /home/useryy

Why do you ask about the default home directory? Do you want to change the home directory of one particular existing user, or of all users added in the future? Notice that chsh don’t change the default login shell, but just the login shell of a given user. To change the HOME of a particular user, just edit /etc/passwd

I’m voting to close this question because it has nothing to do with programming and would have been best suited for Unix & Linux or Super User.

7 Answers 7

Ibrahim’s comment on the other answer is the correct way to alter an existing user’s home directory.

Change the user’s home directory:

usermod -d /newhome/username username 

usermod is the command to edit an existing user.
-d (abbreviation for —home ) will change the user’s home directory.

Change the user’s home directory + Move the contents of the user’s current directory:

usermod -m -d /newhome/username username 

-m (abbreviation for —move-home ) will move the content from the user’s current directory to the new directory.

Not only move the content, I see it more like move whole folder = original folder ( /home/username typically) is removed.

@STW Is this a reversible task? Meaning if I just run it once and then flip the parameters, will my home directory be exactly the way it was before?

Читайте также:  Linux user etc passwd

The order of options for the second command is wrong. usermod -m -d /newhome/username username works.

@KolonUK because that’s the only correct way really. When you are logged in as the user, you have applications opened which rely on that home directory. You shouldn’t be changing the location while everything is running. So yeah, creating a new user account and deleting is not that bad at all. Or you could set a password for root and login as root in a new TTY.

Simply open this file using a text editor, type:

The default home directory defined by HOME variable, find line that read as follows:

Save and close the file. Now you can add user using regular useradd command:

# useradd vivek # passwd vivek 

usermod -m -d /path/to/new/login/home/dir user changes existing user home directory to a new login directory which is created if it does not already exist, option -m moves the contents of the current home directory to the new home dir

The accepted answer is faulty, since the contents from the initial user folder are not moved using it. I am going to add another answer to correct it:

sudo usermod -d /newhome/username -m username 

You don’t need to create the folder with username and this will also move your files from the initial user folder to /newhome/username folder.

In case other readers look for information on the adduser command.

Edit the user home directory and then move the required files and directories to it:

cp/mv -r /home/$user/.bash* /home/newdir .bash_profile .ssh/ 

Set the correct permission

chmod -R $user:$user /home/newdir/.bash* 

Found out that this breaks some applications, the better way to do it is

In addition to symlink, on more recent distros and filesystems, as root you can also use bind-mount:

mkdir /home/username mount --bind --verbose /extra-home/username /home/username 

This is useful for allowing access «through» the /home directory to subdirs via daemons that are otherwise configured to avoid pathing through symlinks (apache, ftpd, etc.).

You have to remember (or init script) to bind upon restarts, of course.

Читайте также:  Orange pi pc linux mint

An example init script in /etc/fstab is

/extra-home/username /home/username none defaults,bind 0 0 

Источник

Как поменять домашнюю директорию для пользователя linux командой usermod

У каждого пользователя в Unix есть своя домашняя папка, предназначенная для хранения данных пользователя в месте, доступном только для него. О том, как узнать домашнюю директорию любого пользователя можно прочитать по → этой ссылке. О том, где и как создаются записи о домашнем каталоге пользователя написано в → этой статье. О том, как поменять домашнюю папку пользователя по умолчанию в Linux → по этой ссылке. Все перечисленные сведения полезны и могут помочь ручками поправить путь до домашнего каталога пользователя, однако для его смены есть удобная команда linux — usermod . То, как с её помощью быстро поменять домашнюю директорию для пользователя и рассмотрим ниже.

Помощь по команде usermod в linux

Зная название команды, лично я лезу в подсказки операционной системе по ней. Чего и всем советую. =) Данный случай не является исключением. Сперва посмотрим на те опции, которые описаны в хэлпе:

[email protected]:~# usermod -h Usage: usermod [options] LOGIN Options: -c, --comment COMMENT new value of the GECOS field -d, --home HOME_DIR new home directory for the user account -e, --expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE -f, --inactive INACTIVE set password inactive after expiration to INACTIVE -g, --gid GROUP force use GROUP as new primary group -G, --groups GROUPS new list of supplementary GROUPS -a, --append append the user to the supplemental GROUPS mentioned by the -G option without removing him/her from other groups -h, --help display this help message and exit -l, --login NEW_LOGIN new value of the login name -L, --lock lock the user account -m, --move-home move contents of the home directory to the new location (use only with -d) -o, --non-unique allow using duplicate (non-unique) UID -p, --password PASSWORD use encrypted password for the new password -R, --root CHROOT_DIR directory to chroot into -s, --shell SHELL new login shell for the user account -u, --uid UID new UID for the user account -U, --unlock unlock the user account -v, --add-subuids FIRST-LAST add range of subordinate uids -V, --del-subuids FIRST-LAST remove range of subordinate uids -w, --add-subgids FIRST-LAST add range of subordinate gids -W, --del-subgids FIRST-LAST remove range of subordinate gids -Z, --selinux-user SEUSER new SELinux user mapping for the user account

Как видно, опций у команды usermod более, чем достаточно, но для текущей цели (смены домашнего каталога пользователя) понадобится опция -d . Её и рассмотрим более подробно.

Читайте также:  Openjdk linux что это

Как с помощью опции -d команды usermod в линукс поменять домашнюю директорию пользователя

Рассмотрим на живом примере. Создадим нового пользователя (как это сделать → подробно тут):

Посмотрим на запись об этом пользователе в файле /etc/passwd . Она имеет следующий вид:

[email protected]:~# cat /etc/passwd . newuser:x:1000:1000. /var/www/newuser:/bin/bash . 

Посмотрим содержимое этой домашней папки (она пустая):

[email protected]:~# ls -l /var/www/newuser total 0 [email protected]:~# tree /var/www/newuser /var/www/newuser 0 directories, 0 files

И теперь сменим домашнюю папку этому пользователю:

[email protected]:~# usermod -d /var/www/newuser2 newuser [email protected]:~# ls -l /var/www/newuser2 ls: cannot access '/var/www/newuser2': No such file or directory [email protected]:~# cat /etc/passwd . newuser:x:1000:1000. /var/www/newuser2:/bin/bash . 
  1. Командой usermod -d /var/www/newuser2 newuser прописали папку /var/www/newuser2 в качестве домашней для пользователя newuser
  2. Но директория при этом не была создана. Это видно при попытке её прочитать: ls -l /var/www/newuser2
  3. Однако, запись в файле /etc/passwd была изменена.

Можно конечно создать эту папку вручную командой mkdir (читать тут), а потом прописать ей владельца и группу командой chown (читать тут), но проще и безболезненнее воспользоваться дополнительной опцией -m команды usermod . Важно, чтобы папка пользователя содержала хоть что-нибудь в себе. Даже просто пустой файл. Тогда и только тогда, новая папка будет создана и в неё будет перенесено содержимое старой папки.

Поэтому для того, чтобы поменять домашнюю директорию для пользователя linux, нужно воспользоваться командой usermod с опцией -md. При этом в папке пользователя должны храниться какие-нибудь данные.

usermod -md /путь_до_новой_домашней_папки username

Заберите ссылку на статью к себе, чтобы потом легко её найти!
Раз уж досюда дочитали, то может может есть желание рассказать об этом месте своим друзьям, знакомым и просто мимо проходящим?
Не надо себя сдерживать! 😉

Источник

Оцените статью
Adblock
detector