Bash shell 中的字典

简介: 一 背景在一些运维工作中,使用字典能让当前工作事半功倍,类似 Python ,在 GNU bash 4.2.46 中,我们也可以很方便的使用字典来完成一些工作了。本文以一段 bash shell 为例展示一下 Bash 中字典的使用。

一 背景

在一些运维工作中,使用字典能让当前工作事半功倍,类似 Python ,在 GNU bash 4.2.46 中,我们也可以很方便的使用字典来完成一些工作了。本文以一段 bash shell 为例展示一下 Bash 中字典的使用。

二 脚本

#!/bin/bash
# Declare a dictionary.
declare -A Host
Host=( [node1]='10.1.1.11' [node2]='10.1.1.12' [node3]='10.1.1.13' [node4]='10.1.1.14' )

# Traversing dictionary values.
for node_ip in ${Host[@]};
do
  echo "One IP of these hosts is ${node_ip} .";
done

# Traversing dictionary keys.
for node in ${!Host[@]};
do
  echo "One hostname of these hosts is: ${node}. ";
done

# Traverse keys and values at the same time.
for node in ${!Host[@]};
do
  echo "Hostname: ${node}, IP: ${Host[${node}]}. "
done

# Get the length of this dictionary.
echo "The length of this dictionary is ${#Host[@]}. "

# Append a key and a value.
Host[node5]='10.1.1.15'
echo "The value of new dictionary is: ${Host[@]}. "
echo "The length of dictionary is: ${#Host[*]}. "

# Modify a value of the dictionary .
Host[node1]='10.1.1.111'
echo "The value of new dictionary is: ${Host[@]}. "

执行结果:

One IP of these hosts is 10.1.1.14 .
One IP of these hosts is 10.1.1.11 .
One IP of these hosts is 10.1.1.12 .
One IP of these hosts is 10.1.1.13 .
One hostname of these hosts is: node4.
One hostname of these hosts is: node1.
One hostname of these hosts is: node2.
One hostname of these hosts is: node3.
Hostname: node4, IP: 10.1.1.14.
Hostname: node1, IP: 10.1.1.11.
Hostname: node2, IP: 10.1.1.12.
Hostname: node3, IP: 10.1.1.13.
The length of this dictionary is 4.
The value of new dictionary is: 10.1.1.14 10.1.1.15 10.1.1.11 10.1.1.12 10.1.1.13.
The length of dictionary is: 5.
The value of new dictionary is: 10.1.1.14 10.1.1.15 10.1.1.111 10.1.1.12 10.1.1.13.

三 总结

脚本的注释解释了后面相关代码的功能。通过脚本,我们对 Bash 中的字典有了一些新的认识。

相关文章
|
2月前
|
移动开发 Shell Linux
百度搜索:蓝易云【Shell错误:/bin/bash^M: bad interpreter: No such file or directory】
将 `your_script.sh`替换为你的脚本文件名。运行此命令后,脚本文件的换行符将被转换为Linux格式,然后就可以在Linux系统上正常执行脚本了。
33 8
|
4月前
|
Linux Shell Windows
4:Bash shell命令-步入Linux的现代方法
4:Bash shell命令-步入Linux的现代方法
53 0
|
8月前
|
Ubuntu 安全 Linux
不用安装虚拟机,直接在Windows上面运行Linux Bash Shell,嗯!真香!!!
不用安装虚拟机,直接在Windows上面运行Linux Bash Shell,嗯!真香!!!
152 0
|
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
|
4月前
|
Shell
在Shell(如Bash)中,`while`循环
在Shell(如Bash)中,`while`循环
41 2
|
4月前
|
机器学习/深度学习 Unix Shell
Shell编程基础入门(Bash|变量与输入输出重定向2&1)
Shell编程基础入门(Bash|变量与输入输出重定向2&1)
69 0
|
8月前
|
Shell Linux
10.1.5 查询指令是否为 Bash shell 的内置命令: type
10.1.5 查询指令是否为 Bash shell 的内置命令: type
60 0
|
8月前
|
Shell 测试技术 Python
如何在Bash Shell脚本中使用`exec`命令?
如何在Bash Shell脚本中使用`exec`命令?
130 0
|
10月前
|
Shell
【Shell编程】Shell中Bash变量-数值运算、运算符变量、测试和内容替换
【Shell编程】Shell中Bash变量-数值运算、运算符变量、测试和内容替换
56 0