Zul146
Zul146

Reputation: 21

How to create for loops in bash script?

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!

Upvotes: 2

Views: 233

Answers (1)

devnull
devnull

Reputation: 123448

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.)

Upvotes: 3

Related Questions