tags:

views:

579

answers:

10

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.

A: 

You can use the environment variable $HOME for that.

Torsten Marek
A: 

Would the ~ directory constant help you in any way?

RichieACC
+1  A: 

To find the home directory for user FOO on a UNIX-ish system, use ~FOO. For the current user, use ~.

Yuliy
That's interpreted by the shell only, not the kernel/libraries.
Joachim Sauer
+1  A: 

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.

Alnitak
A: 

Can you parse /etc/passwd?

e.g.:

 cat /etc/passwd | awk -F: '{printf "User %s Home %s\n",  $1, $6}'
Mark
This doesn't work when anything but traditional unix user accounts is used (for example nis or winbindg).
Joachim Sauer
A: 

Find a Java wrapper for getpwuid/getpwnam(3) functions, they ask the system for user information by uid or by login name and you get back all info including the default home directory.

Keltia
A: 

For UNIX-Like systems you might want to execute "echo ~username" using the shell (so use Runtime.exec() to run {"/bin/sh", "-c", "echo ~username"}).

Joachim Sauer
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.
Joachim Sauer
A: 

The userdir prefix (e.g., '/home' or '/export/home') could be a configuration item. Then the app can append the arbitrary user name to that path.

Caveat: This doesn't intelligently interact with the OS, so you'd be out of luck if it were a Windows system with userdirs on different drives, or on Unix with a home dir layout like /home/f/foo, /home/b/bar.

Jeff
+3  A: 

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)

dhiller
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.
A: 

For an arbitrary user, as the webserver:

private String getUserHome(String userName) throws IOException{
    return new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(new String[]{"sh", "-c", "echo ~" + userName}).getInputStream())).readLine();
}
paf0