无法 运行 bash 来自 "The linux command line, a complete introduction, 2nd" 的脚本示例

Cant run bash script example from "The linux command line, a complete introduction, 2nd"

这是我的 zsh 脚本的示例,该脚本是从原始脚本修改而来的:

#!/bin/sh

set -e

# read-default.sh: supply a default value if user preses Enter key.

read -e -p "What is your user name? " -i $USER
echo "You answered: '$REPLY'"

这是本书的原始脚本:

#!/bin/bash
# read-default: supply a default value if user presses Enter key.
read -e -p "What is your user name? " -i $USER
echo "You answered: '$REPLY'"

这是我在 运行 zsh 脚本之后遇到的一个错误:

read-default.sh: line 7: read: -i: invalid option
read: usage: read [-ers] [-u fd] [-t timeout] [-p prompt] [-a array]
[-n nchars] [-d delim] [name ...]

如有任何帮助,我将不胜感激! :)

如您在 shell 的错误消息中所见,调用 read 时不能使用 -i 标志。要解决您的问题,您需要检查 $REPLY 是否为空,如果为空则提供默认值。

你的脚本是用什么语言写的?

Shell 用 bashzshsh 编写的脚本略有不同。

您似乎正在使用 bash 功能,但是 运行 代码带有 sh

read 命令是一个 shell 内置命令。查看相应的手册页,了解您的 shell.

允许使用哪些选项

对于您的示例,将 shebang(第一行)改回 #!/bin/bash 或 运行 脚本就足够了 bash read-default.sh