2010-02-28 18 views
5

我想讓我的腳本定義一個空數組。如果預定義條件成立,則應添加數組值。爲此我做了什麼執行這個腳本我得到了一些錯誤,如時是如何操作shell腳本中的數組

declare -a FILES 
file_count=0 
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then 
     echo "$file_ext is not supported for this task." 
else 
     $FILES[$file_count] = $filename 
     file_count=$file_count+1 
fi 

linux-softwares/launchers/join_files.sh: 51: [0]: not found 
+0

要進一步閱讀bash數組,請查看http://tldp.org/LDP /abs/html/arrays.html – 2010-02-28 20:32:48

回答

3

當陣列設置數據不與$回憶:

declare -a FILES 
file_count=0 
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then 
     echo "$file_ext is not supported for this task." 
else 
     FILES[$file_count]=$filename 
     file_count=$file_count+1 
fi 

沒有$的文件。


這個工作對我來說:

#!/bin/bash 
declare -a FILES 
file_count=0 

file_ext='jpg' 
SUPPORTED_FILE_TYPE='jpg' 
filename='test.jpg' 

if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then 
     echo "$file_ext is not supported for this task." 
else 
     FILES[$file_count]=$filename 
     file_count=$(($file_count+1)) 
fi 

正如你看到的,稍加修改$(())的數學運算,但文件assignements是一樣的...


經過大量測試後指出,Ubuntu默認shell似乎是破折號,這就引發了錯誤。

+0

嗨富,刪除後,我得到 linux軟件/啓動器/ join_files.sh:51:文件[0]:找不到 這是什麼? – 2010-02-28 20:37:07

+1

還記得你幾分鐘前的問題嗎?空間傷害:)只刪除FILES [$ file_count] – 2010-02-28 20:42:10

+0

ohh yes後的空格。抱歉失去了病變。 :) – 2010-02-28 20:48:19

0

你可以用這種方式以及

declare -a FILES 
file_count=0 
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then 
     echo "$file_ext is not supported for this task." 
else 
     FILES[((file_count++))]=$filename 
fi 

把它寫:維傑

微小的示範,列表*目錄txt文件,並把數組FILES

declare -a FILES 
i=0 
for file in *.txt 
do 
    FILES[((i++))]=$file 
done 
# display the array 
for((o=0;o<${#FILES};o++)) 
do 
    echo ${FILES[$o]} $o 
done 

輸出

$ ./shell.sh 
A.txt 0 
B.txt 1 
file1.txt 2 
file2.txt 3 
file3.txt 4 
+0

這不起作用。錯誤消息是「files.sh:39:語法錯誤:」(「unexpected(expected)」)「 – 2010-03-01 06:40:15

+0

變量FILES中有一個額外的」$「。去掉它。 – ghostdog74 2010-03-01 07:01:07

+0

我沒有得到任何$這是哪裏? – 2010-03-01 07:18:10

1

要在數組末尾添加元素,請使用+ =運算符(自2004年bash 3.1以來):

files+=("$file")