【问题标题】:Cant run bash script example from "The linux command line, a complete introduction, 2nd"Cant run bash script example from "The linux command line, a complete introduction, 2nd"
【发布时间】:2015-04-06 22:02:12
【问题描述】:

这是我的 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 ...]

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

【问题讨论】:

  • 您不能对read 使用-i 选项
  • 哦,谢谢,但是我怎样才能以另一种方式运行这个脚本呢?
  • 你需要检查$REPLY是否为空。
  • 非常感谢,我正在考虑!
  • 将 zsh 与 bash 书一起使用,或者相反,不是一个好习惯;它们是不同的外壳,具有不同的扩展名和与 POSIX sh 的不同偏差。

标签: macos bash shell unix zsh


【解决方案1】:

您的脚本是用什么语言编写的?

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

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

read 命令是一个内置的 shell。查看相应的手册页,了解您的 shell 允许哪些类型的选项。

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

【讨论】:

  • 我正在使用zsh作为我的登录shell,我已经解决了这个问题,按照你说的更改了shebang,并使用bash运行脚本,谢谢!
【解决方案2】:

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

【讨论】:

  • 不能投票给你的答案,没有声誉,再次感谢。 :)
  • @kostyawhite,哎呀,真可惜 :-)
  • 是的,因为这是我的第一个问题,你是第一个帮助我的人!
  • 你的意思是你的答案?
  • @kostyawhite,是的,还有什么? :)
猜你喜欢
  • 2022-12-27
  • 2021-12-10
  • 2022-12-02
  • 1970-01-01
  • 2022-12-26
  • 2022-12-02
  • 2022-12-26
  • 2022-12-01
  • 2022-12-01
相关资源
最近更新 更多