On April 28, 2022 6:22 PM, Junio C Hamano wrote: ><rsbecker@xxxxxxxxxxxxx> writes: > >>>is_root() { >>> id -u >u >>> id -u root >r >>> cmp u r >>>} >> >> This is about as portable as I can find and works even in ksh. It could be >optimized. >> >> is_root() { >> id -u >u >> id -u root >r >> cmp -s u r >> if [ $? -ne 0 ]; then >> echo 0 >> else >> echo 1 >> fi >> } >> >> if [ `is_root` -ne 0 ]; then >> echo root >> else >> echo Not root >> fi > >The above looks very roundabout way. With the first three in is_root that ends >with "cmp", we already know from its exit status if "id -u" output for ourselves >matches that for root, i.e. if we are root then cmp would have exited with 0. > >So with the first one I quoted from your quote, the caller can say > > if is_root > then > echo root > else > echo not root > fi > >without turning the exit status into string "0" or "1" and comparing that string with >"[ `cmd` -ne 0 ]". And the first one is just as portable. I agree that running cmp >with "-s" is probably a good idea. > >What I used to often use in my previous life (in previous century) is technically >incorrect, but is a lot more succinct and works well in practice on any sanely >installed systems. Just see if the root directory is writable. No sane system makes >it writable by anybody but root. > >I.e. > > if test -w / > then > ... we are running as root ... > else > ... we are not running as root ... > fi I agree. I think my ksh is rather broken. But we use bash for git testing and can never go back to ksh, so no worries on that score. Thanks.