How can I add numbers in a bash script

2019-01-01 09:25发布

I have this bash script and I had a problem in line 16. How can I take the previous result of line 15 and add it to the variable in line 16?

#!/bin/bash

num=0
metab=0

for ((i=1; i<=2; i++)); do      
    for j in `ls output-$i-*`; do
        echo "$j"

        metab=$(cat $j|grep EndBuffer|awk '{sum+=$2} END { print sum/120}') (line15)
        num= $num + $metab   (line16)
    done
    echo "$num"
 done

10条回答
浅入江南
2楼-- · 2019-01-01 10:08

I really like this method as well, less clutter:

count=$[count+1]
查看更多
看风景的人
3楼-- · 2019-01-01 10:13

In bash,

 num=5
 x=6
 (( num += x ))
 echo $num   # ==> 11

Note that bash can only handle integer arithmetic, so if your awk command returns a fraction, then you'll want to redesign: here's your code rewritten a bit to do all math in awk.

num=0
for ((i=1; i<=2; i++)); do      
    for j in output-$i-*; do
        echo "$j"
        num=$(
           awk -v n="$num" '
               /EndBuffer/ {sum += $2}
               END {print n + (sum/120)}
           ' "$j"
        )
    done
    echo "$num"
done
查看更多
旧时光的记忆
4楼-- · 2019-01-01 10:13

I always forget the syntax so I come to google, but then I never find the one I'm familiar with :P. This is the cleanest to me and more true to what I'd expect in other languages.

i=0
((i++))

echo $i;
查看更多
人间绝色
5楼-- · 2019-01-01 10:13

Another portable POSIX compliant way to do in bash, which can be defined as a function in .bashrc for all the arithmetic operators of convenience.

addNumbers () {
    local IFS='+'
    printf "%s\n" "$(( $* ))"
}

and just call it in command-line as,

addNumbers 1 2 3 4 5 100
115

The idea is to use the Input-Field-Separator(IFS), a special variable in bash used for word splitting after expansion and to split lines into words. The function changes the value locally to use word-splitting character as the sum operator +.

Remember the IFS is changed locally and does NOT take effect on the default IFS behaviour outside the function scope. An excerpt from the man bash page,

The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.

The "$(( $* ))" represents the list of arguments passed to be split by + and later the sum value is output using the printf function. The function can be extended to add scope for other arithmetic operations also.

查看更多
柔情千种
6楼-- · 2019-01-01 10:22

Use the $(( )) arithmetic expansion.

num=$(( $num + $metab ))

See http://tldp.org/LDP/abs/html/arithexp.html for more information.

查看更多
泪湿衣
7楼-- · 2019-01-01 10:24
 #!/bin/bash
read X
read Y
echo "$(($X+$Y))"
查看更多
登录 后发表回答