2015-03-02 110 views
0

您好,我需要制作一个bash脚本,它将从文件中读取数据,然后在文件中添加数字。例如,文件即时阅读会为已读:bash脚本读取文件中的数字

猫samplefile.txt

1 
2 
3 
4 

脚本会使用文件名作为参数,然后添加这些数字并打印出总和。我坚持如何从文件中读取整数,然后将它们存储在一个变量中。 到目前为止,我拥有以下内容:

#! /bin/bash 

file="$1" #first arg is used for file 
sum=0  #declaring sum 
readnums #declaring var to store read ints 

if [! -e $file] ; do  #checking if files exists 
    echo "$file does not exist" 
    exit 0 
fi 

while read line ; do 

do < $file 

exit 

回答

1

问题是什么?您的代码看起来很好,除了readnums不是有效的命令名称,并且您需要if条件的方括号内的空格。 (哦,"$file"应该适当地双引号)。

#!/bin/bash 

file=$1 
sum=0 

if ! [ -e "$file" ] ; do  # spaces inside square brackets 
    echo "$0: $file does not exist" >&2 # error message includes $0 and goes to stderr 
    exit 1     # exit code is non-zero for error 
fi 

while read line ; do 
    sum=$((sum + "$line")) 
do < "$file" 


printf 'Sum is %d\n' "$sum" 
# exit      # not useful; script will exit anyway 

然而,外壳是不是传统的算术一个很好的工具。也许你可以试试

awk '{ sum += $1 } END { print "Sum is", sum }' "$file" 

也许shell脚本的一个片段里面,以检查文件是否存在,等等(虽然你会在这种情况下得到awk中一个相当有用的错误消息,反正)。