12

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 etcbinvar (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: etcbinvarsbin (of course on separate lines).

This is not working. How can I do it?

1
  • 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 senseCommentedJun 22, 2015 at 18:19

2 Answers 2

7

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

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.