user3344382
user3344382

Reputation: 1991

long number most significant bit chopped off in shell script

I am assigning a long value to my variable in shell script and trying to do some calculations with it, however I get the results with negative sign numbers.

    count=4
    initial_value=128
    final_value=18446744073709547520
    step=$((($final_value - $initial_value) / ($count - 1)))
    value=$initial_value
    for((i=1; i<=count; i++))
    do
    START=`date +%s`
    myvariable=$(mysql $database -u $user -se "SET GLOBAL join_buffer_size = $value;query to run")
    END=`date +%s`
    TIME=`echo "$END - $START" | bc`
    echo "$value $TIME" >> output.txt
    value=$(($value+$step))
    mysqld restart
    done

the output of my output.txt file is this:

    128 20
    -1280 20
    -2688 21
    -4096 20

I can't tell the shell script to use unsigned long, so that it didn't chop off the number. How can I fix it? Thanks

Upvotes: 0

Views: 116

Answers (1)

Josh Jolly
Josh Jolly

Reputation: 11796

Your $final_value is larger than the max int for bash arithmetic (which is 9223372036854775807). Use bc instead:

count=4
initial_value=128
final_value=18446744073709547520
step=$(echo "($final_value - $initial_value) / ($count - 1)")
value=$initial_value
for((i=1; i<=count; i++))
do
START=$(date +%s)
myvariable=$(mysql $database -u $user -se "SET GLOBAL join_buffer_size = $value;query to run")
END=$(date +%s)
TIME=$(echo "$END - $START" | bc)
echo "$value $TIME" >> output.txt
value=$(echo "$value+$step" | bc)
mysqld restart
done

Sample output (removed the mysql commands from my copy):

128 0
6148914691236515925 0
12297829382473031722 0
18446744073709547519 0

Upvotes: 2

Related Questions