我正在尝试在 Ubuntu 22.04 的 Bash 脚本中使用静默阅读:
#!/bin/bash
sensitive_input() {
read -rsp "${1}: " value
echo "$value"
}
x=$(sensitive_input "Password: ")
我得到:
read: Illegal option -s
如果我在终端上尝试
read -rsp "test: " value
,它会起作用。
为什么会这样? shell脚本出了什么问题?
你如何调用你的脚本?
我猜你正在做类似的事情:
$ sh script_name
这将导致脚本在
sh
shell 下运行,在我的 Ubuntu 22.04
环境中实际上是 dash
并且 dash
不支持 -s
的 read
选项。我们可以在下面看到这一点:
#### run on Ubuntu 22.04; my default shell is bash
$ man sh # brings up the man page for dash
$ read -rsp "Password: " value # run under bash
Password: # success
$ sh # switch from bash to sh
$ read -rsp "Password: " value
sh: 1: read: Illegal option -s # error
$ exit # switch back to bash
$ dash # explicitly switch to dash
$ read -rsp "Password: " value
dash: 1: read: Illegal option -s # error
确保您的脚本使用 shebang 中列出的 shell:
#### following works as desired regardless of the command line shell (bash, sh, dash)
$ chmod +x script_name # insure script is executable (per Ted Lyngmo comment)
$ ./script_name # let OS determine shell from shebang
Password: # success