gpt4 book ai didi

linux - 如何为此代码制作错误消息

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:05:25 25 4
gpt4 key购买 nike

#!/bin/bash

my_array=(red orange green)
value='green'

for i in "${!my_array[@]}"; do
if [[ "${my_array[$i]}" = "${value}" ]]; then
echo "${i}";
fi
done

此代码将打印数组中值的索引,如果条目不在数组中,我如何改进它以打印错误消息

最佳答案

你可以添加一个标志变量,在循环之前被清除,找到值时设置,如果标志仍然为空,则在循环后打印错误消息。

found=
for i in "${!my_array[@]}"; do
if [[ "${my_array[$i]}" = "${value}" ]]; then
echo "${i}"
found=1
fi
done

if [ ! "$found" ]; then
echo Error: no such value in the array: $value
fi

或者,您可以使用关联数组来保留值的索引及其在数组中的位置:

my_array=(red orange green)

declare -A index
for ((i = 0; i < ${#my_array[@]}; i++)); do
index[${my_array[$i]}]=$i
done

local value=$1

if [ "${index[$value]}" ]; then
echo "${index[$value]}"
else
echo Error: no such value in the array: $value
fi

关于linux - 如何为此代码制作错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47721387/

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