FOR嵌套在bash中的IF内的语法错误。

时间:2014-10-30 13:54:14

标签: bash

我试图让这条管道更灵活。所以说我希望能够根据我是否要分析所有数据来轻松切换for循环运行的次数。

#!/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

这会出错:

$ 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* ]]'

我想知道的是,if和elif / fi之间的代码是否必须是自包含的?或者你可以做我在这里尝试的东西,只需要基于AllCohorts的两种方式之一启动for循环

2 个答案:

答案 0 :(得分:1)

您在done循环结束时遗失for

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

答案 1 :(得分:0)

使用较少外部工具的一些增强功能:

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