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

标签 linux bash macos indexing

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

相关文章:

linux - 在linux中复制具有目录结构的修改后的文件

macos - 如何提示用户输入名称以创建文件夹(bash | shell 脚本)?

java - 找不到适合 jdbc :postgresql://192. 168.1.8:5432/NexentaSearch 的驱动程序

linux将程序提升为shell命令

linux - 仅计算目录中可见文件的数量

xcode - 安装 xcode 后的 git push.default 设置

c - 在 Linux 内核中从 sk_buff 和 inode 获取 PID

python - 即使发生任何中断也可以写入文件

bash 读取命令

bash - Docker文件 : how to get bash command line after start?