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 数组的使用与其他编程语言有所不同,可以类比理解。

相关文章
|
2月前
|
移动开发 Shell Linux
百度搜索:蓝易云【Shell错误:/bin/bash^M: bad interpreter: No such file or directory】
将 `your_script.sh`替换为你的脚本文件名。运行此命令后,脚本文件的换行符将被转换为Linux格式,然后就可以在Linux系统上正常执行脚本了。
33 8
|
4月前
|
Shell 索引
shell脚本入门到实战(四)- 数组
shell脚本入门到实战(四)- 数组
|
4月前
|
Linux Shell Windows
4:Bash shell命令-步入Linux的现代方法
4:Bash shell命令-步入Linux的现代方法
53 0
|
4月前
|
Java Shell Linux
Linux【脚本 01】简单Shell脚本实现定时备份文件、压缩、删除超时文件操作(showDoc文件备份脚本举例)
Linux【脚本 01】简单Shell脚本实现定时备份文件、压缩、删除超时文件操作(showDoc文件备份脚本举例)
103 0
|
11天前
|
分布式计算 Hadoop Shell
Hadoop【基础知识 04】【HDFS常用shell命令】(hadoop fs + hadoop dfs + hdfs dfs 使用举例)
【4月更文挑战第4天】Hadoop【基础知识 04】【HDFS常用shell命令】(hadoop fs + hadoop dfs + hdfs dfs 使用举例)
26 5
|
14天前
|
存储 Shell Linux
【攻防世界】unseping (反序列化与Linux bash shell)
【攻防世界】unseping (反序列化与Linux bash shell)
|
22天前
|
人工智能 机器人 Shell
【shell】shell数组的操作(定义、索引、长度、获取、删除、修改、拼接)
【shell】shell数组的操作(定义、索引、长度、获取、删除、修改、拼接)
|
6月前
|
Shell Linux PHP
|
4月前
|
Shell
Shell(如Bash)命令行技巧
Shell(如Bash)命令行技巧
26 2
|
4月前
|
Unix Shell iOS开发
Shell错误:/bin/bash^M: bad interpreter: No such file or directory
Shell错误:/bin/bash^M: bad interpreter: No such file or directory
43 0