Stop being root in the middle of a script that was run with sudo

后端 未结 2 523
逝去的感伤
逝去的感伤 2021-01-20 00:37

There is a list of commands that only succeed when they are prefaced with sudo.
There is another list of commands that only succeed when the user runs them

2条回答
  •  一生所求
    2021-01-20 01:28

    Here is how I would run it in a script.

    #! /bin/bash
    
    if [[ $EUID -ne 0 ]]; then
       echo "This script must be run as root";
       exit 1;
    else
        NON_ROOT_USER=$(who am i | awk '{print $1}');
        echo "root ran this echo.";
        sudo -u $NON_ROOT_USER echo "$NON_ROOT_USER ran this echo.";
    fi
    

    sudo ./script.sh

提交回复
热议问题