Executing bash file with sudo for the second time, leads to permission denied, for some commands

I have a script that checks if the script has been ran with sudo.
If the script is not ran as sudo , the current script is being executed with exec sudo bash .
You are asked for a password, you type in the password, success. Everything is perfect - the commands inside the script are ran as sudo .
However, the second time you run the script, you are getting cat: /etc/sudoers: Permission denied

What is this happening and how can this be fixed?

Output of the Script:

vaidas@vaidas-SATELLITE-L855:~$ cd Desktop
vaidas@vaidas-SATELLITE-L855:~/Desktop$ bash shellscript.sh 
sudo: a password is required
[sudo] password for vaidas: 
----------YAS HAVE SUDO----------
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults    env_reset
Defaults    mail_badpass
vaidas@vaidas-SATELLITE-L855:~/Desktop$ bash shellscript.sh 
----------YAS HAVE SUDO----------
head: cannot open '/etc/sudoers' for reading: Permission denied
vaidas@vaidas-SATELLITE-L855:~/Desktop$ 

The Script:

#!/bin/bash

if sudo -n true;
then
  echo "----------YAS HAVE SUDO----------";
  head /etc/sudoers;
  
else
  exec sudo bash "$0" "$@";
fi

That you can run sudo -n true doesn't always mean you're root. Sometimes it just means you ran sudo recently enough it isn't asking for your password again. Check if UID is 0 too.

1 Like