fid*_*ity 7 bash shell-script associative-array
我需要将命令的输出放入关联数组中。
例如:
dig mx +short google.com
Run Code Online (Sandbox Code Playgroud)
将返回:
20 alt1.aspmx.l.google.com.
40 alt3.aspmx.l.google.com.
50 alt4.aspmx.l.google.com.
10 aspmx.l.google.com.
30 alt2.aspmx.l.google.com.
Run Code Online (Sandbox Code Playgroud)
如何使用优先级 (10,20,...) 作为键和记录 (aspmx.l.google.com.) 作为值创建关联数组?
这是将数据读入 bash 关联数组的一种方法:
代码:
#!/usr/bin/env bash
declare -A hosts
while IFS=" " read -r priority host ; do
hosts["$priority"]="$host"
done < <(dig mx +short google.com)
for priority in "${!hosts[@]}" ; do
echo "$priority -> ${hosts[$priority]}"
done
Run Code Online (Sandbox Code Playgroud)
输出:
20 -> alt1.aspmx.l.google.com.
10 -> aspmx.l.google.com.
50 -> alt4.aspmx.l.google.com.
40 -> alt3.aspmx.l.google.com.
30 -> alt2.aspmx.l.google.com.
Run Code Online (Sandbox Code Playgroud)