Why can't I use 'sudo su' within a shell script? How to make a shell script run with sudo automatically

前端 未结 6 609
Happy的楠姐
Happy的楠姐 2020-12-29 09:22

I cannot figure out what\'s wrong with this. When I run it in terminal and enter password, nothing happens, but if I run every command separately in terminal, it works. Than

6条回答
  •  伪装坚强ぢ
    2020-12-29 09:50

    Command sudo su starts an interactive root shell, but it will not convert the current shell into a root one.

    The idiom to do what you want is something along the lines of this (thanks to @CharlesDuffy for the extra carefulness):

    #check for root
    UID=$(id -u)
    if [ x$UID != x0 ] 
    then
        #Beware of how you compose the command
        printf -v cmd_str '%q ' "$0" "$@"
        exec sudo su -c "$cmd_str"
    fi
    
    #I am root
    mkdir /opt/D3GO/
    #and the rest of your commands
    

    The idea is to check whether the current user is root, and if not, re-run the same command with su

提交回复
热议问题