2014-09-21 80 views
0

我寫了一個使用if - elif構造的小腳本。出於某種原因,它不會起作用。 錯誤代碼:elif的語法錯誤

./lab4.sh: line 9: syntax error near unexpected token `elif' 
./lab4.sh: line 9: `elif [ $number -eq 2 ] then func2' 

我的實際代碼:

#!/bin/bash 
#ask the user for a number between 1 and 3 
#create some functions, write out the function number 
echo "Enter a number between 1 and 3: " 
read number 

#which function should be called? 
if [ $number -eq 1 ] then func1 
elif [ $number -eq 2 ] then func2 
elif [ $number -eq 3 ] then func3 fi 

function func1 { 
    echo "This message was displayed from the first function." 
} 

function func2 { 
    echo "This message was displayed from the second function." 
} 

function func3 { 
    echo "This message was displayed from the third function." 
} 
+1

在看看:HTTP://www.shellcheck .net/ – Cyrus 2014-09-21 14:45:51

+0

在'[$ number -eq 1]之後放一個分號;' – anubhava 2014-09-21 14:48:27

+0

謝謝,這真的很有用 – masm64 2014-09-21 14:48:38

回答

2

您必須返回到一個新行或shell聲明(iftheneliffi ...)之前使用;

你還必須在使用它們之前聲明你的函數。

#!/bin/bash 
#ask the user for a number between 1 and 3 
#create some functions, write out the function number 
echo "Enter a number between 1 and 3: " 
read number 

function func1 { 
    echo "This message was displayed from the first function." 
} 

function func2 { 
    echo "This message was displayed from the second function." 
} 

function func3 { 
    echo "This message was displayed from the third function." 
} 

#which function should be called? 
if [ $number -eq 1 ]; then func1 
elif [ $number -eq 2 ]; then func2 
elif [ $number -eq 3 ]; then func3; fi 
+1

謝謝!我實際上修復了這個功能,但是如果 - elif構造讓我瘋狂了x) – masm64 2014-09-21 14:52:58

+0

歡迎你,感謝投票。 – 2014-09-21 14:53:40

2

對於這種多if/elif的IT有時候更容易使用case語句,如:

func1() { echo "func1"; } 
func2() { echo "func2"; } 
func3() { echo "func3"; } 

while read -r -p 'Enter a number between 1 and 3:>' number 
do 
    case "$number" in 
     1) func1 ; break ;; 
     2) func2 ; break ;; 
     3) func3 ; break ;; 
     q) exit;; 
     *) echo "Wrong input" >&2;; #error message 
    esac 
done 
echo "end of loop" 

評論:不要使用function關鍵字。這是一個bashism,定義一個殼功能的便攜式方式是

funcname() { 
} 

,這是一個有點短太... :)