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.
To find the home directory for user FOO on a UNIX-ish system, use ~FOO
. For the current user, use ~
.
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.
Can you parse /etc/passwd?
e.g.:
cat /etc/passwd | awk -F: '{printf "User %s Home %s\n", $1, $6}'
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.
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"}
).
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.
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)
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();
}