0
#! /bin/bash


dir=$(find . -type f)

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

I want to add all the files recursively in the current dir into an array arr[], but above code fails,

zhangyf@zhangyf-desktop:~/test/avatar$ ./new.sh 
./daily_burn.sh ./test.sh ./.gitignore ./new.sh 
This is dir[0]

dir is not an array in this code. What is the correct way ? Thanks !

Yifan Zhang
  • 1,461
  • 3
  • 12
  • 19

3 Answers3

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

echo ${dir[0]}
echo ${dir[1]}
xda1001
  • 2,449
  • 16
  • 18
  • There should be no brackets in the first line! This is what the shell complains-`0403-057 Syntax error at line 1 : `(' is not expected` – Pavan Manjunath Feb 29 '12 at 05:49
1
dir=$(find . -type f)

should be

dir=(`find . -type f`)
Kashyap
  • 15,354
  • 13
  • 64
  • 103
1

Here's a small complete shell test for what you want - execute it somewhere safe, e.g. while in /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

The output of this is:

--- 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

Beware, however, of spaces in file - if you uncomment the commented touch above by removing # in front of this line:

#touch root/1/"b with spaces"

you will get the following:

--- 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

Obviously, you can do something like this:

Hope this helps.

Community
  • 1
  • 1
icyrock.com
  • 27,952
  • 4
  • 66
  • 85