Detener/eliminar el script en ejecución si $USER!= "root"

Detener/eliminar el script en ejecución si $USER!= "root"

Estoy trabajando en scripts que deben ejecutarse como root; de lo contrario, debería detener todo.

#!/bin/bash
validationRoot() {
    if [ $USER != 'root' ]
        then
            echo "You're not root! You can't use this script."

    fi
}
validationRoot;
echo "You're root!"

No sé qué agregar después echo "You're not root! You can't use this script."para detener la ejecución.

Respuesta1

Yo hubiera hecho esto así:

#!/bin/bash
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

Tenga en cuenta que id=0 es lo que se utiliza dentro del kernel para identificar al superusuario (o root).


editar: será aún mejor redirigir a STDERR.


Aquí hay una sola línea :)

(( EUID )) && echo ‘You need to be root.’ && exit 1

información relacionada