How to check if cygwin mintty/bash is run as administrator?

I just wrote this function for the same reason. I never know which shell has admin privileges.

function isadmin()
{
    net session > /dev/null 2>&1
    if [ $? -eq 0 ]; then echo "admin"
    else echo "user"; fi
}

It adapted from this answer https://stackoverflow.com/a/11995662/307968 for windows cmd shell. Net Session returns 0 status if you are admin.

Now I just need to change my prompt, or maybe the titlebar color....


The definitive answer to this question comes from the Cygwin mailing list. A process is running with Administrator rights if the user who started it is part of group 544 (Administrators). Also from the comment below by Cromax, it seems that group 114 (Local account and member of Administrator group) is also sometimes present. The test for these two groups is

id -G | grep -qE '\<(114|544)\>'

or in bash without external calls,

[[ "${GROUPS[@]}" =~ (^| )(114|544)( |$) ]]

For example,

id -G | grep -qE '\<(114|544)\>' && echo admin || echo user

In the past you also needed to check for group 0, the root group in /etc/group. But /etc/group is no longer installed in Cygwin, and should usually be removed if it's present, so it's no longer recommended to check for group 0 too.


I use the return value of the Windows program at. I also recreated the functionality of the PROMPTING special character \$.

# Set a white $ initially
eStyle='\[\e[0m\]$'

# If 'at' succeeds, use a red # instead
at &> /dev/null && eStyle='\[\e[0;31m\]#\[\e[0m\]'  # Use # in red

PS1='\n\[\e[0;32m\]\u@\h \[\e[0;33m\]\w\[\e[0m\]\n'"$eStyle "

Examples


Do something that only admin could do and test for success or fail:-

if touch c:/Users/.x ; then  echo 'ok'  ; fi

or

touch c:/Users/.x && echo ok

or

touch c:/Users/.x && \rm c:/Users/.x && echo ok

or

touch c:/Users/.x  &> /dev/null && \rm c:/Users/.x && echo you are admin

id -G | grep -qE '\<(544|0)\>' didn't seem to work for me, as my output had neither <> or 544 even when elevated. However, since elevation is required for writing to %WINDIR%\system32, I used that to test for elevation with a shell function:

is_elevated() { 
   [[ $(uname -o) -eq "Cygwin" ]] || return 1
   touch $WINDIR/system32/.cyg_elevated &> /dev/null
}

When applied to Steven's excellent idea of a red hash character:

is_elevated && PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\[\e[0;31m\]#\[\e[0m\] '