Linux current user directory

How to get $HOME directory when switching to a different user in bash?

I need to execute part of a bash script as a different user, and inside that user’s $HOME directory. However, I’m not sure how to determine this variable. Switching to that user and calling $HOME does not provide the correct location:

# running script as root, but switching to a different user. su - $different_user echo $HOME # returns /root/ but should be /home/myuser 

Update:

$different_user=deploy # create user useradd -m -s /bin/bash $different_user echo "Current user: `whoami`" # Current user: root echo "Switching user to $different_user" # Switching user to deploy su - $different_user echo "Current user: `whoami`" # Current user: root echo "Current user: `id`" # Current user: uid=0(root) gid=0(root) groups=0(root) sudo su $different_user # Current user: root # Current user: uid=0(root) gid=0(root) groups=0(root) 

su — $different_user should have been enough. Are you sure you’re even logged in as myuser . Try running id command to verify. Some login shell is set to nologin and it exits as soon you login as myuser .

@anubhava I updated my question to include how I created the user. Essentially: useradd -m -s /bin/bash $different_user .

Please take another look at my answer. I substantially changed it to match exactly what you have attempted to do.

Please do not use eval or bash -c with a variable. I added an answer that works safely for an Linux/Unix/macOS system with bash (even if you are not using bash as your shell, it likely has bash available because bashisms are everywhere). stackoverflow.com/a/53219743/117471 It also explains the danger of other answers.

13 Answers 13

Update: Based on this question’s title, people seem to come here just looking for a way to find a different user’s home directory, without the need to impersonate that user.

In that case, the simplest solution is to use tilde expansion with the username of interest, combined with eval (which is needed, because the username must be given as an unquoted literal in order for tilde expansion to work):

eval echo "~$different_user" # prints $different_user's home dir. 

Note: The usual caveats regarding the use of eval apply; in this case, the assumption is that you control the value of $different_user and know it to be a mere username.

By contrast, the remainder of this answer deals with impersonating a user and performing operations in that user’s home directory.

  • Administrators by default and other users if authorized via the sudoers file can impersonate other users via sudo .
  • The following is based on the default configuration of sudo — changing its configuration can make it behave differently — see man sudoers .

The basic form of executing a command as another user is:

sudo -H -u someUser someExe [arg1 . ] # Example: sudo -H -u root env # print the root user's environment 
  • If you neglect to specify -H , the impersonating process (the process invoked in the context of the specified user) will report the original user’s home directory in $HOME .
  • The impersonating process will have the same working directory as the invoking process.
  • The impersonating process performs no shell expansions on string literals passed as arguments, since no shell is involved in the impersonating process (unless someExe happens to be a shell) — expansions by the invoking shell — prior to passing to the impersonating process — can obviously still occur.
Читайте также:  Создание копии файла линукс

