bash shell 中数组使用举例

简介: bash shell 中数组使用举例一 背景让我们先来看一个 shell 脚本的执行过程及结果:[gysl@gysl-DevOps ~]$ sh array.sh N2 N3 N4The elements of this array 2-4 are: N2 N3 N4N1 is in array.

bash shell 中数组使用举例

一 背景

让我们先来看一个 shell 脚本的执行过程及结果:

[gysl@gysl-DevOps ~]$ sh array.sh N2 N3 N4
The elements of this array 2-4 are: N2 N3 N4
N1 is in array.  
N2 is in array.  
N3 is in array.  
N4 is in array.  
The original array is as follows: N1 N2 N3 N4
The length of this array is 4. 
The array[2] is N3. 
Append an element at the end of this array. This array: N1 N2 N3 N4 N5
Modify an element in an array. This array: N1 N2 N6 N4 N5

二 实现

实现脚本如下:

#!/bin/bash
array=('N1' 'N2' 'N3' 'N4')
case $1 in 
  ${array[0]})
    echo "${array[0]}"
  ;;
  ${array[@]:1:3})
    echo "The elements of this array 2-4 are: ${array[@]:1:3}"
  ;;
  *)
    echo "ERROR"
  ;;
esac
for num in ${array[@]} ;do
   echo "${num} is in array. "
done
echo "The original array is as follows: ${array[@]}"
echo "The length of this array is ${#array[*]}. "
echo "The array[2] is ${array[2]}. "
array[${#array[@]}]=N5
echo "Append an element at the end of this array. This array: ${array[@]}"
array[2]=N6
echo "Modify an element in an array. This array: ${array[*]}"

三 总结

3.1 这个例子实现了数组的各种用法,我们可以通过执行结果进行直观理解。需要注意的是子数组的获取,元素的修改,追加。
3.2 shell 数组的使用与其他编程语言有所不同,可以类比理解。

相关文章
|
5月前
|
移动开发 Shell Linux
百度搜索:蓝易云【Shell错误:/bin/bash^M: bad interpreter: No such file or directory】
将 `your_script.sh`替换为你的脚本文件名。运行此命令后,脚本文件的换行符将被转换为Linux格式,然后就可以在Linux系统上正常执行脚本了。
65 8
|
5月前
|
Shell 索引
shell脚本入门到实战(四)- 数组
shell脚本入门到实战(四)- 数组
|
2月前
|
Shell KVM 虚拟化
Shell 数组编程
【8月更文挑战第22天】 Shell 数组编程
42 10
|
2月前
|
缓存 Shell Linux
在Linux中,bash shell 中的 hash 命令有什么作用?
在Linux中,bash shell 中的 hash 命令有什么作用?
|
2月前
|
Shell Linux
在Linux中,使用bash shell实现条件判断和循环结构的例子是什么样的?
在Linux中,使用bash shell实现条件判断和循环结构的例子是什么样的?
|
2月前
|
存储 Shell 数据处理
深入探讨Bash脚本中的数组
【8月更文挑战第20天】
13 0
|
2月前
|
存储 运维 Shell
运维.Linux.bash学习笔记.数组及其使用
运维.Linux.bash学习笔记.数组及其使用
27 0
|
5月前
|
存储 算法 安全
shell 脚本之 函数与数组
shell 脚本之 函数与数组
|
4月前
|
存储 Shell 开发者
Shell 数组:灵活操作的秘诀
**Shell 数组简介**:作为基础数据结构,数组在Shell编程中不可或缺。它们存储多个值,下标从0开始。创建如`array=(值1 值2...)`,访问用`${array[index]}`。增删改查及获取长度、拼接数组都有相应语法,例如`unset array[index]`删除元素,`${#array[@]}`获取长度。通过实践这些操作,提升Shell脚本技能。
22 0
|
4月前
|
Shell Linux
linux shell 脚本实现:根据文件内容中的每行分隔符放入数组,根据规则打印日志并重新创建目录 备份文件
linux shell 脚本实现:根据文件内容中的每行分隔符放入数组,根据规则打印日志并重新创建目录 备份文件
42 0