Строка может потянуть символы (или цвета) быть добавленной к меню списка файлов Bash?

Я создал самое ужасное меню в мире с помощью первого инструмента Linux, который я изучаю, Bash.

На что похоже меню

The following /usr/local/bin/bell/sounds were found
1) /usr/local/bin/bell/sounds/Amsterdam.ogg
2) /usr/local/bin/bell/sounds/bell.ogg
3) /usr/local/bin/bell/sounds/Blip.ogg
4) /usr/local/bin/bell/sounds/default.ogg
5) /usr/local/bin/bell/sounds/Mallet.ogg
6) /usr/local/bin/bell/sounds/message.ogg
7) /usr/local/bin/bell/sounds/Positive.ogg
8) /usr/local/bin/bell/sounds/Rhodes.ogg
9) /usr/local/bin/bell/sounds/Slick.ogg
'a' to hear to all files, use number to hear a single file, 
'u' to update last single file heard as new default, or 'q' to quit:

Код

#! /bin/bash

# NAME: bell-select-menu
# PATH: /usr/local/bin
# DESC: Present menu of bell sounds to listen to all, listen to one and update default.
# CALL: bell-select-menu
# DATE: Created Oct 1, 2016.

echo "The following /usr/local/bin/bell/sounds were found"

# set the prompt used by select, replacing "#?"
PS3="'a' to hear to all files, use number to hear a single file, 
'u' to update last single file heard as new default, or 'q' to quit: "

lastfile="none"

