0

I have a shell script that installs several programs with sudo apt-get then opens vncserver, then installs more stuff.

This works:

#!/bin/sh
vncserver

>./my_script.sh

But this does not work:

#!/bin/sh
sudo apt-get update
vncserver

>./my_script.sh 

Nor does this work:

#!/bin/sh
vncserver

>sudo ./my_script.sh

When it doesn't work, it returns the error vncserver: Wrong type or access mode of /home/username/.vnc.

Someone on this question said that this was a known problem. So how can I run vncserver in my_script?

Qwertford
  • 283
  • And if you do sudo <the-script> does it work? – George Udosen Jul 04 '19 at 16:52
  • If it's a sudo session it doesn't work, even if the sudo is called inside the script. sudo would be like in my 3rd example and it gives the error I mentioned. Is there a way to exit out of a sudo session, run vncserver, then go back into sudo, all inside of the shell script? – Qwertford Jul 04 '19 at 16:56
  • What is the > you have there? Is that actually part of your script? >./my_script.sh will just empty the file ./my_script.sh. What is the username in the error message? Is that your username or root's? – terdon Jul 04 '19 at 17:22
  • Sorry, thats my way of writing the final command you write into terminal after writing your shell script. – Qwertford Jul 04 '19 at 17:30
  • it's roots username. It's a cloud instance so i think there's only 1 account. – Qwertford Jul 04 '19 at 17:32

1 Answers1

0

You can use sudo -u to revert to the non-root user for a particular command.

Ex.:

$ cat myscript.sh
#!/bin/sh

whoami

sudo -u $SUDO_USER whoami

then

$ sudo ./myscript.sh
[sudo] password for steeldriver: 
root
steeldriver
steeldriver
  • 136,215
  • 21
  • 243
  • 336