使用空格获取 awk 输出并将其放入带有 BASH 的 Whiptail 菜单中

Taking awk Output with Spaces and Putting it in a Whiptail Menu with BASH

我有一个 BASH 脚本,我想要获取附近无线网络的所有 SSID 并将它们输出到用户可以选择的菜单中。我有列出网络的部分,它们显示在菜单中,生成的 SSID 保存到变量中。

问题是,当任何网络的名称中包含 space 时,列表就会变得混乱。带有 space 的 SSID 在 whiptail 菜单中被拆分为多个条目。一个例子是 "Test Networks Network" 将是 3 个条目。如果您能帮助解决此问题,我们将不胜感激。


有问题的代码如下所示。您会注意到我手动将 "Other" 添加到列表中,以便稍后手动输入 SSID。

wifiNetworkList="$(iwlist wlan0 scan | grep ESSID | awk -F \" '{print  ; print }')"
wifiNetworkList+=' Other Other'
wifiSSID=$(whiptail --notags --backtitle "PiAssist" --menu "Select WiFi Network" 20 80 10 $wifiNetworkList 3>&1 1>&2 2>&3)

最终解决方案:

wifiNetworkList=()  # declare list array to be built up
ssidList=$(iwlist wlan0 scan | grep ESSID | sed 's/.*:"//;s/"//') # get list of available SSIDs
while read -r line; do
    wifiNetworkList+=("$line" "$line") # append each SSID to the wifiNetworkList array
done <<< "$ssidList" # feed in the ssidList to the while loop
wifiNetworkList+=(other other) # append an "other" option to the wifiNetworkList array
wifiSSID=$(whiptail --notags --backtitle "PiAssist" --menu "Select WiFi Network" 20 80 10 "${wifiNetworkList[@]}" 3>&1 1>&2 2>&3) # display whiptail menu listing out available SSIDs

我在代码中加入了注释,以帮助解释那些 运行 遇到同样问题的人的情况。需要注意的关键事情之一是,当我们将 wifiNetworkList 提供给 whiptail 时,我们必须在它周围加上引号,这给了我们 "${wifiNetworkList[@]}".

与使用各种引号构建字符串相比,使用数组更容易。您基本上是在使用有时在单个条目中有空格的相同对。

我无法复制带空格的输入,但从 grep 的角度来看,它可以通过以下方式制作:

% echo 'ESSID:"net one"\nESSID:"net2"'
ESSID:"net one"
ESSID:"net2"

我将在 Zsh 中展示其余部分,因为它的数组处理 (not splitting words) 更干净,如果 Zsh 不适合您,您可以移植到 Bash。

这会将每个 essid e 放入数组中两次。

% l=()  # declare list array to be built up
% print 'ESSID:"net one"\nESSID:"net2"' |
    while read line; do e=$(sed 's/.*:"//;s/"//' <<<$line); l+=($e $e); done

other两次:

% l+=(other other)

您可以看到 l 现在是一个有用的配对形式:

% print -l $l     
net one
net one
net2
net2
other
other

现在调用 whiptail 就很简单了:

% wifiSSID=$(whiptail --notags --backtitle "PiAssist" --menu "Select WiFi Network" 20 80 10 $l)