简体   繁体   中英

Nested for loop in unix shell script

I am creating the shell script that will take two condition first it will get all file name in and insert one by one in html field other for loop will get the count and it will used for auto increment in serial number.

I have written code like this

cnt=`find /optware/oracle/logs/20190311_JAVA/TEMP/  -type f | wc -l`
    for ((i in `ls -l /optware/oracle/logs/20190311_JAVA/TEMP/|grep -v ^$|awk '{print $9}` && a=1; a <= $cnt ; a++)) 
    do
    echo "  <tr> $a <td></td><td>$i</td></tr>" >>Temp.lst
    done

I am getting error as && a=1: arithmetic syntax error

Kindly help me with this issue.

The ((...)) should contain three arithmetic expressions. in is not an arithmetic operator. In fact, it's unclear what you're trying to achieve.

To nest two loops, specify each one with its own for :

for i in `ls -l /optware/oracle/logs/20190311_JAVA/TEMP/|grep -v ^$|awk '{print $9}` ; do
    for (( a = 1 ; a <= cnt ; a++ )) ; do
        echo "$i:$a"
    done
done

If you just need a counter, there's no need for the second loop:

a=1;
for i in `ls -l /optware/oracle/logs/20190311_JAVA/TEMP/|grep -v ^$|awk '{print $9}` ; do
    echo "$i:$a"
    (( ++a ))
done

You can't loop over an index+value pair directly in Bash. I would write this code as follows:

index=0
for path in /optware/oracle/logs/20190311_JAVA/TEMP/*
do
    echo "  <tr>${index}<td></td><td>${path}</td></tr>" >> Temp.lst
    ((++index))
done

You're mixing up two looping constructs . You can use either one, but not both together.

for name [ [in [words …] ] ; ] do commands; done

and

for (( expr1 ; expr2 ; expr3 )) ; do commands ; 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