百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>服务器> linux中Bash数组使用示例
分享文章到:

linux中Bash数组使用示例

发布时间:01/15 来源: 浏览: 关键词:
本文章来为各位介绍一篇关于linux中Bash数组使用示例,希望这一篇文章能够帮助到各位朋友,具体的步骤细节如下文介绍.

数组赋值


列表赋值

用新元素创建数组

array=('first element' 'second element' 'third element')
下标赋值

显式指定元素索引创建数组:

array=([3]='fourth element' [4]='fifth element')
按索引赋值

array[0]='first element'
array[1]='second element'
按名称赋值(关联数组)

declare -A array
array[first]='First element'
array[second]='Second element'
动态赋值

以其它命令的输出创建一个数组,例如使用seq创建一个从1到10的数组:

array=(`seq 1 10`)
从脚本参数创建数组

array=("$@")
循环内赋值

while read -r; do
    #array+=("$REPLY")     # Array append
    array[$i]="$REPLY"     # Assignment by index
    let i++                # Increment index
done < <(seq 1 10)  # command substitution
echo ${array[@]}    # output: 1 2 3 4 5 6 7 8 9 10
访问数组元素


打印索引为0的元素

echo "${array[0]}"
打印最后一个元素(从Bash 4.3可用)

echo "${array[-1]}"
打印从索引1开始的元素

echo "${array[@]:1}"
打印从索引1开始的3个元素

echo "${array[@]:1:3}"
数组更改


按索引更改

初始化或者更新数组中的一个特定元素

array[10]="elevenths element"    # because it's starting with 0
追回

修改数组,追加元素到数组结尾

array+=('fourth element' 'fifth element')
添加元素到数组开头

array=("new element" "${array[@]}")
插入

给定索引值插入一个元素

arr=(a b c d)
# insert an element at index 2
i=2
arr=("${arr[@]:0:$i}" 'new' "${arr[@]:$i}")
echo "${arr[2]}" #output: new
删除

使用uset删除指定索引元素

arr=(a b c)
echo "${arr[@]}"   # outputs: a b c
echo "${!arr[@]}"  # outputs: 0 1 2
unset -v 'arr[1]'
echo "${arr[@]}"   # outputs: a c
echo "${!arr[@]}"  # outputs: 0 2
重排索引

当有一些元素从数组被删除时,可以使用下面方法重排索引,或者你不知道索引是否存在时隙时会有用。

array=("${array[@]}")
数组长度


${#array[@]}可以得到${array[@]}数组的长度

array=('first element' 'second element' 'third element')
echo "${#array[@]}" # gives out a length of 3
迭代数组元素


fileList=( file1.txt file2.txt file3.txt )
 
# Within the for loop, $file is the current file
for file in "${fileList[@]}"
do
  echo "$file"
done

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有8人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板