0

I want a script shell make the user use su not sudo

I want a script check if i use sudo or su in my command, like :

if [ "$USER" != "root" -a "$0" = "sudo" ];then

    echo "You have to run this script as a root \"Use : su \" "

fi 

I know is wrong, can anybody help me ??

  • 1
    Why do you need to do this? What is the underlying problem you are trying to solve? – Explosion Pills Nov 02 '15 at 22:23
  • You may want to check this out: http://serverfault.com/questions/568627/can-a-program-tell-it-is-being-run-under-sudo – Javier Conde Nov 02 '15 at 22:25
  • i know all the example to run as a root but i want create a script for arch and arch u can use sudo and su so how do i know when he use sudo and when he use su – zakaria gatter Nov 02 '15 at 22:38
  • did you read my last comment ?? – zakaria gatter Nov 02 '15 at 23:18
  • `su` runs a shell under a different user id; `sudo` runs an arbitrary command under a different user id, so `su root` and `sudo -u root sh` essentially do the exact same thing. Why do you need to differentiate between two? – chepner Nov 03 '15 at 15:09

1 Answers1

3

You can use the $EUID since the effective user id will always be 0 for sudo :) Example:

#!/usr/bin/env bash
if [[ $EUID = 0 ]]; then
    echo "sudo!"
else
    echo "not sudo!"
fi

Edit:

above doesn't work, but if you just want to check this from a simple bash script you could do this hack:

#!/usr/bin/env bash
if [[ $EUID = 0 && "$(ps -o comm= | sed -n '1p')" = "su" ]]; then
    echo "sudo!"
else
    echo "not sudo!"
fi

Will obviously not recognize normal root shells, but actual su use is properly recognized. ( could break when called by another script :/ )

really dirty and not stable against nested su use (where sudo could still pass when ran from nested su) , it might suffice to do something like this:

#!/usr/bin/env bash
if [[ $EUID = 0 && "$(ps -o comm= | grep su | sed -n '1p')" = "su" ]]; then
    echo "sudo!"
else
    echo "not sudo!"
fi

... admittedly a solution from the (NOT OK!) category ...

Armin Braun
  • 3,645
  • 1
  • 17
  • 33