Shell: how to use 2 variables with for condition
5,951
Solution 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
Solution 2
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.
Solution 3
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
Related videos on Youtube
Author by
RNL
Updated on September 18, 2022Comments
-
RNL over 1 year
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
-
Jeff Schaller almost 7 yearsIf I'm reading your comment correctly you want nested loops, not a lock-step single loop through both files ?
-