Shell脚本:使用关联数组存储命令输出
在shell脚本中,可以使用关联数组来存储输出。关联数组是一种能够将键值对联系起来的数据结构,可以使用键来快速访问对应的值。以下是一个示例脚本,将命令输出存储到关联数组中:
#!/bin/bash
# 执行命令,并将输出存储到关联数组中
declare -A output
output['date']=$(date)
output['whoami']=$(whoami)
output['pwd']=$(pwd)
# 遍历关联数组,输出键值对
for key in '${!output[@]}'; do
echo '$key: ${output[$key]}'
done
在此示例中,使用declare -A声明一个空的关联数组output。然后,使用output['键']=值语法将命令输出存储到关联数组中。最后,使用${!output[@]}遍历关联数组的所有键,并使用${output[$key]}获取对应的值。输出的结果类似于:
date: Thu Nov 11 18:21:46 CST 2021
whoami: user
pwd: /home/user
原文地址: https://www.cveoy.top/t/topic/nyS9 著作权归作者所有。请勿转载和采集!