【发布时间】:2020-12-25 22:17:00
【问题描述】:
我在下面有这个 sn-p 的想法是通过 @SiegeX 和 @mklement0 屏蔽来自 this question 的密码输入。
太好了,我唯一想要的补充是只删除输入字符的长度,所以我们不会抹去整行。
这个我不是很懂,所以遇到了bug。
在下面输入“12345”并退格,数字不会“退格”;没有错误。
输入“123FourFive”并退格,产生错误:line 9: [[: 123FourFiv: value too great for base (error token is "123FourFiv")
输入“OneTwo345”和退格,似乎工作正常。
在密码中输入可能期望的符号,然后退格会产生错误:line 9: [[: OneTwo./?: syntax error: invalid arithmetic operator (error token is "./?")
在输入过程中按箭头键也会在退格后产生疯狂的屏幕行为...
如何改进这一点,以便我们屏蔽用户输入,只删除输入的内容?
还是我们在“重新发明轮子”?还有其他东西可以做我已经尝试做的事情(即屏蔽用户输入以在 bash 脚本中获取密码以将其放入变量中)?
用户环境是带有 Cinnamon 的 Linux Mint 19.3。
#!/bin/bash
printf "\n\tPlease enter password: "
# mask the input for the password by @SiegeX and @mklement0 (https://stackoverflow.com/questions/4316730)
while IFS= read -r -s -n1 char; do
[[ -z "${char}" ]] && { printf '\n'; break; } # ENTER pressed; output \n and break.
if [[ "${char}" == $'\x7f' ]]; then # backspace was pressed
# @nooblag, only delete for length of entered chars?
if [[ "${password}" -lt "${#password}" ]]; then printf '\b \b'; fi # erase one '*' to the left.
[[ -n $password ]] && password=${password%?} # remove last char from output variable
else
# add typed char to output variable
password+="${char}"
# print '*' in its stead
printf '*'
fi
done
printf "\tPassword: ${password}\n\n"
更新: askpass 建议 here 几乎可以满足我的要求,但是如果用户尝试使用 Ctrl+C 中止/杀死它,它会弄乱终端...
【问题讨论】:
-
检查这个:stackoverflow.com/questions/4316730/…,而不是构建你的解决方案,它可能是有效的
-
谢谢,但是上面我遇到问题的代码是基于该链接的建议。
标签: bash input passwords masking