Linux基础 - shell数组

作者: 菩提老鹰 | 来源:发表于2018-01-25 20:39 被阅读49次

摘要

数组的特性就是一组数据类型相同的集合,虽然shell是弱类型,但是我们也可以将其数组分为数据类型的数组字符串类型的数组两类
shell的数组元素之间用空格分隔开


数组操作

假设有以下两个数组

array1=(1 2 3 4 5 6)
array2=("James" "Colin" "Harry")
  • 数据变量名默认输出
    默认直接输出变量的话,其输出值默认为第一个元素的值,下标从0开始
root@pts/1 $ echo $array1
1
root@pts/1 $ echo $array2
James
  • 获取数组元素
    格式:${数组名[下标]},下标从0开始,下标为*@代表整个数组内容
root@pts/1 $ echo ${array1[2]}
3
root@pts/1 $ echo ${array2[1]}
Colin

## 获取全部元素
root@pts/1 $ echo ${array2[*]}
James Colin Harry
root@pts/1 $ echo ${array2[@]}
James Colin Harry
  • 获取数组长度
    格式:${#数组名[*或@]}
root@pts/1 $ echo ${#array1[@]}
6
root@pts/1 $ echo ${#array2[*]}
3
  • 数组遍历
root@pts/1 $ for item in ${array2[@]}
> do
>     echo "The name is ${item}"
> done
The name is James
The name is Colin
The name is Harry
  • 数组元素赋值

格式:数组名[下标]=值,如果下标不存在,则新增数组元素; 下标已有,则覆盖数组元素值

root@pts/1 $ array1[2]=18
root@pts/1 $ echo ${array1[*]}
1 2 18 4 5 6

root@pts/1 $ array2[4]="Betty"
root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
  • 数组切片

格式:${数组名[*或@]:起始位:长度},截取部分数组,返回字符串,中间用空格分隔;将结果使用(),则得到新的切片数组

root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array2[*]:1:3}
Colin Harry Betty

root@pts/1 $ array3=(${array2[*]:1:2})
ks-devops [~] 2018-01-25 20:30:16
root@pts/1 $ echo ${array3[@]}
Colin Harry
  • 数组元素替换

格式:${数组名[*或@]/查找字符/替换字符}, 不会修改原数组;如需修改的数组,将结果使用“()”赋给新数组

root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array2[*]/Colin/Colin.Liu}
James Colin.Liu Harry Betty

root@pts/1 $ array4=(${array2[*]/Colin/Colin.liu})
root@pts/1 $ echo ${array4[*]}
James Colin.liu Harry Betty
  • 删除元素

格式:
unset 数组,清除整个数组;
unset 数组[下标],清除单个元素

root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty
root@pts/1 $ echo ${array4[*]}
James Colin.liu Harry Betty

root@pts/1 $ unset array4
root@pts/1 $ unset ${array2[3]}

root@pts/1 $ echo ${array2[*]}
James Colin Harry Betty

root@pts/1 $ echo ${array4[*]}

root@pts/1 $

相关文章

  • Linux基础 - shell数组

    摘要 数组的特性就是一组数据类型相同的集合,虽然shell是弱类型,但是我们也可以将其数组分为数据类型的数组和字符...

  • linux shell数组基础

    1什么是数组: 一组类型相同的数据的集合,有数值型和字符型 2 linux shell如何表示数组 不管数值型还是...

  • Linux Shell:Shell数组操作

    摘要:Linux,Shell Shell数组类型 Shell数组分为普通数组和关联数组,普通数组就是相同类型的元素...

  • Linux Shell 动态生成 数组系列 Seq 使用技巧

    Linux Shell 动态生成 数组系列 Seq 使用技巧 如果对linux shell 数组不是很熟悉的话,请...

  • shell基础

    Linux学习 一、shell介绍 Linux shell基础 什么是shell shell是一个命令解释器,提供...

  • Shell学习

    Linux Shell基础教程 (一) (二) Linux Shell简明教程(推荐) (一) (二) Linux...

  • Linux—Shell基础

    ++2016.8.7++byside @Linux—Shell基础 =======================...

  • Linux Shell:基础知识和Shell变量

    摘要:Linux,Shell 整理Shell内容要点: Shell基础知识 Shell变量的类型 Shell变量赋...

  • shell & bash基础命令及巧用

    shell与bash脚本的区别shell是Linux基础命令解释器bash(Bourne Again shell)...

  • Shell 数组与数学运算

    参考书籍 Linux shell 脚本攻略 数组和关联数组 数组分类普通数组:只能使用整数作为数组索引。关联数组:...

网友评论

    本文标题:Linux基础 - shell数组

    本文链接:https://www.haomeiwen.com/subject/tsrbaxtx.html