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&amp; author是一个字符串数组 aTitle&amp; aAuthor是用户输入
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 :(得分:0)
标准posix shell的for loop
错误!
它不是C / C ++,它是shell,这是通常的方法:
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
来运行该示例,这可能是dash
或bsh
之类的另一个shell。此外,您不应在for循环条件中使用$i
,而i
不能使用$
。
N.B。:在我给出的脚本中,仍然存在错误:$i
未在脚本的上下文中定义!
答案 1 :(得分: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
}