如何检查是否在bash脚本以root身份运行 [英] How to check if running as root in a bash script

查看:635
本文介绍了如何检查是否在bash脚本以root身份运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写需要root级别权限的脚本,我希望让这个如果脚本不以root身份运行,它只是呼应请以root身份运行。并退出。

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 exits.

下面是一些伪code什么我要找:

Here's some pseudocode for what I'm looking for:

if (whoami != root)
  then echo "Please run as root"

  else (do stuff)
fi

exit

我最好的(干净和安全)怎么能做到这一点?谢谢!

How could I best (cleanly and securely) accomplish this? Thanks!

嗯,我只想澄清:在(做的东西)部分将涉及运行的命令,在-和自身需要根。所以运行它作为一个普通用户只想拿出一个错误。这只是为了顺利运行需要root命令的脚本,而不使用脚本中sudo的,我只是在寻找一些语法糖。

Ah, just to clarify: the (do stuff) part would involve running commands that in-and-of themselves require root. So running it as a normal user would just come up with an error. This is just meant to cleanly run a script that requires root commands, without using sudo inside the script, I'm just looking for some syntactic sugar.

推荐答案

一个几个答案已经给出,但现在看来,最好的方法是使用的是:

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


  • 标识-u

  • 如果以root身份运行,将返回0的ID。

这似乎是比其他方法更可靠,它似乎返回即使脚本通过须藤运行0的ID。

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.

这篇关于如何检查是否在bash脚本以root身份运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