[java] 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.

This question is related to java linux unix grails

The answer is


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)


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


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();
}

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.


Can you parse /etc/passwd?

e.g.:

 cat /etc/passwd | awk -F: '{printf "User %s Home %s\n",  $1, $6}'

Try this on Java:

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

You can use the environment variable $HOME for that.


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.


Try this on Java:

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

You can use the environment variable $HOME for that.


Can you parse /etc/passwd?

e.g.:

 cat /etc/passwd | awk -F: '{printf "User %s Home %s\n",  $1, $6}'

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)


eval echo ~$SUDO_USER

might work.


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.


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.


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.


Can you parse /etc/passwd?

e.g.:

 cat /etc/passwd | awk -F: '{printf "User %s Home %s\n",  $1, $6}'

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.


eval echo ~$SUDO_USER

might work.


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();
}

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.


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


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.


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.


You can use the environment variable $HOME for that.


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


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)


Can you parse /etc/passwd?

e.g.:

 cat /etc/passwd | awk -F: '{printf "User %s Home %s\n",  $1, $6}'

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.


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.


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.


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.


You can use the environment variable $HOME for that.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to unix

Docker CE on RHEL - Requires: container-selinux >= 2.9 What does `set -x` do? How to find files modified in last x minutes (find -mmin does not work as expected) sudo: npm: command not found How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script gpg decryption fails with no secret key error Loop through a comma-separated shell variable Best way to find os name and version in Unix/Linux platform Resource u'tokenizers/punkt/english.pickle' not found

Examples related to grails

Convert base64 string to image How to pass parameters to a modal? Checking if a collection is null or empty in Groovy What in the world are Spring beans? How do I properly set the permgen size? how to parse json using groovy Copy entire directory contents to another directory? Posting a File and Associated Data to a RESTful WebService preferably as JSON Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails Found shared references to a collection org.hibernate.HibernateException