2014-01-30 80 views
0
for ((c=0; c<$i; c++)); do 
if [[ "$aTitle" == "${bookTitle[$c]}" ]]; then 
if [[ "$aAuthor" == "${author[$c]}" ]]; then  
found=true 
fi 
fi 
done 

echo $found 

嗨,即时通讯相当新的shell编程,任何人都可以告诉我为什么我得到这个错误,当我运行这段代码?非常感谢。 BOOKTITLE &作者是一个字符串数组 aTitle & aAuthor是输入用户Bash if else声明错误

function add_new_book 
{ 
echo "1) add_new_book" 

found=false 

echo -n "Title: " 
read aTitle 
echo -n "Author: " 
read aAuthor 

for ((c=0; c<$i; c++)); do 
    if [[ "$aTitle" == "${bookTitle[$c]}" ]]; then 

     if [[ "$aAuthor" == "${author[$c]}" ]]; then  

      found=true 

     fi 

    fi 
done 

echo $found 
} 

#author[$i]=$aAut} 

./menu.sh: line 43: syntax error near unexpected token `done' 
./menu.sh: line 43: ` done' 
+0

该错误可能在其他地方。 – devnull

+0

执行为bash -x ./menu.sh并发布输出 – BrenoZan

+0

我不明白问题,我的示例通过了ok –

回答

0

for loop是错误的标准POSIX外壳! 这不是C/C++,它的外壳和这里的通常的方式做到这一点:

for c in $(seq 0 $i); do 
    ... 
done 

和下面的结构:

typeset -i i END 
for ((i=0;i<END;++i)); do echo $i; done 

是bash的具体和下面给出任何错误:

#!/bin/bash 

function add_new_book() { 
    echo "1) add_new_book" 

    found=false 

    echo -n "Title: " 
    read aTitle 
    echo -n "Author: " 
    read aAuthor 

    # declare c and END as integers 
    typeset -i c END 
    let END=5 # use END instead of $i if $i is not defined! 
    for ((c=0;c<i;++c)); do 

     if [[ "$aTitle" == "${bookTitle[$c]}" ]]; then 

      if [[ "$aAuthor" == "${author[$c]}" ]]; then  

       found=true 

      fi 

     fi 
    done 

    echo $found 
} 

add_new_book 

所以我想你可能一直试图用/bin/sh而不是/bin/bash来运行这个例子,它可能是另一个shell,如dashbsh。在for循环条件下,您也不能使用$i,但在中不应使用i

N.B .:在我给出的脚本中,仍然存在错误:$i未在脚本的上下文中定义!

+0

哦..谢谢..但它不应该工作呢? – user3188291

+0

鉴于他成功使用'function'关键字来定义函数,我怀疑他是否使用严格符合POSIX标准的shell。 – chepner

0

此示例脚本可能会对您有所帮助。

bookTitle="linux,c,c++,java" 
author="dony,jhone,stuart,mohan" 

function add_new_book() 
{ 
    IFS=', ' 
    read -a bookTitle <<< "$bookTitle" 
    read -a author <<< "$author" 

    echo "1) add_new_book" 

    found=false 

    echo -n "Title: " 
    read aTitle 
    echo -n "Author: " 
    read aAuthor 


    for index in "${!bookTitle[@]}" 
    do 
     if [[ "$aTitle" == "${bookTitle[index]}" ]] 
     then  

      if [[ "$aAuthor" == "${author[index]}" ]] 
      then  
        found=true 
      fi 
     fi 
    done 

    echo $found 
}