Skip navigation

很多脚本需要以root来执行,因此当前用户不是root的时候可以提示并引导用户获得root权限再执行。至少比看到一堆Permission Denied要友好一些。这里给出一个自动调用sudo的bash函数:

invoke_sudo()
{
    if [ "`id -u`" != "`id -u $1`" ]; then 
        echo "`whoami`: you need $1 priviledge to run this application."
        if [ "$AUTO_INVOKE_SUDO" == "yes" ]; then 
            echo "Invkoing sudo ..."
            sudo -u "#`id -u $1`" bash -c "$2"
        fi 
        exit 0
    fi
}
# 使用方法是
#
# invoke_sudo root "$0 $@"

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>