Find the answer to your Linux question:
Results 1 to 5 of 5
Hi, I have a bash script that need to be run as sudo because it needs to edit system files. This is fine I execute:- Code: sudo ./script Obviously if ...
  1. #1
    Just Joined!
    Join Date
    Sep 2010
    Posts
    8

    Bash Script run as root but know what user executed script

    Hi,

    I have a bash script that need to be run as sudo because it needs to edit system files. This is fine I execute:-

    Code:
    sudo ./script
    Obviously if the script contained:-

    Code:
    theuser=`id -u`
    echo $theuser
    echo $USER
    It would return:-

    Code:
    0
    root
    But lets say I'm logged in as the user 'admin' with ID '1000' and i run:-

    Code:
    sudo ./script
    How can I get the script to know what the originating user was and somehow assign admin's details to variables in the script to be used later on.

    e.g. I want to edit /etc/ssh/sshd_config and add a line AllowUser with the current logged in user. I want the line to read:-

    Code:
    AllowUser admin
    But the script would have to run as root to be able to edit the file.

    Hope this makes sense.

    Cheers

    Harv

  2. #2
    Linux User
    Join Date
    Jan 2005
    Location
    Saint Paul, MN
    Posts
    262
    Quote Originally Posted by harveyd View Post
    Hi,

    I have a bash script that need to be run as sudo because it needs to edit system files. This is fine I execute:-

    Code:
    sudo ./script
    Obviously if the script contained:-

    Code:
    theuser=`id -u`
    echo $theuser
    echo $USER
    It would return:-

    Code:
    0
    root
    But lets say I'm logged in as the user 'admin' with ID '1000' and i run:-

    Code:
    sudo ./script
    How can I get the script to know what the originating user was and somehow assign admin's details to variables in the script to be used later on.

    e.g. I want to edit /etc/ssh/sshd_config and add a line AllowUser with the current logged in user. I want the line to read:-

    Code:
    AllowUser admin
    But the script would have to run as root to be able to edit the file.

    Hope this makes sense.

    Cheers

    Harv
    Take a look at the command "who am i" (not "whoami").

  3. #3
    Linux Guru
    Join Date
    May 2011
    Posts
    1,842
    I would have said "echo $SUDO_UID" but that 'who am i' is cool!

  4. #4
    Just Joined!
    Join Date
    Sep 2010
    Posts
    8
    They both sound great, I will give them a go, thanks!

  5. #5
    Just Joined!
    Join Date
    Sep 2010
    Posts
    8
    atreyu: yours does closer to what I want it to do.

    Thanks to both!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...