1

I am trying to loop through filenames within a directory so I can perform an operation on each.

I am able to loop through just 10 filenames if I use:

var=($(ls directory))
for k in {1..10}
do
    echo ${var[$k]}
done

Which gives me the first 10 filenames in my directory. However, I want to loop through them all.

If I do:

length=($(ls directory -1 | wc -l))

I get the length (for this example, it is 62)

So when I combine everything together:

var=($(ls directory))
length=($(ls directory -1 | wc -l))
for k in {1..$length} 
do
    echo ${var[$k]}
done

I get the error 'syntax error: operand expected (error token is "{1..62}")

Any help to fix this, or a better solution would be greatly appreciated!

1
  • Brace expansion is both powerful and limited. Observe that it happens before any variables are expanded, so any attempt to use {1..$length} is doomed to failure. Commented Apr 22, 2016 at 17:33

2 Answers 2

2

Brace expansion is performed by shell before variable expansion, hence you are getting the error.

You can use:

for k in $(seq 1 "$length")

to get around the problem.


Also what you are doing can be easily done by:

files=( * )
for i in "${files[@]}"; do echo "$i"; done

or even simpler:

printf '%s\n' "${files[@]}"
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you for your help!
1

Why not simply :

for file in *; do
  if [ -f "$file" ]; then
    echo "Do what you want with" "$file"; 
  fi
done

4 Comments

The one problem that neither your answer nor the other answer (as I type) deals with is that ls directory part. Up to a point, using directory/* would work; it would give the names in a usable format (and shopt -s nullglob might be beneficial). However, the ls command would give just file where directory/* would yield directory/file. That can be dealt with (by basename, for example, or with minor caveats ${file##*/}) in the loop.
Added a test to get files.
@JonathanLeffler: Or: (cd directory; for file in *; do ...; done)
@rici: that's probably OK, unless the processing relies on being in the current directory at the start of each processing step, rather than in a distant directory. Problems could relate to commands or files not found that would be found if the cd had not been done Probably OK, but not guaranteed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.