Search code examples
bashsudo

Bash script. Sign in as user, run a command, sign out


Hey guys I am pretty new to bash. I am creating a simple logger all I want to achieve is to log in as super user so (sudo su) run some code (write to a file) and then log out as super user THEN execute the rest of the code

Here is my example:

 read -p "Are you sure you want to log this?" -n 1 -r
if [[ $REPLY =~ ^[Yy] ]]
    then
    sudo su
    if [ "$EUID" -ne 0 ]
    then
        echo $log >> ~/Logs/logs.txt            
    fi
    exit
fi
echo "DONE"

I am really struggling to find a solution there are examples but nothing as simple as this (what I can find that is)

Thank you if you find the time to assist.


Solution

  • You will get an interactive session if you do a sudo su - perhaps you should just execute the command to write the log instead:

    read -p "Are you sure you want to log this?" -n 1 -r
    if [[ $REPLY =~ ^[Yy] ]]
    then
     sudo bash -c "if [ \"$EUID\" -ne 0 ]; then echo $log >> ~/Logs/logs.txt; fi"
    fi
    echo "DONE"