【问题标题】:Reading From Standard Input In Bash Programming在 Bash 编程中读取标准输入
【发布时间】:2014-04-26 01:52:25
【问题描述】:

我一直在为 Uni 做一个 bash 编程作业,一切正常,除了 Automark 软件(它是黑盒)给我一个 0/​​5。我联系了我的 Uni 讲师,他回答说:

“对于“从标准输入读取”的含义似乎有些混淆。这意味着您是从终端的键盘而不是从命令行读取的......这个错误在 histo (以前的程序)中。它也似乎在 histoplot 中。(我在这里谈论的程序)“

现在我不知道这是什么意思。我浏览了整个互联网,我认为我的代码是从标准输入中读取的。

这不是“While Read Line”的作用吗?我的程序获取数据并将其转换为如下所示的 Histoplot:

 1 1
 2 3
 3 2
 4 1

把它变成这样:

 1 #
 2 ###
 3 ##
 4 #

这是我的代码(抱歉有这么多):

 #!/bin/bash

 addWordcount=0
 customHash=0
 customHashchoice="#"

 scale=0


 for i in $*
 do
         if [[ $i = "-c" ]]
     then
     addWordcount=1 
     elif [[ $i = "-p" ]] 
     then
     customHash=1

     elif [[ $i = "-s" ]]   
     then
     scale=1
         fi
 done
 for x in $*
 do 
 if [ -f $x ] ; then
         while read line    
         do     
             lineAmnt=${line% *}
             hashNo=${line##* }
             for ((i=0; i<hashNo; i++))

            do
            hashes+="#" 
            #hashNumber=$(expr $hashNumber - 1)
            done    
        printf "%3s" $lineAmnt 

        if [[ $addWordcount -eq 1 ]] 
        then
            printf "%5s"$hashNo
        fi

        printf " $hashes\n"
        hashes=""   
    done < $x
     fi
 done

【问题讨论】:

  • while read line 确实从标准输入读取。 stdin 总是(甚至通常)是键盘,但很多人将两者混为一谈。不要让自己陷入认为 stdin 是键盘的陷阱。

标签: linux bash input stdin


【解决方案1】:

while read line 确实从标准输入读取,但您使用了重定向。通过编写while read line; do ... done &lt; $x,您正在使以$x 命名的文件成为while read 循环的标准输入,而不是从您的bash 脚本的标准输入中读取。也就是说,该脚本的标准输入与 while 循环的标准输入不同。

只需省略重定向即可。

【讨论】:

  • 感谢您的意见! “省略重定向”是什么意思?删除倒数第三行的“
  • @BarneyChambers:是的。 &lt; $x 是重定向的一个实例,感谢&lt;;更具体地说,它是一个 input 重定向(相比之下,将 stdout 重定向到带有 &gt; outfile 的文件是 output 重定向的一个实例) .