anvd
anvd

Reputation: 4047

Sum in shell script

Why can't I create a sum of total words in this script? I get the result something like:

 120+130

but it isn't 250 (as I expected)! Is there any reason?

#!/bin/bash

while [ -z "$count" ] ;
do
    echo -e "request :: please enter file name "
    echo -e "\n\tfile one : \c"
    read count

    itself=counter.sh

    countWords=`wc -w $count |cut -d ' ' -f 1`
    countLines=`wc -l $count |cut -d ' ' -f 1`
    countWords_=`wc -w $itself |cut -d ' ' -f 1`

    echo "Number of lines: " $countLines
    echo "Number of words: " $countWords
    echo "Number of words -script: " $countWords_

    echo "Number of words -total " $countWords+$countWords_  

done

if [ ! -e $count ] ; then
    echo -e "error :: file one $count doesn't exist. can't proceed."
    read empty
    exit 1
fi

Upvotes: 0

Views: 1754

Answers (2)

SiegeX
SiegeX

Reputation: 140237

echo "Number of words -total " $countWords+$countWords_

You want this:

echo "Number of words -total $((countWords + countWords_))"

Edit

Here are some optimizations to your script.

  1. The while loop seems pointless since count is going to get set for sure inside making this a 1-iteration while loop.
  2. Your if check on existence of the file should happen before you ever use that file.
  3. You don't need to hardcode the name of your script to the variable itself, you can use $0 for that
  4. Since you are using bash I took the liberty to remove the need for cut by using process substitution.

Here is the revised script:

#!/bin/bash

echo -e "request :: please enter file name "
echo -e "\n\tfile one : \c"
read count

if [ ! -e "$count" ] ; then
    echo "error :: file one $count doesn't exist. can't proceed."
    exit 1
fi

itself="$0"

read countWords _ < <(wc -w $count)
read countLines _ < <(wc -l $count)
read countWords_ _ < <(wc -w $itself)

echo "Number of lines: '$countLines'"
echo "Number of words: '$countWords'"
echo "Number of words -script: '$countWords_'"

echo "Number of words -total $((countWords + countWords_))"

Upvotes: 6

Amir Afghani
Amir Afghani

Reputation: 38511

One way to go about this is:

echo `expr $countWords + $countWords_`

Upvotes: 1

Related Questions