El -s
Option von read
ist im POSIX-Standard nicht definiert. Siehe http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html . Ich wollte etwas, das für jede POSIX-Shell funktioniert, also habe ich eine kleine Funktion geschrieben, die stty
um das Echo zu deaktivieren.
#!/bin/sh
# Read secret string
read_secret()
{
# Disable echo.
stty -echo
# Set up trap to ensure echo is enabled before exiting if the script
# is terminated while echo is disabled.
trap 'stty echo' EXIT
# Read secret.
read "$@"
# Enable echo.
stty echo
trap - EXIT
# Print a newline because the newline entered by the user after
# entering the passcode is not echoed. This ensures that the
# next line of output begins at a new line.
echo
}
Diese Funktion verhält sich ganz ähnlich wie die read
Befehl. Hier ist eine einfache Verwendung von read
gefolgt von einer ähnlichen Verwendung von read_secret
. Die Eingabe in read_secret
erscheint leer, weil es nicht an das Terminal zurückgesendet wurde.
[susam@cube ~]$ read a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret a b c
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=bar c=baz qux
[susam@cube ~]$ unset a b c
Hier ein weiteres Beispiel, das die -r
um die Backslashes in der Eingabe zu erhalten. Dies funktioniert, weil die read_secret
Funktion, die oben definiert wurde, übergibt alle Argumente, die sie erhält, an die read
comando.
[susam@cube ~]$ read -r a b c
foo \bar baz \qux
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c
[susam@cube ~]$ read_secret -r a b c
[susam@cube ~]$ echo a=$a b=$b c=$c
a=foo b=\bar c=baz \qux
[susam@cube ~]$ unset a b c
Zum Schluss noch ein Beispiel, das zeigt, wie man die read_secret
Funktion, um ein Kennwort auf POSIX-konforme Weise zu lesen.
printf "Password: "
read_secret password
# Do something with $password here ...