0

What specific changes need to be made in the commands below in order to use a variable username and a variable user_home to create a subdirectory within the current user's home and then to change ownership of the new subdirectory to the current user?

The current commands we are using in a GitHub ubuntu-lastest runner are too brittle because the following commands use the explicit name of the user:

mkdir /home/runner/mysubdirectory/
sudo chown -R runner:runner /home/runner/mysubdirectory/

This OP is asking how to replace /home/runner with a variable declaration of the current user's home, and how to replace runner:runner with variable representations of the current user's name.

2
  • 1
    $USER refers to the current user.
    – annahri
    Commented Nov 19, 2022 at 0:43
  • 1
    And $HOME is used to get the user's home directory Commented Nov 19, 2022 at 0:52

1 Answer 1

0

You could do:

username=runner
sudo -Hu "$username" sh -c 'mkdir ~/mysubdirectory'

Which runs mkdir as the target user (and primary gid of that user) from a shell where $HOME has been set to the home directory of that user with -H and so where ~ will expand to that.

Or you could invoke getent to retrieve the user's information:

IFS=: read -r name x uid gid gecos home shell < <(
  getent -- passwd "$username") &&
  sudo install -o "$uid" -g "$gid" -d "$home/mysubdirectory"
1
  • A more elegant solution is to use the comments from other users to reduce the command to sudo chown -R $USER:$USER $HOME/mysubdirectory/
    – CodeMed
    Commented Nov 22, 2022 at 19:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .