2014-01-10 94 views
0

該程序通過匹配書名和書籍作者的用戶輸入來檢查某個書名是否存在。奇怪的shell腳本錯誤:無效的選項return:usage:return [n]

function removebook_option() 
{ 
    echo -n "Title : " 
    read title_input2 

    echo -n "Author: " 
    read author_input2 

    checkexist $title_input2 $author_input2 
    error=$? 
    echo "$error" 

    if [ $error != -1 ];then 
     #removebook 
      echo "New book title $title_input removed successfully" 
     else 
     echo "Book does not exist" 


    fi 

} 

function checkexist() 
{ 
    counter=0 

    for x in ${title[@]} 
    do 

    for y in ${author[@]} 
    do 
     if [ $x == $1 ] && [ $y == $2 ]; 
     then 
      error=$counter 
       return "$error" 
     fi 
    done 
    counter=$((counter+1)) 
    done 

    error=-1 
    return "$error" 

} 

title=(foo1 foo2) 
author=(bar1 bar2) 
removebook_option 

我得到一個非常奇怪的錯誤,其中function checkexist()回報2,而不是-1時,心不是匹配返回值error=-1

line 43: return: -1: invalid option return: usage: return [n]

時發生,您可以嘗試輸入不正確的數據看奇怪的錯誤

我需要幫助解決這個問題謝謝!

+0

不能在shell函數使用'return'。也許你可以'回聲'的東西,並在調用函數時捕獲它。 – fedorqui

+0

我不確定,我看到之前使用return的代碼,你如何回顯代碼並捕獲它? – Computernerd

回答

1

你應該爲0或正整數1到255

之間根據http://tldp.org/LDP/abs/html/exit-status.html#FTN.AEN2974

by convention, 0 on success or an integer in the range 1 - 255 on error.

雖然可以使用return -- -1
$?會顯示255,而不是-1

返回

,因爲-1超出了有效範圍

看到http://tldp.org/LDP/abs/html/exitcodes.html#EXITCODESREF

Out of range exit values can result in unexpected exit codes. An exit value greater than 255 returns an exit code modulo 256. For example, exit 3809 gives an exit code of 225 (3809 % 256 = 225).

+0

是否有返回-1? – Computernerd

+0

否,不在0和255之間的任何數字都將被更改爲有效範圍[0,255] – ray