破碎:带有增量计数器的{for}循环中的Elif

时间:2015-08-02 22:25:13

标签: bash for-loop counter conditional-statements

我写了一个简短的脚本来为macintalk中的音节合成生成一个格式化的字符串。我想每20个音节插入一个静音,所以我写了一个for循环,其中一个计数器存储在一个tempfile和一个嵌套的elif语句中,每当计数器达到20时,该语句应该添加一个静音命令。然后计数器在到达后重置20。

出于某种原因,我无法理解,只有在第一次找到条件时才能访问elif。换句话说:第一次计数器达到20时,它会插入静音命令,重置并继续循环。第二次计数器达到20时,不会访问elif并继续增长,直到$ k达到它的最大值。

有没有人知道为什么这段代码不起作用?

编辑**这是一个稍长的摘录,根据流行的请求=)

如果您想尝试重现,以下是文件的链接: syllables_phncode.txt cbsyllindx.txt

# Load Syllables
echo ''
echo 'Opening Syllable Transcription for Victoria'
echo ''
syllfile=./syllables_phncode.txt
syllables=$(cat $syllfile)
syllarray=()
counter=0;
# Create Indexed Array of Phonological Code for Syllables
for k in $syllables
do
    echo $counter
    echo $k
    syllarray[counter]=$k
    counter=$(($counter + 1));
done
# Load syllable index for stimulus stream
indxfile=./cbsyllindx.txt
indx=$(cat $indxfile)
stream=''
tempfile=count.tmp
echo 0 > $tempfile
echo '====================================================================================='
echo 'Counter Balanced Stimulus Order (Indexed by Syllables in Alphabetical Order)'
echo '====================================================================================='
echo $indx
echo '====================================================================================='
echo ''
echo 'Creating counterbalanced stimulus stream string with proper Macintalk formatting'
echo ''
for k in $indx
do
    counter=$[$(cat $tempfile) + 1]
    echo $counter > $tempfile
    if [ $k -eq 0 ]; then
        stream=$stream'@_'${syllarray[k]}
    elif [ $counter -eq 20 ]; then
    echo Adding Silence after syllable: ${syllarray[k]}
        stream=$stream'_'${syllarray[k]}'[[ slnc 20 ]]'
        echo 0 > $tempfile
    else
        stream=$stream'_'${syllarray[k]}
    fi
done
unlink $tempfile
echo '------------------------------------------------------'
echo 'Printing Stream to Screen'
echo '------------------------------------------------------'
echo $stream

以下是此脚本创建的字符串:

  

_tUW_dAE_rOW_pIY_gOW_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IY_bUW_dOW_pAE_pIY_gOW_lAE @ _bIY_kUW_tIY_bUW_dOW_pAE @ _bIY_kUW_tIY_tUW_dAE_rOW_bUW_dOW_pAE_tUW_dAE_rOW_pIY_gOW_lAE @ _bIY_kUW_tIY_tUW_dAE_rOW_pIY_gOW_lAE_bUW_dOW_pAE

1 个答案:

答案 0 :(得分:1)

您的问题是,当$k -eq 0等于$counter时,您点击了20支票,但无论如何都会增加计数器,然后一旦通过20,您就永远无法点击再一次。

您可以通过在脚本顶部添加set -x并运行它并查看输出来查看此内容。

你不希望if / else用于不相关的检查它有这个问题。

你可能想要更像这样的东西作为你的循环体。

if [ $k -eq 0 ]; then
    stream=${stream}@
fi
stream=${stream}_${syllarray[k]}
if [ $counter -eq 20 ]; then
    stream=$stream'[[ slnc 20 ]]'
fi

这使问题分开。

你也没有(如评论中所示)在这里需要tempfile。 (除了那些处理不读数的文件之外,你没有任何子shell。)

您也可以使用$(cat file)来避免$(< file)子广告。

您还应该始终使用$((...))代替$[...]