Reputation:
I want to subtract a list of values from a number.
I tried:
DATACOME=1013
DATAREF=1010
1020
var=$((DATACOME - DATAREF))
echo "$var"
3
It works just for the first value in $DATAREF
and outputs 3
instead of:
echo "$var"
3
-7
Upvotes: 0
Views: 672
Reputation: 7509
Straightforward approach is to save the list of values as an array dataref
and then iterate over it with a for
loop:
datacome=1013
dataref=(1010 1020)
for num in "${dataref[@]}"; do
echo $((datacome - num))
done
If you don't want to use arrays, you can store your values in a string separated by whitespace characters and use awk
:
datacome=1013
dataref="1010 1020"
awk -v num="$datacome" '{
for (i = 1; i <= NF; i++) {
print num-$i
}
}' <<< "$dataref"
Or again with a for
loop using word-splitting this time:
datacome=1013
dataref="1010
1020"
for num in $dataref; do
echo $((datacome - num))
done
Or when using a file to store your values:
#input_file:
#1010
#1020
datacome=1013
while read num; do
echo $((datacome - num))
done < input_file
awk -v num="$datacome" '{
for(i = 1; i <= NF; i++) {
print num-$i
}
}' < input_file
EDIT: on @dawg's recommendation, this is one of many possible ways to do this with bc
:
datacome=1013
dataref="1010 1020"
for num in $dataref; do
echo "$num-$datacome"
done | bc -l
There really are a lot of ways to do this. Also, please do not use uppercase variables as they could collide with environment and internal shell variables.
Upvotes: 1