Search code examples
linuxbashshellscriptingsuse

how to prompt user to login as root when running a shell script


The problem I am getting is, when I enter the command,

su - root

at the beginning of my shell script file, it prompts the user to enter the password and then does NOT continue with the rest of the shell script. I then have to manually locate and run the shell script via terminal. I want the script to make sure that the user logs in as root and then continue with the rest of the shell script.

In other words, I want to run the script as any user but as soon as the script begins to execute, the user must change to root and then continue on with the rest of the script as root until it is done. Can this be done?


Solution

  • So I wanted to run a script as a normal username. But as soon as the script executed, I needed to become root have have certain privileges that a normal user wouldn't have. So you can see from my question what I tried doing. The solution is the following and it should be added at the beginning of the script to ensure that you are root until the end of file (EOF). Then you become a normal user again.

      #!/bin/sh
      [ "$(whoami)" != "root" ] && exec sudo -- "$0" "$@"
      # rest of the code
      ...
      EOF