Optionally, you can have an impersonating process run as or via a(n impersonating) shell, by prefixing someExe either with -i or -s — not specifying someExe . creates an interactive shell:

  • -i creates a login shell for someUser , which implies the following:
    • someUser ‘s user-specific shell profile, if defined, is loaded.
    • $HOME points to someUser ‘s home directory, so there’s no need for -H (though you may still specify it)
    • The working directory for the impersonating shell is the someUser ‘s home directory.
    • no shell profile is loaded (though initialization files for interactive nonlogin shells are; e.g., ~/.bashrc )
    • Unless you also specify -H , the impersonating process will report the original user’s home directory in $HOME .
    • The impersonating shell will have the same working directory as the invoking process.

    Using a shell means that string arguments passed on the command line MAY be subject to shell expansionssee platform-specific differences below — by the impersonating shell (possibly after initial expansion by the invoking shell); compare the following two commands (which use single quotes to prevent premature expansion by the invoking shell):

     # Run root's shell profile, change to root's home dir. sudo -u root -i eval 'echo $SHELL - $USER - $HOME - $PWD' # Don't run root's shell profile, use current working dir. # Note the required -H to define $HOME as root`s home dir. sudo -u root -H -s eval 'echo $SHELL - $USER - $HOME - $PWD' 

    What shell is invoked is determined by «the SHELL environment variable if it is set or the shell as specified in passwd(5)» (according to man sudo ). Note that with -s it is the invoking user’s environment that matters, whereas with -i it is the impersonated user’s.

    Note that there are platform differences regarding shell-related behavior (with -i or -s ):

    • sudo on Linux apparently only accepts an executable or builtin name as the first argument following -s / -i , whereas OSX allows passing an entire shell command line; e.g., OSX accepts sudo -u root -s ‘echo $SHELL — $USER — $HOME — $PWD’ directly (no need for eval ), whereas Linux doesn’t (as of sudo 1.8.95p ).
    • Older versions of sudo on Linux do NOT apply shell expansions to arguments passed to a shell; for instance, with sudo 1.8.3p1 (e.g., Ubuntu 12.04), sudo -u root -H -s echo ‘$HOME’ simply echoes the string literal «$HOME» instead of expanding the variable reference in the context of the root user. As of at least sudo 1.8.9p5 (e.g., Ubuntu 14.04) this has been fixed. Therefore, to ensure expansion on Linux even with older sudo versions, pass the the entire command as a single argument to eval ; e.g.: sudo -u root -H -s eval ‘echo $HOME’ . (Although not necessary on OSX, this will work there, too.)
    • The root user’s $SHELL variable contains /bin/sh on OSX 10.9, whereas it is /bin/bash on Ubuntu 12.04.

    Whether the impersonating process involves a shell or not, its environment will have the following variables set, reflecting the invoking user and command: SUDO_COMMAND , SUDO_USER , SUDO_UID= , SUDO_GID .

    See man sudo and man sudoers for many more subtleties.

    Tip of the hat to @DavidW and @Andrew for inspiration.

    Источник

    How to Find User’s Home Directory in Linux or Unix

    Under a Linux operating system distribution environment, a created/existing system user is associated with a Home directory. The configuration of the Home directory ensures that the files belonging to the currently active Linux user are only accessible to that user unless this user switches to another user account where they will access the Home directory of that switched user.

    The files under a Linux Home user directory are specific to the currently active users. The base directory of the Linux operating system is the root (/) directory.

    It is from the root (/) directory that we should be able to access the Home (/home) directory.

    If you only have a single active user on your Linux operating system environment, dealing with the Home directory is straightforward. The latter statement implies that every created/existing Linux user will have their system username as a directory name under this Linux Home directory.

    For instance, listing the directories in the above Home directory lists three other directories to imply that the Linux operating system in question hosts 3 three users.

    View Linux Home Directory

    If we decide to navigate into either of the above Linux user folders, we should first be able to meet the following prerequisite.

    It is only by being a sudoer/root user that we can be able to navigate into other Linux users’ Home directories without bumping into permission/access barriers.

    View User Home Directory

    From the above display, we have managed to navigate to the Home directory and list the files, folders, and directories associated with user dnyce whose user directory exists within the Home (/home) directory.

    The above screen capture also reveals to us the different file permissions associated with the listed files, folders, and directories. The file permissions starting with – e.g – rw-rw-r— , imply that we are dealing with a file and the file permissions starting with d e.g drwxr-xr-x , imply that we are dealing with a folder or directory.

    Ways to Find User’s Home Directory in Linux

    Before we look at some viable approaches to finding a user’s home directory in Linux, it is important to understand why the Home directory exists. This directory helps differentiate system-wide data from user data such that we do not have to deal with redundancy. Also, important file backup operation becomes flawless.

    You first need to be sure that the Linux user exists. This approach is a summary of the above-discussed content.

    The tilde (~) symbol indicates that we are at the home directory of the currently active user.

    Find User Home Directory

    The Linux user’s home directory contains directories like Documents, Downloads, Music, Pictures, and Public.

    Find User’s Home Directory Using Cd Command

    Executing the cd (change directory) command alone should take you to the home directory of the current Linux user.

    Find User Home Directory

    Another approach is to use cd + tilde (~) should navigate us to the Home directory of the currently logged-in user.

    Switch to User Home Directory

    You can also use $HOME command, which takes you to the Home directory as a variable.

    Not only do we understand the concept of the Linux user’s home directory, but we can navigate to it from any directory path.

    Источник

    How to get HOME, given USER?

    I have an USER variable in my script, and I want to see his HOME path based on the USER variable. How can I do that?

    6 Answers 6

    There is a utility which will lookup user information regardless of whether that information is stored in local files such as /etc/passwd or in LDAP or some other method. It’s called getent .

    In order to get user information out of it, you run getent passwd $USER . You’ll get a line back that looks like:

    [jenny@sameen ~]$ getent passwd jenny jenny:*:1001:1001:Jenny Dybedahl:/home/jenny:/usr/local/bin/bash 

    Now you can simply cut out the home dir from it, e.g. by using cut, like so:

    [jenny@sameen ~]$ getent passwd jenny | cut -d: -f6 /home/jenny 

    getent is the better answer, specially with remote user. in simpler systems ~user should be enough. Modded you up.

    @muru — that’s true — and is spec’d behavior. the ~ does seem to tab-expand, though, and another spec’d behavior of the tilde-prefix shall be replaced by a pathname of the initial working directory associated with the login name obtained using the getpwnam() function and so probably that lookup is pretty good. i dont like tab-expansions, though — i like to type tabs.

    Note that this only gets you the initial value of $HOME; the user’s login scripts are perfectly entitled to change it to something else. This is an unusual thing to do, but I can think of situations where it would be sensible, e.g. choosing between a local and an NFS-mounted homedir.

    You can use eval to get someone’s home directory.

    At least for local users this works for sure. I don’t know if remote users like LDAP are handled with eval .

    Interesting, thanks, however this only gets the directory of the current user, not of other users. I think LDAP users are not handled, though I can be wrong.

    @RuiFRibeiro It will work fine with LDAP, just use whatever variable contains your LDAP user’s username instead of USER .

    Don’t use this without verifying that $USER expands to just a single string of alphabetic characters.

    The usual place is /home/$USER , but that does not have to be universal. The definitive place to search for such information is inside the file /etc/passwd .

    That file is world readable (anyone could read it), so any user has access to its contents.
    If the $USER exists in the file, the entry previous to last is the user HOME directory.

    This will select the entry and print the HOME directory:

    awk -v FS=':' -v user="$USER" '($1==user) ' "/etc/passwd" 

    For more complex (remote) systems, getent is the usual command to get users information from the NSS (Name Service Switch libraries) system.

    getent passwd "$USER" | cut -d : -f 6 

    Will provide equivalent information (if available).

    Источник

Оцените статью
Adblock
detector