2013-05-01 70 views
1

我試圖寫一個簡單的bash腳本,將整數和供應的總和。我想最簡單的方法是將輸入分配給一個數組。然後遍歷數組以執行求和。我需要使用數組的長度在我的for循環,不能弄清楚如何數組長度分配給一個變量。如何數組長度分配給一個變量在bash

讚賞這個簡單的腳本任何幫助(我做到了學習bash)的

#!/bin/bash 
# add1 : adding user supplied ints 

echo -n "Please enter any number of integers: " 
read -a input 

echo "Your input is ${input[*]}" 
echo "${#input[@]} number of elements" 

num = ${#input[@]} # causing error 
for ((i = 0; i < "${num}"; ++i)); do # causing error 
    sum = $((sum + input[$i])) 
done 

echo "The sum of your input is $sum" 

其產生的錯誤:

line 10: num: command not found 
line 11: ((: i < :syntax error: operand expected (error token is "< ") 
+1

[下面是詳細信息](http://tldp.org/LDP/abs/html/varassignment.html)上分配CON在擊:) – summea 2013-05-01 18:10:23

+0

ventions你說「導致錯誤」;知道它造成了什麼錯誤會很有幫助。 – msw 2013-05-01 18:16:39

+0

@msw - 已經解決了。感謝您的反饋。錯誤是: 線10民:未找到命令 線11:((:I <:語法錯誤:操作數預期(錯誤令牌「<」) – ZenStunna 2013-05-01 18:37:31

回答

7

你只是有一個語法錯誤。 =之前刪除空格:

num = ${#input[@]} # causing error 

變爲:

num=${#input[@]} # works 

請注意,如果您使用=運營商分配給一個變量在bash,必須不存在前後=

是任何空間

this entry about Variable Assignment in the Advanced Bash-Scripting Guide

+0

謝謝。它的工作原理,我整個程序有同樣的錯誤。我覺得自己像個白癡。由C++即將在那裏那個空間也無所謂...... – ZenStunna 2013-05-01 18:18:34

+0

不擔心這一點。每一個慶典編碼器曾經看到過這個錯誤;) – hek2mgl 2013-05-01 18:19:32