简体   繁体   中英

Bash - Multiple conditions in a for loop

I'm trying to do a for loop with multiple conditions and I didn't find any information about how to do it on the web

I'm sorry for the stupid questions, but I just started programming in linux

what am I doing wrong here?

    #!/bin/bash

j=0

for line in `cat .temp_` || j in `seq 0 19`
do
    ...

done

the error says wrong syntax and that I can't use ||

Thanks a lot

for line in `cat .temp_`
do
    if ! grep -Fxq $line $dictionary && [ $j -lt 20 ]
    then
        echo $line >> $dictionary
        j=$((j+1))
    fi
    [ $j -gt 20 ] && break
done

You can't check a condition in a for loop in shell. You must do it in a extra statement. In this case so:

[ $j -gt 20 ] && break

Another solution, without break :

while read line && [ $j -lt 20 ]
do
    if ! grep -Fxq $line $dictionary && [ $j -lt 20 ]
    then
        echo $line >> $dictionary
        j=$((j+1))
    fi
done < .temp_

You are trying to combine two different styles of for -loops into one. Instead, just break if the value of j becomes too large:

j=0
while read -r line; do
    [[ j >= 20 ]] && break
    ...
done < ._temp

(This, by the way, is the preferred way to iterate over a file in bash. Using a for -loop runs into problems if the file is too large, as you essentially building a command line using the entire contents of the file.)

[UPDATE: the following is based on my conjecture as to the purpose of the loop. See Calculate Word occurrences from file in bash for the real context.]

Actually, you can dispense with the loop. You are looking for at most 20 lines from .temp_ that do not already appear in the file whose name is in dictionary, right?

sort -u .temp_ | grep -f $dictionary -Fx -v -m 20 >> $dictionary

This will call grep just once, instead of once per line in .temp_ .

A simple nested for-loop?

for line in `cat file`; do for j in {0..19}; do
     your_commands
done; done

If I understand you correctly (you want to run a command on every line 20 times).

Once I need to process all files inside a directory, but only until nth file or until all is processed:

count=1
nth=10
for f in folder/*; do
  ((count++))
  # process $f
  if [[ $count -gt $nth ]] 
  then
    break
  fi
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM