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

前端 未结 6 656
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:34

    sudo su will attempt to start a new shell as root. Once that new shell is opened, the original script will not continue until the new shell is closed.

    For a fix try:

    In the shell script try:

    su  -c "my command"
    

    So if the user was "userA":

    su userA -c "mkdir /opt/D3GO/"
    

    However, if you are userA for example and you want to run the part of script as root, you will be prompted for a pass.

    su root -c "mkdir /opt/D3GO/"
    

    You can also get around that by just running the script with sudo in the first place

    sudo ./myScript.sh
    

    That way the script retains the original user inside the script which you can access using the standard variables like ${USERNAME}, ${UID} etc

    Depends on what works better for you.

提交回复
热议问题