0

I have 4 lists of variables like this:

YEAR1="2008 2008 2009"
YEAR2="2008 2009 2009"
MONTH1="11 12 01"
MONTH2="12 01 02"

I want to pipe them through to a Python script in a way that the first items from all 4 lists are input first, then the second items from each list and so on. I believe I need to use a WHILE loop for this, but mine doesn't work. I don't get an error message either.

while read $YEAR1 $YEAR2 $MONTH1 $MONTH2;do
    python python-code.py "$YEAR1" "$MONTH1" "$YEAR2" "$MONTH2"
done

My Python script is tested and works, I'm just not getting my head around bash scripting.

0

2 Answers 2

3

Use arrays instead:

#! /bin/bash
YEAR1=(2008 2008 2009)
YEAR2=(2008 2009 2009)
MONTH1=(11 12 01)
MONTH2=(12 01 02)

for (( i=0 ; i < ${#YEAR1[@]} ; ++i )) ; do
    python python-code.py ${YEAR1[i]} ${YEAR2[i]} ${MONTH1[i]} ${MONTH2[i]}
done
Sign up to request clarification or add additional context in comments.

Comments

0

Here's another solution that works with any number of columns/fields…

# Any number of values works
YEAR1="2008 2008 2009 2010 2011"
YEAR2="2008 2009 2009 2011 20012"
MONTH1="11 12 01 09 03"
MONTH2="12 01 02 06 07"


NUM_COLS=5

for i in $(seq 1 $NUM_COLS)  # iterate each column/field
do
  # Dynamically set field specifiers y1, y2, m1, m2
  y1=$i y2=$((i+NUM_COLS)) m1=$((i+NUM_COLS*2)) m2=$((i+NUM_COLS*3))

  # Select the 4 fields, passing in concatenated data  on one line
  cut -d ' ' -f $y1,$y2,$m1,$m2 <<< "${YEAR1} ${YEAR2} ${MONTH1} ${MONTH2}"
done

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.