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 i
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.
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 = {"/bin/sh", "-c", "echo ~root"}; //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.
If your are trying to do this for a user name that you cannot hard code, it can be challenging. Sure echo ~rbronosky
would tell you the path to my home dir /home/rbronosky
, but what if rbronosky is in a variable? If you do name=rbronosky; echo ~$name
you get ~rbronosky
Here is a real world case and the solution:
You have a script that the user has to run via sudo. The script has to access the user's home folder. You can't reference ~/.ssh
or else it will expand to /root/.ssh
. Instead you do:
# Up near the top of your script add
export HOME=$(bash <<< "echo ~${SUDO_USER:-}")
# Then you can use $HOME like you would expect
cat rsa_key.pub >> $HOME/.ssh/authorized_keys
The beauty of it is that if the script is not run as sudo then $SUDO_USER is empty, so it's basically the same thing as doing "echo ~". It still works as you' expect.
If you use set -o nounset
, which you should be using, the variable reference ${SUDO_USER:-}
will default to blank, where $SUDO_USER
or ${SUDO_USER}
would give an error (because it is unset) if not run via sudo
.
Try this on Java:
System.out.println("OS: " + System.getProperty("os.name") + ", USER DIRECTORY: " + System.getProperty("user.home"));
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"}
).