2012-02-29 46 views
0
#! /bin/bash 


dir=$(find . -type f) 

echo ${dir[0]} 
echo "This is dir[0]" 
echo ${dir[1]} 

我想在當前目錄中的遞歸所有文件添加到一個數組ARR [],但上面的代碼失敗,如何在當前目錄下添加文件到一個數組

[email protected]:~/test/avatar$ ./new.sh 
./daily_burn.sh ./test.sh ./.gitignore ./new.sh 
This is dir[0] 

dir是不此代碼中的數組。什麼是正確的方法?謝謝 !

回答

1
dir=(`find . -type f`) 

echo ${dir[0]} 
echo ${dir[1]} 
+0

第一行應該沒有括號!這是殼的抱怨 - '0403-057在第1行的語法錯誤:'('不是預期的' – 2012-02-29 05:49:44

1
dir=$(find . -type f) 

應該

dir=(`find . -type f`) 
+0

我想你錯過了() – looyao 2012-02-29 03:19:42

+0

@looyao是的!無論如何,你已經回答了.. :) – Kashyap 2012-02-29 03:21:02

1

這裏有你想要的東西小完整的殼體試驗 - 執行安全的地方,例如而在/ TMP:

# Prepare 
rm -rf root 

mkdir root 
mkdir root/1 
touch root/1/a 
touch root/1/b 
#touch root/1/"b with spaces" 
mkdir root/2 
touch root/2/c 
mkdir root/2/3 
touch root/2/3/d 

# Find 
echo --- Find 
find root 

# Test 
echo --- Test 
files=(`find root -type f`) 
echo $files 

# Print whole array 
flen=${#files[*]} 
for ((i=0; i < $flen; i++)); do 
    echo files[$i] = ${files[i]} 
done 

的這個輸出是:

--- Find 
root 
root/1 
root/1/a 
root/1/b 
root/2 
root/2/c 
root/2/3 
root/2/3/d 
--- Test 
root/1/a 
files[0] = root/1/a 
files[1] = root/1/b 
files[2] = root/2/c 
files[3] = root/2/3/d 

在文件然而當心,的位 - 如果通過在該行的前面去除#取消註釋以上註釋的觸摸:

#touch root/1/"b with spaces" 

你會得到如下:

--- Find 
root 
root/1 
root/1/b with spaces 
root/1/a 
root/1/b 
root/2 
root/2/c 
root/2/3 
root/2/3/d 
--- Test 
root/1/b 
files[0] = root/1/b 
files[1] = with 
files[2] = spaces 
files[3] = root/1/a 
files[4] = root/1/b 
files[5] = root/2/c 
files[6] = root/2/3/d 

很明顯,你可以做這樣的事情:

希望這有助於。

相關問題