Bash while循环完成<$ 1

问题描述:

我有点困惑done < $1表示法。

我正试图编写一个程序“sumnums”,它读入一个名为“nums”的文件,该文件有几行数字。然后它应该打印出数字的行,然后是所有数字的总和。

目前我有:

#!/bin/bash 
sum=0; 
while read myline 
do 
    echo "Before for; Current line: \"$myline\"" 
done 
for i in $myline; do 
    sum=$(expr $sum + $i) 
done < $1  
echo "Total sum is: $sum" 

并正确输出的数字从NUMS列表,然后说 ./sumnums: line 10: $1: ambiguous redirect,然后输出Total sum is: 0

因此不知何故,它不是添加。如何重新排列这些行来修复程序并摆脱“不明确的重定向”?

+0

你怎么调用你的脚本?要么称之为'./sumnum nums'或将'done codeforester

+0

'cat nums | 。/ sumnums' – themightyscot

+0

脚本需要该文件作为参数。 – karakfa

awk来救援!

awk '{for(i=1;i<=NF;i++) sum+=$i} END{print "Total sum is: " sum}' file 

bash不适合这项任务。

+0

“done

假设你的文件名是$1(也就是你的脚本与./yourscript nums称呼):

#!/bin/bash 

[[ $1 ]] || set -- nums ## use $1 if already set; otherwise, override with "nums" 

sum=0 
while read -r i; do  ## read from stdin (which is redirected by < for this loop) 
    sum=$((sum + i))  ## ...treat what we read as a number, and add it to our sum 
done <"$1"    ## with stdin reading from $1 for this loop 
echo "Total sum is: $sum" 

如果$1不包含您的文件名,然后使用一些包含在你的文件名它的位置,或者只是硬编码实际的文件名本身。

注:

  • <"$1"应用于while read循环。这是必不可少的,因为read(在此上下文中)是实际使用文件内容的命令。它可以是有意义的重定向标准输入到for循环,但只有当该循环内的东西是从标准输入读取。
  • $(())是现代POSIX sh算术语法。 expr是传统语法;不要使用它。
+0

对一个有问题的问题的很好的答案! – codeforester