为什么$((sum + = i))在bash告诉我"命令未找到"?

时间:2016-09-27 03:56:40

标签: bash scripting

目标是有一个bash脚本,它将从1到N的整数相加,其中N由用户定义。这是我的代码:

#!/bin/bash

read -p "Enter an integer greater than zero: " N  #allows the user to enter a value, which is then read from stdin and assigned to N

sum=0

for ((i=0; i<=N; i++))

do

  $((sum+=i))  #add i to sum each iteration

done

echo "The sum of the numbers from 1 to $N is $sum"

输出:

Enter an integer greater than zero: 5
-bash: 0: command not found
-bash: 1: command not found
-bash: 3: command not found
-bash: 6: command not found
-bash: 10: command not found
-bash: 15: command not found
The sum of the numbers from 1 to 5 is 15

总和是正确的。我意识到每次迭代的总和导致某种错误(b / c 0,1,3,6 ...是每个i的求和值),但我不确定为什么或如何解决它。有没有办法在vi中调试?感谢

2 个答案:

答案 0 :(得分:6)

$放在前面:

((sum+=i))

$(())将进行算术扩展,扩展的结果将被视为运行导致错误消息的命令。

答案 1 :(得分:1)

您可以使用冒号作为该行的第一个字符来避免此问题:

<?php
// get all active memberships for a user; 
// returns an array of active user membership objects
// or null if no memberships are found
$user_id = get_current_user_id();
$args = array( 
    'status' => array( 'active', 'complimentary', 'pending' ),
);  
$active_memberships = wc_memberships_get_user_memberships( $user_id, $args );
if ( ! empty( $active_memberships ) ) {
echo "User is active";
}
?>

或删除: $((sum+=i)) #add i to sum each iteration

$

((sum+=i)) #add i to sum each iteration 的问题在于它有一个输出(没有:)
被解释为要执行的命令(1,3,6 ......等)。

您可以将代码缩减为此较短版本:

$(( ))

或更快(很多):

#!/bin/bash
read -p "Enter an integer greater than zero: " N  

for (( i=0,sum=0 ; i<N ; i++,sum+=i )); do : ; done

echo "The sum of the numbers from 1 to $N is $sum"