2

Usually when writing for loops in bash script, I will write like this:

FILE[1]=/tempA/aaa

FILE[2]=tempB/bbb

for FILES in `ls -1 ${FILE[@]}`
do 
   echo $FILES
done

this will display the FILE depending how many I initialize the FILE because it is in array. I need to create a bash script to copy files from a directory to another directory.

assuming like this:

SOURCE[1]=/tempA/source/aaa

SOURCE[2]=/tempB/source/bbb


DEST[1]=/tempA/dest/

DEST[2]=/tempB/dest/

I need to copy from source[1] to dest[1] also from source[2] to dest[2]. So my question how I need to write the FOR loops? or maybe there are another way to do other than for loops?

Thanks!

1 Answer 1

3

You can use a for loop to iterate over the array:

$ SOURCE=( /tempA/source/aaa /tempB/source/bbb )      # declare SOURCE array
$ DEST=( /tempA/dest /tempB/dest )                    # declare DEST array
$ for i in ${!SOURCE[@]}; do echo "${SOURCE[$i]}" "${DEST[$i]}"; done
/tempA/source/aaa /tempA/dest
/tempB/source/bbb /tempB/dest

Depending upon the operation that needs to be performed, replace echo with the appropriate command. (You might declare arrays in the form mentioned above, thereby obviating the need to declare array elements one-by-one.)

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

1 Comment

thanks a lot for your time to reply. my script already working now by using my own code. In future maybe i can use your way. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.