bash脚本:如何在for循环中使用嵌套if

时间:2011-02-02 21:58:33

标签: bash scripting

#! /bin/bash

count=1
step=(a b)

for x in 0 1
do
    if [[ $count != '0' ]]; then
        if [[ ${step[x]} = "a"]]; then
            echo "Python test ($count)"
        else
            echo "stress test"
        fi
    fi
done

我收到以下错误

syntax error in conditional expression: unexpected token `;'
line 20: syntax error near `;
line 20: `        if [[ ${step[x]} = "a"]]; then'

为什么?

2 个答案:

答案 0 :(得分:5)

"a"]]中的if之间需要一个空格。

从技术上讲,[[]]必须是单独的标记,而bash的解析器不会在引号或大多数标点符号上分隔标记。

我相信该行的原始代码等同于if [[ ${step[x]} = "a]]"; then,如果这会使问题更加明显。

答案 1 :(得分:1)

更改

if [[ ${step[x]} = "a"]]; then

if [[ ${step[$x]} = "a" ]]; then

即。 使用$x代替x在最后一个参数后添加一些空格。

更新:您不需要在数组下标中使用$符号的变量前面(也在双括号(( ))内或let关键字后面)。

相关问题