数组中可以存放多个值。 Shell 只支持一维数组(不支持多维数组),初始化时不需要定义数组大小。
与大部分编程语言类似,数组元素的下标由0开始。
Shell 数组用括号来表示,元素用"空格"符号分割开,语法格式如下:
my_array=(value1 ... valuen)
1.定义一个数组
my_array=(A B C D)
2.读取数组中的元素
读取方式:{my_array[index]}
echo "第一个元素为: ${my_array[0]}"
echo "第二个元素为: ${my_array[1]}"
echo "第三个元素为: ${my_array[2]}"
echo "第四个元素为: ${my_array[3]}"
3.获取数组中所有元素
shell使用@ 或 * 可以获取数组中的所有元素
#!/bin/bash
my_array=(A B C D)
echo "数组的元素为: ${my_array[*]}"
echo "数组的元素为: ${my_array[@]}"
4.获取数组的长度
#!/bin/bash
my_array=(A B C D)
echo "数组元素个数为: ${#my_array[*]}"
echo "数组元素个数为: ${#my_array[@]}"
5.接下来我们用数组结合函数写一个菜单
#!/bin/bash MENU_EXPLAIN=( "退出" "状态" "更新" "回滚" "重启" "停止" "免密" "日志" "资源" "登陆" ) MENU_LIST=( "exit" "status" "update" "roollback" "restart" "stop" "SEND_KEY" "log" "mem_disk" "ssh_login" ) main(){ clear ARRAY_NUM_MENU_LIST=${#MENU_EXPLAIN[*]} ARRAY_NUM=$(expr $ARRAY_NUM_MENU_LIST - 1) while true do echo -e "主菜单操作:" for I_MENU_LIST in ${!MENU_EXPLAIN[@]} do echo -e " ${MENU_EXPLAIN[${I_MENU_LIST}]} -----> $I_MENU_LIST" done read -p "选择要执行的操作:" NUM_MENU_LIST if [ "$NUM_MENU_LIST" = 0 ];then exit elif [[ "$NUM_MENU_LIST" =~ ^[0-9]+$ ]] && [ ${NUM_MENU_LIST} -le ${ARRAY_NUM} ];then clear ${MENU_LIST[${NUM_MENU_LIST}]} else clear echo "输入0-${ARRAY_NUM_MENU_LIST}的数字" fi done } main