简体   繁体   中英

Syntax error with FOR nested inside IF in bash.

Im trying to make this pipeline more flexible. So say I want to be able to easily switch the number of times a for loop is run, based on whether or not I want to analyse all my data.

#!/bin/bash
#AllCohorts='Yes'
AllCohorts='NotAll'
groups=$(wc -l Groups | awk '{print $1}' ) 

if [[ $AllCohorts == *Yes* ]]
then
    for pheno in `seq 1 $groups`; 
    do
    out=$(sed -n "$pheno"'p' Groups) 
    whichPheno=$pheno
elif [[ $AllCohorts == *Not* ]]
then
    nbGroups=$(wc -l TestingGroups | awk '{print$1}')
    for pheno in `seq 1 $nbGroups`; 
    do
    out=$(sed -n "$pheno"'p' Groups) 
    hit=$(grep -n $out TestingGroups) 
    whichPheno=${hit%:*} 
fi

This gives an error:

$ sh run_gene_tests.sh
run_gene_tests.sh: line 29: syntax error near unexpected token `elif'
run_gene_tests.sh: line 29: `elif [[ $AllCohorts == *Not* ]]'

What Im wondering is, does the code you have in between the if and elif/fi have to be self contained? or can you do what im trying here and just have the for loop starting in one of two ways based on AllCohorts

You're missing done at the end of the for loops

if [[ $AllCohorts == *Yes* ]]
then
    for pheno in `seq 1 $groups`; 
    do
        out=$(sed -n "$pheno"'p' Groups) 
        whichPheno=$pheno
    done
elif [[ $AllCohorts == *Not* ]]
then
    nbGroups=$(wc -l TestingGroups | awk '{print$1}')
    for pheno in `seq 1 $nbGroups`; 
    do
        out=$(sed -n "$pheno"'p' Groups) 
        hit=$(grep -n $out TestingGroups) 
        whichPheno=${hit%:*} 
    done
fi

Some enhancements using less external tools:

readarray grouptab < Groups || exit 1

if [[ "$AllCohorts" == *Yes* ]]; then
    for ((pheno=1;pheno <= groups; pheno++)); do     # use for loop
        out=${grouptab[pheno+1]}                     # avoid sed
        whichPheno=$pheno
    done
elif [[ "$AllCohorts" == *Not* ]]; then
    nbGroups=$(wc -l < TestingGroups)                # avoid awk using <
    for ((pheno=1;pheno <= nbGroups; pheno++)); do   # use for loop
        out=${grouptab[pheno+1]}                     # avoid sed
        hit=$(grep -n "$out" TestingGroups) 
        whichPheno=${hit%:*} 
    done
fi

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