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

时间:2015-07-25 06:00:20

标签: bash awk raspberry-pi raspbian whiptail

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

问题是,当任何网络名称中都有空格时,列表就会搞乱。带有空格的SSID在whiptail菜单中被分割为多个条目。一个例子是"测试网络网络"将是3个条目。任何帮助解决这个问题,将不胜感激。

有问题的代码如下所示。您会注意到我手动添加"其他"到列表中以便以后允许手动输入SSID。

wifiNetworkList="$(iwlist wlan0 scan | grep ESSID | awk -F \" '{print $2 ; print $2}')"
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时,我们必须在它周围加上引号,这给了我们"${wifiNetworkList[@]}"

1 个答案:

答案 0 :(得分:1)

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

我无法使用空格重现输入,但从% echo 'ESSID:"net one"\nESSID:"net2"' ESSID:"net one" ESSID:"net2" 开始,它可以用以下方式制作:

e

我将在Zsh中展示其余内容,因为它的数组处理(docs)更干净,如果Zsh不适合你,你可以移植到Bash。

这会将每个essid % 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) 就像你做的那样简单:

"D-ROW": [
       {
        "@num": "26",
        "type": "wew",
        "val": ".000"
       },
       {
        "@num": "27",
        "type": "wew",
        "val": ".000"
       },
       {
        "@num": "28",
        "type": "wew",
        "val": ".000"
    }

not splitting words