как проверить, является ли входной аргумент сценария bash десятичным числом?

После выполнения команды fold выходные данные направляются в sed, а начало строки заменяется табуляцией. И вы можете управлять отступом с помощью команды «вкладки» до:

tabs 5
echo "A very long line that I want to fold on the word boundary and indent as well" | fold -s -w 20  | sed -e "s|^|\t|g"
     A very long line
     that I want to fold
     on the word
     boundary and indent
     as well
-4
20.11.2018, 14:56
2 ответа

Сравните его с самим собой, заставляя основание -десять интерпретаций. Как видно из руководства по арифметике оболочки:

Constants with a leading 0 are interpreted as octal numbers. A leading ‘0x’ or ‘0X’ denotes hexadecimal. Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. When specifying n, the digits greater than 9 are represented by the lowercase letters, the uppercase letters, ‘@’, and ‘_’, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35.

Следовательно, если это первый аргумент, вы можете сделать...

СНОВА ОТРЕДАКТИРОВАНО, ЧТОБЫ ПРИНЯТЬ ОТРИЦАТЕЛЬНЫЙ ВВОД

#!/bin/bash
b=${1#-}
if [[ $b =~ ^[0-9]+$ ]]; then                       #If it's all numbers
        a=$((10#$b))                                #create a base 10 version
        if [ "$a" == "$b" ]; then                   #if they LOOK the same...
                echo "$b is Base 10!"; exit 1; fi;  #It's base 10; exit.
fi
    echo "$b is not base 10"                        #If it has letters or $a and $b look different, it's not base 10.

Этот код примет любой ввод и сообщит вам, является ли он основанием 10 или нет. Аргумент сначала лишен отрицательного знака, а затем численно сравнивается с $a non -, потому что 012 -eq $ ((10 #012 )); но мы не хотим, чтобы сценарий сообщал нам, что это число с основанием десять, потому что это не так.

root@xxxx:~#./testing.sh -124124
124124 is Base 10!
root@xxxx:~#./testing.sh 58135
58135 is Base 10!
root@xxxx:~#./testing.sh aksjflkfj929148
aksjflkfj929148 is not Base 10
0
28.01.2020, 05:20

Вы можете использовать сопоставление с образцом (улучшить регулярное выражение, если вы не хотите принимать начальный 0):

if [[ $num =~ ^[+-]?[1-9][0-9]*$ ]]
then
echo Decimal
else
echo Not decimal
fi
1
28.01.2020, 05:20

Теги

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