bash 'case' для классификации входных данных как не- и целых чисел

Básicamente, no puede recuperar su tarjeta SD si formatea su teléfono.
Android almacena la clave de cifrado de su tarjeta SD en la tienda de confianza, que básicamente se borra al restablecer la configuración de fábrica.
Debería poder formatear su tarjeta SD con gparted, pero antes tendría que eliminar la tabla de particiones y volver a crearla.
Además, no se debe confiar en la tarjeta SD y las unidades defectuosas son bastante comunes.

1
17.06.2019, 10:37
1 ответ

резюме:Спасибо

  • замораживание дляs/;&/;;&/
  • Фредди за правильный положительный -целочисленный шаблон (думаю, я только что получил ночную слепоту)

Я также добавил дополнительное предложение для обнаружения знаковых нулей и еще несколько тестов.

детали:

Сохраните этот улучшенный код в файл (, например. /tmp/integer_case_statement.sh), chmodи запустите:

#!/usr/bin/env bash

### Simple `bash` `case` statement to classify inputs as {positive|negative|zero|non-} integers.
### Trying extglob, since my previous integer-match patterns failed.
### Gotta turn that on before *function definition* per https://stackoverflow.com/a/34913651/915044
shopt -s extglob

declare input=''

### For `case` *patterns* (NOT regexps), see
### https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
function identify() {
    local -r it=${1}  # no quotes in case it's multiline
#    shopt -s extglob # can't do that here
    case ${it} in
        '')
            # empty string, no need for `if [[ -z...`
            >&2 echo 'ERROR: null arg'
            ;;
        [+-]0)
            >&2 echo 'ERROR: zero should not be signed'
            ;;
        ?(-|+)+([[:digit:]]))
            # it's an integer, so just say so and fallthrough
            >&2 echo 'DEBUG: int(it), fallthrough'
#            ;& # this only runs the next clause, thanks https://unix.stackexchange.com/users/30851/frostschutz
            ;;& # works
        -+([[:digit:]]))
            >&2 echo 'DEBUG: it < 0'
            ;;
        0)
            >&2 echo 'DEBUG: it == 0'
            echo '0'
            ;;
        ?(+)+([[:digit:]])) # thanks https://unix.stackexchange.com/users/332764/freddy
            >&2 echo 'DEBUG: it > 0'
            ;;
        *)
            >&2 echo 'DEBUG: !int(it)'
            ;;
    esac
} # end function identify

echo -e "'bash --version'==${BASH_VERSION}\n"

for input in \
    '' \
    '@#$%^&!' \
    'word' \
    'a
multiline
string' \
    '2.1' \
    '-3' \
    '+3' \
    '+0' \
    '0' \
    '-0' \
    '42' \
; do
    echo "identify '${input}'"
    identify "${input}"
    ret_val="${?}"
    if [[ "${ret_val}" -ne 0 ]] ; then
        >&2 echo "ERROR: retval='${ret_val}', exiting..."
        exit 3
    fi
    echo # newline
done

exit 0

На этой рабочей станции Debian приведенный выше вывод в настоящее время выводит:

'bash --version'==4.3.30(1)-release

identify ''
ERROR: null arg

identify '@#$%^&!'
DEBUG: !int(it)

identify 'word'
DEBUG: !int(it)

identify 'a
multiline
string'
DEBUG: !int(it)

identify '2.1'
DEBUG: !int(it)

identify '-3'
DEBUG: int(it), fallthrough
DEBUG: it < 0

identify '+3'
DEBUG: int(it), fallthrough
DEBUG: it > 0

identify '+0'
ERROR: zero should not be signed

identify '0'
DEBUG: int(it), fallthrough
DEBUG: it == 0
0

identify '-0'
ERROR: zero should not be signed

identify '42'
DEBUG: int(it), fallthrough
DEBUG: it > 0

Мы ценим вашу помощь!

1
28.01.2020, 00:08

Теги

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