Linux home directory path

👥 Как создать домашний каталог для существующего пользователя Linux

По умолчанию, когда вы создаете пользователя в Linux, домашний каталог создается в каталоге /home.

Возможно вы заметили, что в производных дистрибутивах Ubuntu и Debian команда useradd по умолчанию не будет создавать домашний каталог.

Давайте представим ситуацию, что вы уже создали пользователя, но домашний каталог отсутствует.

В этом руководстве я покажу вам, как создать домашний каталог по умолчанию для существующего пользователя в системах Linux.

Создание домашнего каталога по умолчанию для существующего пользователя

В примере я использую Ubuntu 20.04 и собираюсь создать пользователя с именем ‘bob’ с помощью команды useradd:

Если я попытаюсь войти в систему от этого пользователя, используя su -, система показывает logging in with Home=/

Это означает, что домашний каталог пользователя не создан.

В Linux домашним каталогом пользователя по умолчанию является /home.

Чтобы создать домашний каталог по умолчанию, используйте команду mkhomedir_helper.

Обязательно запустите команду mkhomedir_helper от имени пользователя root или пользователя с доступом sudo.

В графической среде (например, GNOME или XFCE), если вам не хватает подкаталогов в домашнем каталоге, пользователь должен выйти из системы и войти обратно.

При первом входе пользователя в систему все подкаталоги, такие как папки Pictures, Documents, Videos, и Downloads , могут быть созданы в домашнем каталоге.

Другой метод – удалить пользователя и создать нового пользователя с помощью параметра -m или –create-home.

Следующая команда создает домашнюю папку (-m) и задаст указанный домашний каталог (-d) в качестве значения для входа нового пользователя:

Заключение

В заключение, если вы являетесь поклонником Ubuntu, вы должны теперь использовать команду adduser.

Если у вас уже есть пользователь, теперь вы сможете добавить каталог по умолчанию.

Источник

Get home directory in Linux

I need a way to get user home directory in C++ program running on Linux. If the same code works on Unix, it would be nice. I don’t want to use HOME environment value.

AFAIK, root home directory is /root. Is it OK to create some files/folders in this directory, in the case my program is running by root user?

is it not? As in cd

is implemented by the shell, not the kernel or libc. When programming in C++, you need to implement that yourself.

3 Answers 3

You need getuid to get the user id of the current user and then getpwuid to get the password entry (which includes the home directory) of that user:

Note: if you need this in a threaded application, you’ll want to use getpwuid_r instead.

Читайте также:  Mac os big sur games

You should first check the $HOME environment variable, and if that does not exist, use getpwuid.

Also note, that if you want the home directory to store configuration or cache data as part of a program you write and want to distribute to users, you should consider following the XDG Base Directory Specification. For example if you want to create a configuration directory for your application, you should first check $XDG_CONFIG_HOME using getenv as shown above and only fall back to the code above if the variable is not set.

If you require multi-thread safety, you should use getpwuid_r instead of getpwuid like this (from the getpwnam(3) man page):

Источник

How to get HOME, given USER?

I have an USER variable in my script, and I want to see his HOME path based on the USER variable. How can I do that?

5 Answers 5

There is a utility which will lookup user information regardless of whether that information is stored in local files such as /etc/passwd or in LDAP or some other method. It’s called getent .

In order to get user information out of it, you run getent passwd $USER . You’ll get a line back that looks like:

Now you can simply cut out the home dir from it, e.g. by using cut, like so:

user should be enough. Modded you up.

foo with variables in bash . Not directly, anyway.

does seem to tab-expand, though, and another spec’d behavior of the tilde-prefix shall be replaced by a pathname of the initial working directory associated with the login name obtained using the getpwnam() function and so probably that lookup is pretty good. i dont like tab-expansions, though — i like to type tabs.

You can use eval to get someone’s home directory.

At least for local users this works for sure. I don’t know if remote users like LDAP are handled with eval .

foo after variable expansion.

The usual place is /home/$USER , but that does not have to be universal. The definitive place to search for such information is inside the file /etc/passwd .

That file is world readable (anyone could read it), so any user has access to its contents.
If the $USER exists in the file, the entry previous to last is the user HOME directory.

This will select the entry and print the HOME directory:

For more complex (remote) systems, getent is the usual command to get users information from the NSS (Name Service Switch libraries) system.

Will provide equivalent information (if available).

Источник

Get home directory by username

I want to obtain home dir of any user with echo

But I cant use variable

7 Answers 7

You can use eval :

But see Andrew’s comment and glenn’s reply below.

$username it’s okay, but in sh eval is needed if is a variable

This might work for you:

This will also work on users that are not you. For instance,

Читайте также:  Значок меню для linux

It seems you are that user — why not

There is a safe way to do this!

on Linux/BSD/macOS/OSX without sudo or root

