How can I use 'do I have root access?' as a conditional in bash?

感情迁移 提交于 2020-01-17 03:59:30

问题


I am writing an installation script, and would like it to install in a local directory if the user does not have root access.

specifically, I am looking for the code that goes between the carats (<>)

if [[<do I have root access? = TRUE>]]; then
    .. install .. 
else
    .. install  in $HOME/mylib .. 
fi

回答1:


For bash, you can use the EUID variable:

if [ "$EUID" == 0 ] ; then
    ..something..
else
    ..something else
fi

For a POSIX-compliant solution, use:

if [ "`id -u`" == 0 ] ; then

Although be aware that the usual answer to your question is "don't do that". You never know when someone will decide to run your code in an environment you did not expect... So in general, instead of "check permissions then do something", a better approach is "try to do something and then detect if it fails".




回答2:


Try this:

http://www.cyberciti.biz/tips/shell-root-user-check-script.html



来源:https://stackoverflow.com/questions/7251335/how-can-i-use-do-i-have-root-access-as-a-conditional-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!