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

后端 未结 13 661
时光说笑
时光说笑 2020-12-23 19:57

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

13条回答
  •  旧巷少年郎
    2020-12-23 20:14

    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.

提交回复
热议问题