NOTE: The reason this is safe is because bash (even versions prior to 4.4) has its own printf function that includes:

%q quote the argument in a way that can be reused as shell input

See: help printf

Compare to how other answers respond to code injection

on Linux/BSD/macOS/OSX as root

If you are doing this because you are running something as root then you can use the power of sudo:

on Linux/BSD (but not modern macOS/OSX) without sudo or root

If not, the you can get it from /etc/passwd . There are already lots of examples of using eval and getent , so I’ll give another option:

I would really only use that one if I had a bash script with lots of other awk oneliners and no uses of cut . While many people like to «code golf» to use the fewest characters to accomplish a task, I favor «tool golf» because using fewer tools gives your script a smaller «compatibility footprint». Also, it’s less man pages for your coworker or future-self to have to read to make sense of it.

Источник

What is the home directory on Windows Subsystem for Linux?

When I start bash on Windows Subsystem for Linux, it drops me in the directory

When I ls this directory, I see the directories Desktop , Documents , etc. that I can see are in C:\Users\ using the Windows File Explorer. Since this is where the bash program started, I expected this is my home directory, but when I type either cd or cd

I am brought to

which contains my .bashrc , .profile etc. file which I would expect to find in my home directory in a Linux box. Moreover, entering cd ../.. from here I can see the directories bin , etc and so on, again as expected on a Linux box.

I have two questions regarding all this:

  1. What exactly is /mnt/c/Users/ compared with C:\Users\ ? It seems they are one in the same—so what is /mnt/c/ ?
  2. How can I view the files in /home/ using the Windows File Explorer? Not that I’d really ever want to—I’m just trying to get a feel for how Windows is organizing this Subsystem for Linux thing.

11 Answers 11

In the latest versions [2020], the file system is accessed from:

Previously, as of 2018, The current path is related to which distribution you have installed from the Microsoft Store rather than one global path; for Ubuntu, it was located at:

Other distributions should be (to be confirmed) in a similar location under their respective folders within:

In Bash, to view the current directory in Windows File Explorer just enter:

Don’t leave out the «.».

This will open windows explorer at the current folder and you can see where everything is in relation to the rest of your Windows system.

  1. /mnt/c is the exact same as C:\ . It’s just the syntax for getting to it from WSL.
  2. Look in C:\Users\ \AppData\Local\Lxss\rootfs .
Читайте также:  Use windows application on mac

About the filesystem mounted on /mnt/c

  1. What exactly is /mnt/c/Users/ compared with C:\Users ? It seems they are one in the same—so what is /mnt/c/?

In contrast to Windows, Linux (and the other systems based on Unix) use a single folder structure independent of the number of disks you have. If you have multiple disks, all these disks must me mounted into the folder structure at some point.

  • Typically, all the disks (different than the used to boot the system) are mounted in a folder named /mnt or /media

WSL has an special type of filesystem named DrvFS that gives you access to the disks used in windows. You can use DrvFS to mount, not only your windows filesystem, but also network disks and other media types.

  • In WSL, by default, the C: disk in windows is mounted under /mnt/c
  • If you have another disk, for instance a D: disk in windows, it will be mounted under /mnt/d

The files you can see in /mnt/c are the same you have in C: . If you modify some file, you will get the changes in the windows too.

About the location of /home/

  1. How can I view the files in /home/ using the Windows File Explorer? Not that I’d really ever want to—I’m just trying to get a feel for how Windows is organizing this Subsystem for Linux thing.

In WSL, all the linux filesystem is located under a Windows folder. The location of the folder depends on the version of Windows and of the WSL distribution you are using.

  • Initial versions of WSL store the linux filesystem in %LOCALAPPDATA%\Lxss\rootfs
  • WSL distributions installed from the Windows Store, starting in Windows Build 16215 (mid of 2017), use a folder like %LOCALAPPDATA%\Packages\\LocalState\rootfs . The name of the package varies depending on the distribution (e.g. it is different for Ubuntu than for Debian). For Ubuntu on Windows it is CanonicalGroupLimited.UbuntuonWindows_ , for example.
  • Linux distributions installed using other tools, such as lxRunOffline or WSL-DistroLauncher may store the linux filesystem into any location.

You may check many options to know the location of the WSL folder. For instance, I think the easiest option is to use lxRunOffline to know the installation folder.

Once you know the location of the installation folder, the /home/ is under \rootfs\home\username .

  • For instance, if your installation folder is c:\wsl\ubuntu
  • the /home/ is in c:\wsl\ubuntu\rootfs\home\username

NOTE: Both Linux and Windows stores file permissions in different ways. Nowadays, the WSL DrvFS stores the Linux permissions as Streams (metadata) attached to the files you can see in Windows. Microsoft does not recommend to modify linux files using Windows programs. It is possible that some Windows applcations damage the linux permissions without notice it.

Источник

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