How to check if running as root in a bash script

前端 未结 17 772
太阳男子
太阳男子 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:31

    try the following code:

    if [ "$(id -u)" != "0" ]; then
        echo "Sorry, you are not root."
        exit 1
    fi
    

    OR

    if [ `id -u` != "0" ]; then
        echo "Sorry, you are not root."
        exit 1
    fi
    

提交回复
热议问题