Bash和函数

时间:2018-03-07 21:23:06

标签: bash

我要编写一个basg = h脚本,如果输入正确的数字,则会显示一条消息(例如1 =函数f1,2 =函数f2,3 =函数f3)

我的代码如下

 #!/bin/bash

function f1
{
     echo "This message is from function 1"
}

function f2
{
    echo "This messge is from function 2"
}

function f3
{
    echo "This message is from function 3"
}

function=$(typeset -F)

declare -a myarr=(`echo "$function" [sed 's/declare[ ]-f / /g'`)

read -p "Enter a number (1, 2, or 3): " number

if ! [[ "$number" =~ ^[0-9]+$ ]]
    then
        echo "Not a valid number"
        exit
fi

flag=0

for element in "${myarr[@]}
do

    if echo "$element" | grep -q "$num"; then
        $element

        flag=1
    fi
done

if [ "$flag" -eq 0 ]; then
echo "No function matches number $num"
fi

现在,当我运行代码时,我获得了错误

  

q6:第43行:在寻找匹配的“"'

时出现意外的EOF      

q6:第45行:语法错误:意外的文件结尾

任何帮助来源错误?

1 个答案:

答案 0 :(得分:1)

for element in "${myarr[@]}

缺少最终报价。您可以通过查看语法突出显示的位置来捕获这样的错误。请注意此行后面的脚本有多少红色错误?

更好的是,您可以使用ShellCheck

Line 32:
for element in "${myarr[@]}
^-- SC1009: The mentioned syntax error was in this for loop.
               ^-- SC1078: Did you forget to close this double quoted string?

解决这个问题,你得到:

Line 1:
 #!/bin/bash
^-- SC1114: Remove leading spaces before the shebang.

Line 20:
declare -a myarr=(`echo "$function" [sed 's/declare[ ]-f / /g'`)
                  ^-- SC2207: Prefer mapfile or read -a to split command output (or quote to avoid splitting).
                  ^-- SC2006: Use $(..) instead of legacy `..`.
                  ^-- SC2116: Useless echo? Instead of 'cmd $(echo foo)', just use 'cmd foo'.

Line 22:
read -p "Enter a number (1, 2, or 3): " number
^-- SC2162: read without -r will mangle backslashes.

Line 35:
    if echo "$element" | grep -q "$num"; then
                                  ^-- SC2154: num is referenced but not assigned.