重定向stdin会引发严重的重定向错误

时间:2016-04-17 18:54:40

标签: linux bash shell scripting

我试图从文件或用户的输入中读取数据,以便在bash shell脚本中处理它。我是新手,当脚本接受文件作为参数时,我的代码工作到目前为止。当我尝试创建一个新文件,我可以读取用户的输入并处理它时,它会抛出一个错误:$ datafilepath模糊重定向。我觉得我非常接近它,但我可能会错过一些好的语法。有人能把我推向正确的方向吗?谢谢!

#!/bin/bash
if [ "$#"  = "1" ]
then
    cat >>"$datafilepath"
elif  [ "$#" = "2" ]
then
    datafilepath=$2
fi

echo Average Median
while read myLine
do
    sum=0
    med=0
    for word in $myLine
        do
            sum=`expr $sum + $word`
            echo -e $word >> medfile
        done

sort < medfile >sorted
cat sorted | tr '\n' '\t' > rowfile
printf "%.0f\t%.0f\n" $(echo "scale=2; $sum/5" | bc ) $(cut -d' ' -f3 rowfile)
rm -f medfile
rm -f sorted
rm -f rowfile
done <$datafilepath 

1 个答案:

答案 0 :(得分:1)

#!/bin/bash
if [ "$#"  = "1" ]
then
    cat >>"$datafilepath"
elif  [ "$#" = "2" ]
then
    datafilepath=$2
fi

$datafilepath首先出现在第4行,但它尚未初始化,因此它是空白的。 shell'&gt;&gt;'除非有文件名,否则不会追加。之前需要有一行将$ datafilepath设置为默认文件名。

第2行:'1'应为'0'。 第5行:'2'应为'1' 第7行:'$ 2'应该是'$ 1'

此块有一个不必要的文件“已排序”:

sort < medfile >sorted
cat sorted | tr '\n' '\t' > rowfile
printf "%.0f\t%.0f\n" $(echo "scale=2; $sum/5" | bc ) $(cut -d' ' -f3 rowfile)
rm -f medfile
rm -f sorted
rm -f rowfile

建议减少:

sort medfile | tr '\n' '\t' > rowfile
printf "%.0f\t%.0f\n" $(echo "scale=2; $sum/5" | bc ) $(cut -d' ' -f3 rowfile)
rm -f medfile rowfile