skip to Main Content

I would like to check if the user has sudo privileges. This is an approximate example of what I am trying to do. I am trying to get this to work across the following os: centos, ubuntu, arch.

if userIsSudo; then
 chsh -s $(which zsh)
fi

3

Answers


  1. sudo -l will display the commands that the user can run with sudo privileges. If there are no commands that can be run, sudo -l will return an error code and so you could try:

    sudo -l && chsh -s $(which zsh)
    
    Login or Signup to reply.
  2. Try with this:

    $ sudo -v &> /dev/null && echo "Sudoer" || echo "Not sudoer"
    

    Also, IDK how secure will be searching for his membership in the sudo group, i.e:

    $ groups "$(id -un)" 
        | grep -q ' sudo ' 
            && echo In sudo group 
            || echo Not in sudo group
    

    Or:

    $ getent group sudo 
        | grep -qE "(:|,)$(id -un)(,|$)" 
            && echo in sudo group 
            || echo not in sudo group
    
    Login or Signup to reply.
  3. Usually when you run an script you want to know if end it well or you got an error or what kind of error you got if there was any.

    This is a more elaborated snippet, sudoer-script.sh:

    ## Define error code
    E_NOTROOT=87 # Non-root exit error.
    
    ## check if is sudoer
    if ! $(sudo -l &> /dev/null); then
        echo 'Error: root privileges are needed to run this script'
        exit $E_NOTROOT
    fi
    
    ## do something else you 
    
    ## means it was successfully executed
    exit 0
    

    Now you can reuse your script, pipe it or concatenate with other commands

    sudoer-script.sh && ls
    
    ## in a script
    if $(sudoer-script.sh); then
      echo 'success'
    fi
    
    ## capture error
    stderr=$(./sudoer-script.sh 2>&1 >/dev/null)
    echo $stderr
    

    As a function:

    is_sudoer() {
        ## Define error code
        E_NOTROOT=87 # Non-root exit error.
    
        ## check if is sudoer
        if ! $(sudo -l &> /dev/null); then
            echo 'Error: root privileges are needed to run this script'
            return $E_NOTROOT
        fi
        return  0
    }
    
    if is_sudoer; then
        echo "Sudoer"
    else
        echo "Not sudoer"
    fi
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search