Bash scripts requiring sudo password

前端 未结 4 1090
北海茫月
北海茫月 2021-01-31 07:58

I\'m creating a Bash installer script which compiles and installs some libraries for both OSX and Linux. Because some commands in my script (\"make install\", \"apt-get install\

相关标签:
4条回答
  • 2021-01-31 08:43

    To get the password, just put sudo echo "Thanks." at the start of the script.

    But I would prefer this solution:

    if [[ $UID != 0 ]]; then
        echo "Please run this script with sudo:"
        echo "sudo $0 $*"
        exit 1
    fi
    
    0 讨论(0)
  • 2021-01-31 08:49

    Another way to go about it :

    function checkSudo() {
        if ((EUID != 0)); then
            echo "Granting root privileges for script ( $SCRIPT_NAME )"
            if [[ -t 1 ]]; then
                sudo "$0" "$@"
            else
                exec 1>output_file
                gksu "$0" "$@"
            fi
            exit
        fi
    }
    
    0 讨论(0)
  • 2021-01-31 08:53

    Maybe a bit easier to read:

    [ $(whoami) == "root" ] || exit
    
    0 讨论(0)
  • 2021-01-31 09:03

    For those who don't want to elevate the entire script (to limit risks by only using sudo within the script where needed) the first part of the accepted answer sudo echo "Thanks" works but won't respond to sudo password failure by exiting the script. To accomplish this, scripts that include sudo commands and want to ensure sudo access before it's used could start with

    if [[ ! $(sudo echo 0) ]]; then exit; fi
    

    The caveat is that you are relying on the existence of a sudoers timeout that will last the duration of your script to suppress the rest of the prompts.

    0 讨论(0)
提交回复
热议问题