#!/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/