如何在Bash / Ubuntu 12.04中正确编写此算术表达式?

时间:2012-05-03 09:34:08

标签: linux bash shell ubuntu

我无法以某种方式完成这项工作,

(( chunks = $size / $chunk_size + 1 ))
echo $chunks

修改


我也试过了,

chunks = $(( $size / $chunk_size + 1 ))

虽然这有效,

while [ $counter -le 10 ]; do
    echo $counter;
    (( counter++ ))
done

前者给我/ 157286400 + 1 ")syntax error: invalid arithmetic operator (error token is ",错误本身格式不正确。

3 个答案:

答案 0 :(得分:2)

您的$size变量未初始化或其中包含其他非数字字符。

$ chunk_size=157286400
$ unset size
$ (( chunks = $size / $chunk_size + 1 ))
-bash: ((: chunks =  / 157286400 + 1 : syntax error: operand expected (error token is "/ 157286400 + 1 ")
$ size=$'\r'  # carriage return
$ (( chunks = $size / $chunk_size + 1 ))
 / 157286400 + 1 ")syntax error: operand expected (error token is "

您可以通过修改AWK命令来删除回车符:

awk '/^Content-Length:/ { gsub("\015", "", $2); print $2 }'

答案 1 :(得分:0)

确保初始化$ size和$ chunk_size ... 测试:

size=1
chunk_size=2
(( chunks = $size / $chunk_size + 1 ))
echo $chunks

答案 2 :(得分:0)

试试这个:

let size=10
let chunk_size =2
declare -i chunks
let chunks =  $(($size / $($chunk_size + 1))))
echo $chunks