Changing to root user inside shell script

后端 未结 5 1372
不思量自难忘°
不思量自难忘° 2021-01-03 21:13

I have a shell script which needs non-root user account to run certain commands and then change the user to root to run the rest of the script. I am using SUSE11. I have use

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 21:49

    There is an easy way to do it without a second script. Just put this at the start of your file:

    if [ "$(whoami)" != "root" ]
    then
        sudo su -s "$0"
        exit
    fi
    

    Then it will automatically run itself as root. Of course, this assumes that you can sudo su without having to provide a password - but that's out of scope of this answer; see one of the other questions about using sudo in shell scripts for how to do that.

提交回复
热议问题