1

So the following works to wrap the for loop and print out something for each item:

iterate() {
  local array=$1

  shift

  for i in $array; do
    $*
  done
}

iteratecallback() {
  echo item: $i
}

data=$(ls)
iterate "$data" iteratecallback

But what I would like to do is take the echo item: $i and make i into echo item: $position for top level, then index for next level nesting, then i for third level nesting, for example. Basically, be able to arbitrarily name these index variables while passing them into the wrapping function.

So for example, something like this:

iterate() {
  local customname=$1
  local array=$2

  shift

  for $customname in $array; do
    $*
  done
}

iteratecallback() {
  echo item: $position

  data2=$(ls)
  iterate index "$data2" iteratecallback2
}

iteratecallback2() {
  echo item: $index in $position
}

data=$(ls)
iterate position "$data" iteratecallback

Wondering how to do such a thing in Bash.

  • 2
    Note that you're not passing an array, you are passing a string that contains newlines. The for loop iterates over the words in that string, so if you have a filename that contains a space, you're not doing what you think you are. – glenn jackman Mar 27 at 16:23
  • 1
    You'll want to investigate "nameref" in the bash manual to truly reference a variable in the calling scope. – glenn jackman Mar 27 at 16:24

Your Answer

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

Browse other questions tagged or ask your own question.