PythonNoob28
PythonNoob28

Reputation: 23

Loop two variables through one command in shell

I want to run a shell script that can simultaneously loop through two variables. So that I can have an input and output file name. I feel like this isn't too hard of a concept but any help is appreciated.

Files = "File1,
         File2,
         ...
         FileN
         "

Output = OutFile1,
         Outfile2,
         ...
         OutfileN
         "

and I would in theory my code would be:

for File in $Files
do
    COMMAND --file $File --ouput $Output        
done

Obviously, there needs to be another loop but I'm stuck, any help is appreciated.

Upvotes: 2

Views: 714

Answers (2)

conanforever22
conanforever22

Reputation: 1

zsh enables multiple loop variables before the list.

#!/bin/zsh
input2output=(
    'File1' 'Outfile1'
    'File2' 'Outfile2'
)

for input ouput in $input2output
do
    echo "[$input] -->  [$ouput]"
done

quotes from zsh(5.9) manual or man zshmisc

for name ... [ in word ... ] term do list done

More than one parameter name can appear before the list of words. If N names are given, then on each execution of the loop the next N words are assigned to the corresponding parameters. If there are more names than remaining words, the remaining parameters are each set to the empty string.

Upvotes: 0

anubhava
anubhava

Reputation: 785196

You don't really need to loop 2 variables, just use 2 BASH arrays:

input=("File1" "File2" "File3")
output=("OutFile1" "OutFile2" "OutFile3")

for ((i=0; i<${#input[@]}; i++)); do
   echo "Processing input=${input[$i]} and output=${output[$i]}"
done

Upvotes: 3

Related Questions