answer=$(echo $(( length / 1024 )) | bc -l)
so length is a variable which has a value like 2402267538.
and it needs to be divided by 1024
.
executing this throws this error
")syntax error: invalid arithmetic operator (error token is "
answer=$(echo $(( length / 1024 )) | bc -l)
so length is a variable which has a value like 2402267538.
and it needs to be divided by 1024
.
executing this throws this error
")syntax error: invalid arithmetic operator (error token is "
When you do:
echo $(( length / 1024 )) | bc -l
You've already lost the part after decimal point before bc -l
as $(( length / 1024 ))
performs integer division.
You can use bc -l
like this:
length="2402267538"
answer=$(bc -l <<<"scale=2; $length / 1024")
echo "$answer"
2345964.39
Little more verbose using awk
:
answer=$(awk -v len=$length 'BEGIN{printf "%.2f\n", len/1024}')
echo "$answer"
2345964.39
Or this:
answer=$(awk -v len=$length 'BEGIN{printf "%d\n", len/1024}')
echo "$answer"
2345964
Switching to ksh
would simplify the task:
$ length=2402267538
$ answer=$((length/1024.00))
$ echo $answer
2345964.392578125
One way with awk:
$ answer=$(awk "BEGIN{printf(\"%f\n\",$length/1024);}")
$ echo $answer
2345964.392578
If you only need the integer part of the result (works with both bash
and ksh
):
$ answer=$((length/1024))
$ echo $answer
2345964
If your length variable is a floating point number, you can trim it that way:
$ length=2402267538.12
$ ilength=${length%%.*}
$ answer=$((ilength/1024))
$ echo $answer
2345964