Get user home directory linux

How to find a user’s home directory on linux or unix?

How do I find the home directory of an arbitrary user from within Grails? On Linux it’s often /home/user. However, on some OS’s, like OpenSolaris for example, the path is /export/home/user.

Can you be a bit more specific? Do you look for the home directory of the user that runs grails, or for the home directory of an arbitrary user whose name or UID you have?

13 Answers 13

Normally you use the statement

String userHome = System.getProperty( "user.home" ); 

to get the home directory of the user on any platform. See the method documentation for getProperty to see what else you can get.

There may be access problems you might want to avoid by using this workaround (Using a security policy file)

The app server will run as a production user and be located in /opt, for example. This may, or may not work, depending on how the production account is set up. Therefore, asking for the production user’s home directory might not be the answer.

The OP was asking for the home of an arbitrary user. But user.home is the one of the current user. Is this method always working if you would go from the current users home to the parent and then down to the directory with the specified users name?

For UNIX-Like systems you might want to execute » echo ~username » using the shell (so use Runtime.exec() to run ).

Shelling out an doing an ‘echo ~username’ seems like the neatest answer. I see so many people who type ‘cd /home/username’ instead of ‘cd ~username’ . Of course, you should never shell out, if you don’t have to.

But since Java doesn’t provide an API for this, the only alternative I can think of is JNI, which is even worse than calling a shell.

Running echo ~ seems to do the trick if you’re signed in as the user whose home directory you’re looking for.

To be super-precise here — /bin/sh is guaranteed under POSIX to be a Bourne-compliant shell, but tilde expansion ( ~ and ~user ) is not one of the required features of such shell. Linux distributions use BASH as /bin/sh , for which tilde expansion works. If you run echo ~ using /bin/sh under some other UNIX OS, you can get back just the tilde (e.g. «~» ) instead of home directory path.

This does not answer the question. They didn’t ask how to find their own home directory, they asked how to find a user’s home directory.

System.out.println("OS: " + System.getProperty("os.name") + ", USER DIRECTORY: " + System.getProperty("user.home")); 

For an arbitrary user, as the webserver:

private String getUserHome(String userName) throws IOException< return new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(new String[]).getInputStream())).readLine(); > 

You can use the environment variable $HOME for that.

Читайте также:  Linux astra root права пользователю

$HOME changes depending on which user is logged in. I don’t see how it can be used to find the home of an arbitrary user.

If you want to find a specific user’s home directory, I don’t believe you can do it directly.

When I’ve needed to do this before from Java I had to write some JNI native code that wrapped the UNIX getpwXXX() family of calls.

I assume you want to find the home directory of a DIFFERENT user. Obviously getting the «user.home» property would be the easiest way to get the current user home directory.

To get an arbitrary user home directory, it takes a bit of finesse with the command line:

String[] command = ; //substitute desired username Process outsideProcess = rt.exec(command); outsideProcess.waitFor(); String tempResult; StringBuilder sb = new StringBuilder(); while((tempResult = br.readLine()) != null) sb.append(tempResult); br.close(); return sb.toString().trim(); 

Now technically, we should have a thread waiting on the stdout and stderr so the buffers don’t fill up and lock up the process, but I’d sure hope the buffer could at least hold a single username. Also, you might want to check the result to see if it starts with ~root (or whatever username you used) just to make sure the user does exist and it evaluated correctly.

Hope that helps. Vote for this answer if it does as I’m new to contributing to SO and could use the points.

Источник

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?

6 Answers 6

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:

[jenny@sameen ~]$ getent passwd jenny jenny:*:1001:1001:Jenny Dybedahl:/home/jenny:/usr/local/bin/bash 

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

[jenny@sameen ~]$ getent passwd jenny | cut -d: -f6 /home/jenny 

getent is the better answer, specially with remote user. in simpler systems ~user should be enough. Modded you up.

@muru — that’s true — and is spec’d behavior. the ~ 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.

Читайте также:  Kali linux repository gpg

Note that this only gets you the initial value of $HOME; the user’s login scripts are perfectly entitled to change it to something else. This is an unusual thing to do, but I can think of situations where it would be sensible, e.g. choosing between a local and an NFS-mounted homedir.

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 .

Interesting, thanks, however this only gets the directory of the current user, not of other users. I think LDAP users are not handled, though I can be wrong.

@RuiFRibeiro It will work fine with LDAP, just use whatever variable contains your LDAP user’s username instead of USER .

Don’t use this without verifying that $USER expands to just a single string of alphabetic characters.

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:

awk -v FS=':' -v user="$USER" '($1==user) ' "/etc/passwd" 

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

getent passwd "$USER" | cut -d : -f 6 

Will provide equivalent information (if available).

Источник

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?

Current home directory of user (not named) is ~ is it not? As in cd ~ , mv some_file ~/some_file etc.

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

From a programmers point of view, Linux is Unix. It follows the same standards. It just hasn’t been certified by The Open Group. From a users point of view, there is no more difference between Linux and «real» Unix systems, than there is among certified systems.

The HOME environment variable isn’t reliable because it could be changed. R Samuel Klatchko’s answer is more precise. However, you should consider the likelihood that if the user has redefined HOME, maybe they had a reason to do so, and your program would better serve the user’s needs by using that variable.

Читайте также:  Coding python on linux

4 Answers 4

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:

#include #include #include struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; 

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

Note though that the getpwuid() man page has this caveat: An application that wants to determine its user’s home directory should inspect the value of HOME (rather than the value getpwuid(getuid())->pw_dir ) since this allows the user to modify their notion of «the home directory» during a login session.

This isn’t a good answer to the original question. This is the shell starting directory set up in /etc/passwd , which may or may not be the user’s (active) home directory. This is useful information, but getenv is the right answer.

Most programs should prefer geteuid() over getuid(). Otherwise, if you run a command through sudo, for example, then it will examine your real user login rather than whichever login to which you sudo’ed.

While considering using seteuid() instead of setuid(), also notice that environment variable will NOT change by sudo. That means if you favor $HOME variable than getpwuid(), you will always get the original user home directory, not the effective user home directoy.

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

#include #include #include const char *homedir; if ((homedir = getenv("HOME")) == NULL) < homedir = getpwuid(getuid())->pw_dir; > 

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):

struct passwd pwd; struct passwd *result; char *buf; size_t bufsize; int s; bufsize = sysconf(_SC_GETPW_R_SIZE_MAX); if (bufsize == -1) bufsize = 0x4000; // = all zeroes with the 14th bit set (1 s = getpwuid_r(getuid(), &pwd, buf, bufsize, &result); if (result == NULL) < if (s == 0) printf("Not found\n"); else < errno = s; perror("getpwnam_r"); >exit(EXIT_FAILURE); > char *homedir = result.pw_dir; 

Источник

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