【问题标题】:How to create a shell script (/bin/sh) with option -s and read input inside如何使用选项 -s 创建 shell 脚本 (/bin/sh) 并读取里面的输入
【发布时间】:2016-08-04 08:45:44
【问题描述】:

我想像这样运行一个 shell 脚本 (POSIX)。

#!/bin/sh
# this is a.sh
echo your age?
read age
echo "You are $age."

如果这是通过标准输入扔到/bin/sh

cat a.sh | /bin/sh -s

那么问题就被跳过了。

我该如何提问?

【问题讨论】:

  • 有没有理由你以这种方式运行它而不是/bin/sh a.sh?问题是a.sh 从对/bin/sh 的调用继承了它的标准输入,/bin/sh 的标准输入是a.sh/bin/sh 读取第一行和第二行,但您的 read 语句读取第三行。由于没有更多输入供/bin/sh 读取,因此退出。

标签: shell pipe posix sh


【解决方案1】:

问题在于/bin/sh 正在读取脚本,而您的脚本正在读取来自同一输入文件的输入:cat a.sh 提供的管道。

一种解决方案是修改您的脚本以从终端直接读取,而不是标准输入,尽管这可能不是您想要的。

echo "your age?"
read age < /dev/tty
echo "Your age $age"

更好的解决方案是不从标准输入读取脚本;只需将其作为参数传递给/bin/sh

/bin/sh a.sh

【讨论】:

    【解决方案2】:

    试试 -n 选项

    echo -n "your age?"
    read age
    echo "Your age $age"
    

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 1970-01-01
      • 2012-05-22
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2017-12-02
      相关资源
      最近更新 更多