сценарий пепла: переменная, содержащая пробел, отказывается быть очищенной

1267
Nick Alexander

Я пытаюсь запустить сценарий, указанный по адресу http://talk.maemo.org/showthread.php?t=70866&page=2, на предполагаемом оборудовании - телефоне Nokia Linux с установленной программой BusyBox ash. Сценарий получает имя сети WiFi в качестве параметра и пытается подключить к нему телефон. Я подозреваю, что скрипт работает, но мой SSID, BU (802.1x), содержит пробел и круглые скобки. Поэтому, когда я печатаю в командной строке

autoconnect.sh BU\ \(802.1x\) 

Я получаю различные ошибки. Первый,

LIST=`iwconfig wlan0 | awk -F":" '/ESSID/'` if [ $LIST = "\"$1\"" ]; then 

... не удается, даже я подключен к сети. Ошибка не предотвращается путем использования одинарных или двойных кавычек вместо экранирования символов в командной строке.

Во-вторых,

if [ -z `iwlist wlan0 scan | grep -m 1 -o \"$1\"` ]; then echo SSID \"$1\" not found; 

показывает, что grep не находит строку, хотя тот же самый grep, введенный непосредственно в командной строке, находит 'BU (802.1x)' .

Как мне указать 1 доллар в двух вышеупомянутых обстоятельствах, чтобы он работал с моим SSID сети, содержащим пробелы и скобки?

Спасибо.

3

2 ответа на вопрос

2
Ярослав Рахматуллин

The output of iwconfig puts the name of the access point in double quotes, which leads to some weirdness. The author of the script deals with this "artifact" in his script rather than getting rid of it right away. I suggest to remove the quotes before doing anything else. Two possible approaches would be:

$ eval moo=`iwconfig wlan0 | awk -F":" '/ESSID/' ` $ moo=`iwconfig wlan0 | awk -F":" '/ESSID/' |tr -d \"` 

The first one executes the variable assignment statement "literally", while the other one removes double quotes from the output string.

The second problem with the script lies in the assumption that it is fine to use $LIST without quoting it (since the string would have contained double quotes). I think this is a mistake because the string still evaluates as two tokens:

$ moo='"aaa bbb"' $ if [ $moo = "\"aaa bbb\""];then ok;fi ash: bbb": unknown operand $ if [ "$moo" = "\"aaa bbb\"" ];then echo ok;fi ok 

In order to fix this, quote the parameters in the square brackets and get rid of the escaped quotes in the second argument (because we removed them from the iwconfig output):

if [ "$LIST" = "$1" ]; then ... 

Also, in order to pass a string with irregular character (space, parenthesis) as one argument to a script, just quote it:

$ autoconnect.sh "a name (with a comment)" 

The last part about matching the name with grep has already been adequately answered by glenn jackman.

Note: The above was tested with BusyBox ash (1.20.2).

Спасибо, хотелось бы отметить оба ответа как принятые. Оба работали отлично, или, по крайней мере, так кажется. Увы, сценарий никогда не выполняется, потому что следующая строка - это awk, который требует экранирования каждого пробела. Выложу это как отдельный вопрос. Nick Alexander 11 лет назад 0
1
glenn jackman

Don't try to add literal quotes. You need if [ "$LIST" = "$1" ]; .... Both variables need to be quoted so the test command is given exactly 3 arguments -- this is crucial particular because the values contain spaces.

Same advice for the second: if [ -z $(iwlist wlan0 scan | grep -m 1 -o "$1") ]; ...

The better way to write the above: if iwlist wlan0 scan | grep -q "$1"; ...