POSIX 호환 쉘에서 비밀번호를 요청 하시겠습니까? bash스크립트 에서 비밀번호를

bash스크립트 에서 비밀번호를 요청하고 싶을 때 다음과 같이합니다.

read -s

…하지만 bashPOSIX 모드로 실행 sh하면 -s옵션이 거부됩니다.

$ read -s
sh: 1: read: Illegal option -s

POSIX 호환 명령으로 입력을 안전하게 요청하려면 어떻게합니까?



답변

read_password() {
  REPLY="$(
    # always read from the tty even when redirected:
    exec < /dev/tty || exit # || exit only needed for bash

    # save current tty settings:
    tty_settings=$(stty -g) || exit

    # schedule restore of the settings on exit of that subshell
    # or on receiving SIGINT or SIGTERM:
    trap 'stty "$tty_settings"' EXIT INT TERM

    # disable terminal local echo
    stty -echo || exit

    # prompt on tty
    printf "Password: " > /dev/tty

    # read password as one line, record exit status
    IFS= read -r password; ret=$?

    # display a newline to visually acknowledge the entered password
    echo > /dev/tty

    # return the password for $REPLY
    printf '%s\n' "$password"
    exit "$ret"
  )"
}

printf내장 되어 있지 않은 쉘 (mksh)의 경우 , 암호는 ps출력에서 몇 마이크로 초 동안 명확하게 표시 되거나 매개 변수를 가진 모든 명령 호출이 감사되면 일부 감사 로그에 표시 될 수 있습니다.


답변

read -sPOSIX에 없습니다. POSIX 호환이 되려면를 사용하십시오 stty -echo. stty그리고 그 echo매개 변수 는 POSIX에 정의되어 있습니다.

#!/bin/bash
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"

이것은 POSIX를 준수하는 모든 쉘에서 작동합니다.

출처


답변