gpt4 book ai didi

bash - BASH函数中for循环中的数组

转载 作者:行者123 更新时间:2023-12-04 19:14:01 25 4
gpt4 key购买 nike

    function bookExistCheck {

for i in "${bookTitle[@]}"
do
if [ "$1" == "${bookTitle[$i]}" ]; then
if [ "${bookAuthor[$i]}" == "$2" ]; then
bookExist=true
echo "Book already exist in database."
fi
fi
done

}

我正在尝试编写一个接受 2 个变量、标题和作者的函数,然后检查它是否已经存在。 BookTitle 和 BookAuthor 是已经包含书名和作者值的数组。目前使用上面的代码,我在线上遇到错误
 if [ "$1" == "{$bookTitle[$i]}" ]; then

错误说

./menu.sh: line 25: Harry Potter - The Half Blood Prince: syntax error in expression (error token is "Potter - The Half Blood Prince")



我对 BASH 很陌生,所以我的猜测是合成错误?

最佳答案

当你写 for i in "${bookTitle[@]}" , i不是数组的索引,它已经是数组的元素。

试着写这样的东西:if [ "$1" == "${i}" ]; then
编辑

您也可以使用for环形:

for (( i=0; i<=${#bookTitle[@]}; i++ )); do 

在这种情况下, i将索引从 0 到 bookTitle尺寸。

关于bash - BASH函数中for循环中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45160942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com