我正在尝试使用 bash 文件在已经填充的网络之间切换命令行但我得到的是无意义的数据。
但得到废话
1) 0
#? 0
下面的代码。
#!/bin/bash
# Pre-populated UUID data for network connections
networks=(
["tr_5"]="127f3e9e-34dd-444e-aee4-7c2b35c7c307"
["VC_HotSpot_6"]="c498aa6a-24d4-4b51-92c7-9b8d84181fc1"
["Network_3"]="34567890-3456-3456-3456-345678901234"
)
# List available network connections
echo "Available network connections:"
nmcli connection show
# Prompt the user to choose a network
echo "Select the network to connect to:"
select network_name in "${!networks[@]}"; do
if [[ -n $network_name ]]; then
break
fi
done
# Get the UUID of the selected network
network_uuid=${networks[$network_name]}
# Check if the network UUID exists
if [[ -z $network_uuid ]]; then
echo "Network '$network_name' UUID not found. Exiting..."
exit 1
fi
# Disconnect from the current network (if connected)
current_connection=$(nmcli connection show --active | awk 'NR>1{print $1}')
if [[ -n $current_connection ]]; then
echo "Disconnecting from the current network..."
nmcli connection down $current_connection
fi
# Connect to the chosen network
echo "Connecting to network '$network_name'..."
nmcli connection up uuid $network_uuid
# Display the connection status
echo "Connection status:"
nmcli connection show --active | grep -E "($network_name|$current_connection)"
echo "Network switch completed successfully!"
我运行脚本 ./network_switch.sh
但得到废话
1) 0
#? 0
答案1
在这种情况下,使用declare
内置函数来检查分配的结果会很有帮助:
$ networks=(
["tr_5"]="127f3e9e-34dd-444e-aee4-7c2b35c7c307"
["VC_HotSpot_6"]="c498aa6a-24d4-4b51-92c7-9b8d84181fc1"
["Network_3"]="34567890-3456-3456-3456-345678901234"
)
$ declare -p networks
declare -a networks=([0]="34567890-3456-3456-3456-345678901234")
您将看到您已经创建了一个索引数组 ( -a
) 只有一个第 0 个元素。这是因为name=(...)
语法默认创建索引数组,并且它只是将字符串值的“键”评估为数字 0,然后连续覆盖该值。
要创建一个联想数组你需要明确声明它,或者
declare -A networks=(
["tr_5"]="127f3e9e-34dd-444e-aee4-7c2b35c7c307"
["VC_HotSpot_6"]="c498aa6a-24d4-4b51-92c7-9b8d84181fc1"
["Network_3"]="34567890-3456-3456-3456-345678901234"
)
或者
typeset -A networks=(
["tr_5"]="127f3e9e-34dd-444e-aee4-7c2b35c7c307"
["VC_HotSpot_6"]="c498aa6a-24d4-4b51-92c7-9b8d84181fc1"
["Network_3"]="34567890-3456-3456-3456-345678901234"
)
然后你可以检查一下declare -p
:
$ declare -p networks
declare -A networks=([tr_5]="127f3e9e-34dd-444e-aee4-7c2b35c7c307" [Network_3]="34567890-3456-3456-3456-345678901234" [VC_HotSpot_6]="c498aa6a-24d4-4b51-92c7-9b8d84181fc1" )