Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a problem with for loop in bash. For example: I have an array ("etc" "bin" "var"). And I iterate on this array. But in the loop I would like append some value to the array. E.g.

array=("etc" "bin" "var")
for i in "${array[@]}"
do
echo $i
done

This displays etc bin var (of course on separate lines). And if I append after do like that:

array=("etc" "bin" "var")
for i in "${array[@]}"
do
array+=("sbin")
echo $i
done

I want: etc bin var sbin (of course on separate lines).

This is not working. How can I do it?

share|improve this question
    
Altering the thing you're iterating over is always a risky proposition. It's often a good time to step back and consider if there's another approach that might make sense –  Eric Renouf 20 hours ago

2 Answers 2

up vote 3 down vote accepted

It will append "sbin" 3 times as it should, but it won't iterate over the newly added "sbin"s in the same loop.

After the 2nd example:

echo "${array[@]}"
#=> etc bin var sbin sbin sbin
share|improve this answer
    
Yes, thats right, but I need add to the same loop :) –  damekr 21 hours ago
    
Use two for loops then. First peform your additions, then loop over the result. –  PSkocik 21 hours ago
    
I don't see why you'd want to append sbin in the loop though. Appending it just once kind of makes more sense: array+=(sbin); for i in ... –  PSkocik 21 hours ago
    
becouse in for loop I must check if some file which is copying by this for loop has some content.. –  damekr 21 hours ago
set etc bin var
while [ "$#" -gt 1 ]
do    [ "$1" = bin ] &&
      set "$@" sbin
      printf %s\\n "$1"
shift;done 

That will iterate over your list, tack sbin onto the end of said list conditionally, and include sbin in the iterable content.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.