2

I have a trivial for loop in a bash script which is not working and I cannot see what is wrong.

#!/bin/bash
function deleteOut {

for index in {0..$1}
do
    echo "/bin/rm -rf ./OUT/Message_${index}.log"
    /bin/rm -rf ./OUT/Message_${index}.log
done
}

and called it using

deleteOut 5

I was expecting a loop like

    /bin/rm -rf ./OUT/Message_0.log
    /bin/rm -rf ./OUT/Message_1.log
    /bin/rm -rf ./OUT/Message_2.log
    /bin/rm -rf ./OUT/Message_3.log
    /bin/rm -rf ./OUT/Message_4.log
    /bin/rm -rf ./OUT/Message_5.log

Instead I got

/bin/rm -rf ./OUT/Message_{0..5}.log 

I've solved the problem doing something like this instead

find ./OUT -name "Message_*.log" | xargs /bin/rm 

but this is not the point. Why my first approach didn't work?

2 Answers 2

2

Use eval or subshell

Brace expansion comes before variable expansion

 for index in $(eval "echo {0..$q}")
 do 
     echo $index
 done
Sign up to request clarification or add additional context in comments.

Comments

1

You can use seq, which is in general safer than eval:

for index in $(seq $1)

Or even faster without any external program:

for ((index=1; index<=$1; index++))

2 Comments

The second command would be correct if index=0. The first command is not usable because the range was 0..$1 and seq (as far as I know) start with 1. But actually you are answering how to loop over the files whereas my question is about the parameter expansion in the range. The answer from "sehe" is the correct one: "Brace expansion comes before variable expansion" (I didn't know it). Anyway, thanks for your answer.
The link explains the expansion issue and links to more information.

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.