How to check if running as root in a bash script

前端 未结 17 777
太阳男子
太阳男子 2020-12-04 04:44

I\'m writing a script that requires root level permissions, and I want to make it so that if the script is not run as root, it simply echoes \"Please run as root.\" and exit

17条回答
  •  没有蜡笔的小新
    2020-12-04 05:34

    A few answers have been given, but it appears that the best method is to use is:

    • id -u
    • If run as root, will return an id of 0.

    This appears to be more reliable than the other methods, and it seems that it return an id of 0 even if the script is run through sudo.

提交回复
热议问题