Bash If语句无法运行

问题描述 投票:-1回答:1

我正试图在bash中编写一个简单的嵌套if函数;成为新手并不确定我的语法出了什么问题。

  1. 该脚本旨在接受2个参数或根本不接受。
  2. 如果没有将任何参数传递给脚本,则应该运行名为hero的函数,因此将运行外部的if语句。
  3. 但是如果在这种情况下将参数word传递给字符串options,则它应检查第二个参数是否在名为silent_hero的关联数组中已经存在的位置,并运行函数if [![ -n $1 ]] then hero else [[ $1 == 'word']] then if [![ -n $2 ] && [ ${!options[*]} =~ (^|[[:space:]])$2($|[[:space]])] then silent_hero else echo 'error! exit 129 fi fi
if [![ -n $1 ]]
then
        echo "True"
fi
bash syntax
1个回答
0
投票

您已选择了最困难的脚本编写方式:从上到下编写,然后同时调试所有语法问题。

如果一次写一行或更少一行,然后保存,运行并在添加下一行之前验证它是否可以按预期工作,那么您将容易得多。

如果您这样做了,您可能已经到了这里,发现这会产生错误,而不是检查字符串是否为空:

How to find whether or not a variable is empty in Bash

现在代替“如何检查第一个参数是否为空,然后与另一个单词匹配,然后查看第二个参数是否为空以及数组中的键,您可以问/研究一个简单得多的问题” [[ C0]“。

无论如何,这是带注释的脚本的固定版本:

# Make sure variables are defined
declare -A options=([foo]=1 [bar]=1)

# ! must be inside [[ .. ]]
if [[ ! -n $1 ]]
then
        hero
# Use `elif` for additional conditions
# Need space before ]]
elif [[ $1 == 'word' ]]
then
        # ! must be inside [[ ]], but you probably didn't even want it here
        # don't use [..] as parentheses
        # Missing ending : in [[:space]]
        if [[ -n $2 && ${!options[*]} =~ (^|[[:space:]])$2($|[[:space:]]) ]]
        then
                silent_hero

        else
                # add missing trailing quote
                echo 'error!'
                exit 129
        fi
fi

这是击中每个分支的示例:

$ bash myscript
myscript: line 7: hero: command not found
$ bash myscript word foo
myscript: line 17: silent_hero: command not found
$ bash myscript word unknown
error!
© www.soinside.com 2019 - 2024. All rights reserved.