我是bash的新手,想知道是否有人可以帮助我解决以下问题。
我想从文件(/etc/sysctl.conf
)中读取数据并将它们排序到数组中。但是,我不想读取所有值,只读取某些值,如下例。
net.ipv4.tcp_tw_reuse
net.ipv4.tcp_tw_recycle
net.ipv4.tcp_fin_timeout
然后,我想将这些值与预定义的集合(示例如下)进行比较。
net.ipv4.tcp_tw_reuse = 0
net.ipv4.tcp_tw_recycle = 0
net.ipv4.tcp_fin_timeout = 120
然后输出这些值是否匹配。
使用declare -A
创建的关联数组,在bash中相当于其他语言中可能称为的"dict"或"map"(使用字符串作为键和值)。因此,它适用于键/值对。
#!/usr/bin/env bash
case $BASH_VERSION in ''|[0-3].*) echo "ERROR: Bash 4.0+ required" >&2; exit 1;; esac
# define an associative array mapping your expected keys to values
declare -A expected_values=(
[net.ipv4.tcp_tw_reuse]=0
[net.ipv4.tcp_tw_recycle]=0
[net.ipv4.tcp_fin_timeout]=120
)
declare -A matches_seen=( ) # track which of the values are actually set
mismatches_seen=0 # initialize flag: no mismatches yet seen
while IFS='= ' read -r key value; do
expected_value=${expected_values[$key]} # look up expected value if any exists
[[ $expected_value ]] || continue # ignore any lines we don't care about
if [[ $value = "$expected_value" ]]; then
echo "GOOD: $key matches expected value of <$expected_value>" >&2
matches_seen[$key]=1 # record that we really saw this one
else
echo "BAD: $key is expected to be <$expected_value>, but actually is <$value>" >&2
mismatches_seen=1 # set mismatches-seen flag
fi
done </etc/sysctl.conf
# Make sure that we actually saw all the values we expected
# could iterate over the keys to figure out exactly which ones are missing if you cared.
if (( ${#matches_seen[@]} != ${#expected_values[@]} )); then
echo "ERROR: only ${#matches_seen[@]} of ${#expected_values[@]} values present" >&2
exit 1
fi
exit "$mismatches_seen" # failed exit status if any mismatches seen
你可以避免需要matches_seen
,如果你从expected_values
中删除项目,因为他们是匹配的(这样任何键留在expected_values
将反映一个错误),但这意味着你将失去处理在文件中出现多次的值的能力。