问题
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
回答1:
For integers:
Use arithmetic expansion:
$((EXPR))
num=$((num1 + num2)) num=$(($num1 + $num2)) # also works num=$((num1 + 2 + 3)) # ... num=$[num1+num2] # old, deprecated arithmetic expression syntax
Using the external
expr
utility. Note that this is only needed for really old systems.num=`expr $num1 + $num2` # whitespace for expr is important
For floating point:
Bash doesn't directly support this, but there's a couple of external tools you can use:
num=$(awk "BEGIN {print $num1+$num2; exit}")
num=$(python -c "print $num1+$num2")
num=$(perl -e "print $num1+$num2")
num=$(echo $num1 + $num2 | bc) # whitespace for echo is important
You can also use scientific notation (e.g.: 2.5e+2
)
Common pitfalls:
When setting a variable, you cannot have whitespace on either side of
=
, otherwise it will force the shell to interpret the first word as the name of the application to run (eg:num=
ornum
)num= 1
num =2
bc
andexpr
expect each number and operator as a separate argument, so whitespace is important. They cannot process arguments like3+
+4
.num=`expr $num1+ $num2`
回答2:
Use the $(( ))
arithmetic expansion.
num=$(( $num + $metab ))
See http://tldp.org/LDP/abs/html/arithexp.html for more information.
回答3:
There are a thousand and one ways to do it. Here's one using dc
:
dc <<<"$num1 $num2 + p"
But if that's too bash-y for you (or portability matters) you could say
echo $num1 $num2 + p | dc
But maybe you're one of those people who thinks RPN is icky and weird; don't worry! bc
is here for you:
bc <<< "$num1 + $num2"
echo $num1 + $num2 | bc
That said, there are a some unrelated improvements you could be making to your script
#!/bin/bash
num=0
metab=0
for ((i=1; i<=2; i++)); do
for j in output-$i-* ; do # for can glob directly, no need to ls
echo "$j"
# grep can read files, no need to use cat
metab=$(grep EndBuffer "$j" | awk '{sum+=$2} END { print sum/120}')
num=$(( $num + $metab ))
done
echo "$num"
done
EDIT:
As described in BASH FAQ 022, bash does not natively support floating point numbers. If you need to sum floating point numbers the use of an external tool (like bc
or dc
) is required.
In this case the solution would be
num=$(dc <<<"$num $metab + p")
To add accumulate possibly-floating-point numbers into num
.
回答4:
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
回答5:
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;
回答6:
I really like this method as well, less clutter:
count=$[count+1]
回答7:
#!/bin/bash
read X
read Y
echo "$(($X+$Y))"
回答8:
You should declare metab as integer and then use arithmetic evaluation
declare -i metab num
...
num+=metab
...
For more information see https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic
回答9:
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.
回答10:
#!/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)
let num=num+metab (line 16)
done
echo "$num"
done
来源:https://stackoverflow.com/questions/6348902/how-can-i-add-numbers-in-a-bash-script