简体   繁体   中英

bash scripting reading numbers from a file

Hello i need to make a bash script that will read from a file and then add the numbers in the file. For example, the file im reading would read as:

cat samplefile.txt

 1
 2
 3
 4

The script will use the file name as an argument and then add those numbers and print out the sum. Im stuck on how i would go about reading the integers from the file and then storing them in a variable. So far what i have is the following:

#! /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 

What's the problem? Your code looks fine, except readnums is not a valid command name, and you need spaces inside the square brackets in the if condition. (Oh and "$file" should properly be inside double quotes.)

#!/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

However, the shell is not traditionally a very good tool for arithmetic. Maybe try something like

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

perhaps inside a snippet of shell script to check that the file exists, etc (though you'll get a reasonably useful error message from Awk in that case anyway).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM