0

I would like to run a for loop in bash where end index is result of a command

#!/bin/bash
# Basic range in for loop
for value in {0..$(ls | wc -l)}   
do
echo $value
done

But when I run it I see:

{0..14}
2
  • 2
    Brace expansion happens before variable does in bash. that wont work. That question has been asked and answered many-many times in this forum. Use a cstyle for-loop. Commented May 18, 2020 at 12:26
  • Further, ls | wc -l is not a robust way to get (presumably) the number of files in a directory. Commented May 18, 2020 at 12:48

1 Answer 1

1

you can use eval :

for value in $(eval echo {0..$(ls | wc -l)})   
do
echo $value
done

seq is similar to bash's braces, The key advantage of seq is that its arguments can include not just arithmetic expressions, as shown above, but also shell variables

for value in $(seq 1 `ls | wc -l`);
do
    echo ${value}
done

By contrast, the brace notation will accept neither.

seq is a GNU utility and is available on all linux systems as well as recent versions of OSX. Older BSD systems can use a similar utility called jot.

C-Style- pretty and simple :

for ((value = 1 ; value <= $(ls | wc -l) ; value++)); do
  echo ${value}
done
Sign up to request clarification or add additional context in comments.

Comments

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.