# allow the user to choose a file
select filename in /usr/local/bin/bell/sounds/*.ogg

do

    # leave the loop if the user types 'q'
    if [[ "$REPLY" == q ]]; then break; fi

    # play all if the user types 'a'
    if [[ "$REPLY" == a ]] 
    then 
        playall-bells
        continue
    fi

    # update last file name as new default if the user types 'u'
    if [[ "$REPLY" == u ]]
    then
        if [[ "$lastfile" == none ]]
        then
            echo "No file was selected."
            break
        fi
        echo "$lastfile selected"
        cp $lastfile /usr/local/bin/bell/sounds/default.ogg
        load-default-bell
        break
    fi

    # complain if no file was selected, and loop to ask again
    if [[ "$filename" == "" ]]
    then
        echo "'$REPLY' is not a valid number"
        continue
    else
        lastfile="$filename"
    fi

    # listen to the selected file
    ogg123 "$filename"

    # loop back to ask for another
    continue
done

Я основывал код ответа от AskUbuntu: Создайте меню удара на основе списка файлов (файлы карты к числам). Прокрутки меню от экрана как пользовательские опции неоднократно вводятся, хотя, таким образом, цикл должен быть скорректирован.

Самое ужасное меню в мире автоматически сгенерировано так, я не могу трудно кодировать строку ASCII, тянут символы на левых и правых сторонах. Я должен был бы назвать программу для переформатирования меню?

Объем меню сгенерирован единственной командой удара:

select filename in /usr/local/bin/bell/sounds/*.ogg

Я прочитал руководство Bash по select оператор, но не видит опций. Существует ли программа, которую можно назвать для массирования экрана?

Самую близкую вещь, которую я нашел, называют tput описанный здесь: linuxcommand.org/lc3_adv_tput, но я не уверен, практично ли это для этой проблемы.

Заранее спасибо :)

PS Это меню является одним из инструментов для избавлений от раздражающего звукового сигнала громкоговорителя в Терминале и gedit как описано здесь: Выключите МАТЕРИНСКУЮ ПЛАТУ/ДИНАМИК КОМПЬЮТЕРА "звуковой сигнал" в регрессии Ubuntu 16.04


Редактирование - слияние принятого ответа

Большое спасибо wjandrea для регистрации кода для чистки меню. До принятого ответа я добавил, что код для раскрашивает echo строки и PS3 (подсказка). Я также вставил цикл для перерисовки меню для предотвращения его прокручивающий от экрана. Я также вставил a reset очистить экран перед перекрашиванием. Это предотвращает больше и старую копию (иногда усеченный) и новую копию меню, появляющегося одновременно.

Новый взгляд меню

Цвета точно не представлены при копировании с терминального текстового вывода и вставке в AskUbuntu.

=====  Sound Files for Bell in /usr/local/bin/bell/sounds/  ====

1) Amsterdam.ogg  4) default.ogg    7) Positive.ogg
2) bell.ogg       5) Mallet.ogg     8) Rhodes.ogg
3) Blip.ogg       6) message.ogg    9) Slick.ogg

===========================  Options  ==========================

'a' to hear to all files, use number to hear a single file, 
'u' update last number heard as new bell default, 'q' to quit: 

Это - все, что появляется на экране теперь. Существует нет $ sudo bell-menu назовите оператор видимым. Никакая другая история предыдущих команд, введенных видимый.

Снимок экрана показывает цвета точно, и Вы видите, что экран был программно заменен пустым местом:

bell-menu

Новый код меню

#! /bin/bash

# NAME: bell-menu
# PATH: /usr/local/bin
# DESC: Present menu of bell sounds to listen to all, listen to one and update default.
# CALL: sudo bell-menu
# DATE: Created Oct 6, 2016.

# set the prompt used by select, replacing "#?"
PS3="
===========================  Options  ==========================

$(tput setaf 2)'$(tput setaf 7)a$(tput setaf 2)' to hear to all files, use $(tput setaf 7)number$(tput setaf 2) to hear a single file, 
'$(tput setaf 7)u$(tput setaf 2)' update last number heard as new bell default, '$(tput setaf 7)q$(tput setaf 2)' to quit: $(tput setaf 7)"

cd /usr/local/bin/bell/sounds/

# Prepare variables for loops
lastfile="none"
wend="n"

while true; do

  tput reset # Clear screen so multiple menu calls can't be seen.

  echo
  echo -e "===== \e[46m Sound Files for Bell in /usr/local/bin/bell/sounds/ \e[0m ===="
  echo

  # allow the user to choose a file
  select soundfile in *.ogg; do

    case "$REPLY" in
        q) # leave the loop if the user types 'q'
            wend="y" # end while loop
            break    # end do loop
            ;;
        a) # play all if the user types 'a'
            playall-bells
            break    # end do loop
            ;;
        u) # update last file name as new default if the user types 'u'
            if [[ "$lastfile" == none ]]; then
                echo "No file has been heard to update default. Listen first!"
                continue  # do loop repeat
            fi
            echo "$lastfile selected"
            cp "$lastfile" default.ogg
            load-default-bell
            wend="y" # end while loop
            break    # end do loop
            ;;
    esac

    # complain if no file was selected, and loop to ask again
    if [[ "$soundfile" == "" ]]; then
        echo "$REPLY: not a valid selection."
        continue    # repeat do loop
    else
        lastfile="$soundfile"
    fi

    # listen to the selected file
    canberra-gtk-play --file="$soundfile"

    # loop back to ask for another
    break
  done
  if [[ "$wend" == "y" ]]; then break; fi

done

Меню было переименовано от bell-select-menu кому: bell-menu. Поскольку это находится в /usr/local/bin с этим нужно назвать sudo bell-menu и комментарии были обновлены для отражения этого факта.

С небольшой работой самое ужасное меню в мире и теперь становятся и приемлемый взгляд (но не красивым) меню.

2
задан 13 April 2017 в 15:24

1 ответ

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

кроме того, я сделал $PS3 намного меньший; используемый canberra-gtk-play, потому что это предварительно установлено, где ogg123 не; и используемый case оператор вместо приблизительно if операторы.

я не мог протестировать его, потому что я работаю 14.04.

#! /bin/bash

# NAME: bell-select-menu
# PATH: /usr/local/bin
# DESC: Present menu of bell sounds to listen to all, listen to one and update default.
# CALL: bell-select-menu
# DATE: Created Oct 1, 2016.

# set the prompt used by `select`, replacing "#?"
PS3=": "

echo "Options:
a) Play all 
u) Set the last file played as the new default
q) Quit
The following sounds were found in /usr/local/bin/bell/sounds/:"

cd /usr/local/bin/bell/sounds/

# Prepare var for the loop.
lastfile="none"

# allow the user to choose a file
select soundfile in *.ogg; do

    case "$REPLY" in
        q) # leave the loop if the user types 'q'
            break
            ;;
        a) # play all if the user types 'a'
            playall-bells
            continue
            ;;
        u) # update last file name as new default if the user types 'u'
            if [[ "$lastfile" == none ]]; then
                echo "No file was selected."
                break
            fi
            echo "$lastfile selected"
            cp "$lastfile" default.ogg
            load-default-bell
            break
            ;;
    esac

    # complain if no file was selected, and loop to ask again
    if [[ "$soundfile" == "" ]]; then
        echo "$REPLY: not a valid selection."
        continue
    else
        lastfile="$soundfile"
    fi

    # listen to the selected file
    canberra-gtk-play --file="$soundfile"

    # loop back to ask for another
    continue
done
2
ответ дан 2 December 2019 в 03:44

Другие вопросы по тегам:

Похожие вопросы: