How do I get `make` to prompt the user for a password and store it in a Makefile variable?

后端 未结 2 1696
抹茶落季
抹茶落季 2021-02-04 04:12

I\'m writing a Makefile, and some of the commands the makefile runs require a password. I\'d like to give the user the ability to either pass this in as a Makefile variable usi

相关标签:
2条回答
  • 2021-02-04 04:31

    A couple of things:

    • the $ for dereferencing shell variable pwd is being interpreted by make. You can escape it from make with $$
    • make is invoking the shell as Posix compatible /bin/sh instead of /bin/bash. As such, the -s option to read is not supported.

    Try this instead:

    PASSWORD ?= $(shell bash -c 'read -s -p "Password: " pwd; echo $$pwd')
    

    This worked for me on Ubuntu 12.04 / GNU make 3.81 / bash 4.2.25(1)

    And on OSX 10.8.5 / make 3.81 / bash 3.2.48(1):

    $ cat Makefile 
    PASSWORD ?= $(shell bash -c 'read -s -p "Password: " pwd; echo $$pwd')
    
    all:
        echo The password is $(PASSWORD)
    $ make
    Password: echo The password is 1234
    The password is 1234
    $ 
    

    Update - @user5321531 pointed out that we can use POSIX sh instead of bash, and temporarily suppress echo with stty:

    PASSWORD ?= $(shell stty -echo; read -p "Password: " pwd; stty echo; echo $$pwd)
    
    0 讨论(0)
  • 2021-02-04 04:41

    To answer @joeb 's question:

    $ make; echo "---Makefile---"; cat Makefile
    Password: <hidden>
    test
    test
    ---Makefile---
    all: first second
    PASSWORD ?= $(shell read -s -p "Password: " pass; echo $$pass)
    define formatted
    first:
            @echo $1
    second:
            @echo $1
    endef
    
    $(eval $(call formatted,$(PASSWORD)))
    
    0 讨论(0)
提交回复
热议问题