9

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?

  • 1
    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 Jun 22 '15 at 18:19
6

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
  • Yes, thats right, but I need add to the same loop :) – damekr Jun 22 '15 at 17:43
  • Use two for loops then. First peform your additions, then loop over the result. – PSkocik Jun 22 '15 at 17:45
  • 1
    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 Jun 22 '15 at 17:49
  • becouse in for loop I must check if some file which is copying by this for loop has some content.. – damekr Jun 22 '15 at 17:55
5
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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