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

后端 未结 13 567
时光说笑
时光说笑 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:20

    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.

    0 讨论(0)
  • 2020-12-23 20:24

    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)

    0 讨论(0)
  • 2020-12-23 20:26

    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();
    }
    
    0 讨论(0)
  • 2020-12-23 20:26

    Can you parse /etc/passwd?

    e.g.:

     cat /etc/passwd | awk -F: '{printf "User %s Home %s\n",  $1, $6}'
    
    0 讨论(0)
  • 2020-12-23 20:28

    You can use the environment variable $HOME for that.

    0 讨论(0)
  • 2020-12-23 20:28

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

    0 讨论(0)
提交回复
热议问题