2

I am trying to compile a big project, which involves me going to different directories and compiling things there. I have three arrays, all of them contain commands, first array contains directory traversal, second array contains compile commands, and third array contains error messages.

I set up my arrays like so

task[0]="cd vssl/make/; make clean;"
compile[0]="make all"
error[0]="echo \"We failed at vssl install\""

task[1]="cd ../../web/make/; make clean;"
compile[1]="make install"
error[1]="echo \"We failed at web install\""

Now I need a for loop that will work like this

for i in {0..$size_of_array}
do
    eval ${task[$i]}
    if (eval ${compile[$i]}); then
        echo "Done"
    else
        eval ${error[$i]}
        break
    fi
done

I have tried a lot of things, and not sure how to achieve it. for i in "${task[@]}" doesn't work for me either because I have three variables. Would anyone have any insight on how to get around this?

Thanks to anyone who can help. :)

3 Answers 3

4

The size of the task array is ${#task[@]} (lovely syntax, eh?). So you can start your loop as

for ((i=0; i<${#task[@]}; ++i))

See the for command and the section on ARITHMETIC EVALUATION in bash(1) for details.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so very much, this is exactly what I wanted!!! Works perfectly too. Thank you!
Nice one! All of these are explained in the "Parameter Expansion" section of bash(1).
3

You can compute $i as you go:

i=0
for cmd in "${task[@]}"; do
  eval $cmd
  if (eval ${compile[$i]}); then
    echo "Done"
  else
    eval ${error[$i]}
    break
  fi
  i=`expr $i + 1`
done

2 Comments

I was afraid you would say that because I wanted a nice looking for loop to do my things for me. But thank you very much, this has worked quite nicely.
@AndrewSchulman 's answer looks good too; I'll confess I was unaware that you could wrote for-loops like those in bash.
0

Why in the world do you have three arrays? Shell is not so great for programming, but it is great for running commands, which is what you seem to be doing here. So, just do that:

set -ex
make -C vssl/make clean all
make -C ../../web/make/ clean install
...

Not fancy enough? OK:

die() { echo "$*" >&2; exit 1; }
run() { "$@" || die "Failed (exit $?) at $*"; }
run make -C vssl/make clean all
run make -C ../../web/make/ clean install

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.