2

I need to use 2 variables with for condition. For example,

cat days
01072017
02072017
03072017

cat hours
00:00
01:00
02:00
03:00

my shell script sample

 for i in `cat days` & j in `cat hours`
    do
    cat file | grep $i $j >data-$i-$j
    done

I want an output of 3 days * 4hours = 12 files redirected with corresponding data-day-hour

  • see mywiki.wooledge.org/BashFAQ/001 on reading files in bash... add few lines of file to question... you probably want to quote $i $j inside double quotes.. – Sundeep Jul 10 '17 at 11:08
  • If I'm reading your comment correctly you want nested loops, not a lock-step single loop through both files ? – Jeff Schaller Jul 10 '17 at 11:18
1

You need to use a nested for loop

   for i in `cat days` 
      do 
        for j in `cat hours`
        do
        cat file | grep  "$i $j"  >data-${i}-${j}
      done
    done
3

The standard solution for such problem is to make two loops:

for i in $(<days); do
     for j in $(<hours); do
           grep "$i $j" file > data-"$i-$j"
     done
done

Notice that I changed backticks to $() for command substitution, eliminated dead cats, and added double quotes.

1

You can use this one-liner command to run multiloop , for example you have to restart service on different hosts with different service parameters "i" is for host id and "j " is for service name parameter

for i in 1 2 3 4;do  ssh host$i 'for j in A B C D; do sudo systemctl restart service_$j; done'; done

Note: you must change the "i" and "j" values to your requirements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.