读取字符串并转换为 INT (BASH)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38395450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:54:33  来源:igfitidea点击:

Read string and convert to INT (BASH)

stringbashshellscripting

提问by sjsam

i have a simple script in Bash wich read a number in a file and then compare it with a different threshholds. The output is this:

我在 Bash 中有一个简单的脚本,它读取文件中的一个数字,然后将它与不同的阈值进行比较。输出是这样的:

: integer expression expected
: integer expression expected
OK: 3

My code is this:

我的代码是这样的:

#!/bin/bash

wget=$(wget http://10.228.28.8/ -O /tmp/wget.txt 2>/dev/null)
output=$(cat /tmp/wget.txt | awk 'NR==6')
#output=7
echo $output

if [ $output -ge 11 ];then
    echo "CRITICAL: $output"
    exit 2
elif [ $output -ge 6 ] && [ $output -lt 11 ];then
    echo "WARNING: $output"
    exit 1
else
    echo "OK: $output"
    exit 0
fi

rm /tmp/wget.txt

I know what is the problem, i kown that im reading a string and i try to compare a int. But i dont know how can i do to read this file and convert the number to read in a int var..

我知道问题出在哪里,我知道我正在读取一个字符串,并尝试比较一个 int。但我不知道我该怎么做才能读取这个文件并将数字转换为读入 int var ..

Any ideas?

有任何想法吗?

Thanks.

谢谢。

回答by chepner

The problem occurs when $outputis the empty string; whether or not you quote the expansion (and you should), you'll get the integer expression required error. You need to handle the empty string explictly, with a default value of zero (or whatever default makes sense).

问题出现的时候$output是空字符串;无论您是否引用扩展(并且应该引用),您都会得到整数表达式所需的错误。您需要显式地处理空字符串,默认值为零(或任何有意义的默认值)。

wget=$(wget http://10.228.28.8/ -O /tmp/wget.txt 2>/dev/null)
output=$(awk 'NR==6' < /tmp/get.txt)
output=${output:-0}

if [ "$output" -ge 11 ];then
  echo "CRITICAL: $output"
  exit 2
elif [ "$output" -ge 6 ];then
  echo "WARNING: $output"
  exit 1
else
  echo "OK: $output"
  exit 0
fi

(If you reach the elif, you already know the value of $outputis less than 11; there's no need to check again.)

(如果到达elif,则已经知道 的值$output小于 11;无需再次检查。)



The problem also occurs, and is consistent with the error message, if outputends with a carriage return. You can remove that with

问题也出现了,和错误信息一致,如果output以回车结束。你可以用

output=${output%$'\r'}

回答by sjsam

There are a couple of suggestions from my side regarding your code.

我这边有一些关于您的代码的建议。

You could explicitly tell bash the outputis an integer

你可以明确地告诉 bash 这output是一个整数

declare -i output # See [1]

Change

改变

output=$(cat /tmp/wget.txt | awk 'NR==6') # See [2]

may be better written as

可能更好地写成

output=$(awk 'NR==6' /tmp/wget.txt )

Change

改变

if [ $output -ge 11 ]

to

if [ "0$output" -ge 11 ] # See [4]

or

或者

if (( output >= 11 )) # Better See [3]


References

参考

  1. Check bash [ declare ].
  2. Useless use of cat. Check [ this ]
  3. Quoting [ this ]answer :

    ((...))enable you to omit the dollar signs on integer and array variables and include spaces around operators for readability. Also empty variable automatically defaults to 0 in such a statement.

  4. The zero in the beginning of "0$output"help you deal with empty $output
  1. 检查 bash [声明]
  2. 用猫没用。检查[这个]
  3. 引用[this]答案:

    ((...))使您能够省略整数和数组变量上的美元符号,并在运算符周围包含空格以提高可读性。在这样的语句中,空变量也会自动默认为 0。

  4. 零开头"0$output"帮你处理空$output

Interesting
Useless use of catis a phrase that has been resounding in SO for long. Check [ this ]
[ @chepner ]has dealt with the empty outputfiasco using [ bash parameter expansion ]in his [ answer ], worth having a look at.

有趣
Useless use of cat是一个在 SO 中响彻很久的短语。检查[this]
[@chepner]在他的[answer] 中output使用[bash 参数扩展]处理了空惨败,值得一看。

回答by Manuel Alcocer

In BASH, It is a good idea to use double brackets for strings:

在 BASH 中,对字符串使用双括号是个好主意:

if [[ testing strings ]]; then
    <whatever>
else
    <whatever>
fi

Or double parenthesis for integers:

或整数的双括号:

if (( testing ints )); then
    <whatever>
else
    <whatever>
fi

For example try this:

例如试试这个:

var1="foo bar"
if [ $var1 == 'foo bar' ]; then
    echo "ok"
fi

Result:

结果:

$ bash: [: too many arguments

Now, this:

现在,这个:

var2="foo bar"
if [[ $a == "foo bar" ]]; then
    echo "ok"
fi

Result:

结果:

ok

For that, your code in BASH:

为此,您在 BASH 中的代码:

if [[ $output -ge 11 ]]; then
    echo "CRITICAL: $output"
    exit 2
elif [[ $output -ge 6 ]]; then
    echo "WARNING: $output"
    exit 1
else
    echo "OK: $output"
    exit 0
fi

回答by Manuel Alcocer

A simplified script:

一个简化的脚本:

#!/bin/bash

wget=$(wget http://10.228.28.8/ -O /tmp/wget.txt 2>/dev/null)
output=$(awk 'NR==6' </tmp/wget.txt )

output="$(( 10#${output/[^0-9]} + 0 ))"

(( output >= 11 )) && { echo "CRITICAL: $output"; exit 2; }
(( output >=  6 )) && { echo  "WARNING: $output"; exit 1; }
echo "OK: $output"

The key line to cleanup any input is:

清理任何输入的关键行是:

output="$(( 10#${output/[^0-9]} + 0 ))"

${output/[^0-9]}Will leave only digits from 0 to 9.

${output/[^0-9]}将只留下 0 到 9 的数字。

10#${output/[^0-9]}Will convert outputto a base 10 number.

10#${output/[^0-9]}将转换output为基数为 10 的数字。

That will correctly convert numbers like 0019

这将正确转换数字,如 0019

"$(( 10#${output/[^0-9]} + 0 ))"Will produce a zero for a missing value.

"$(( 10#${output/[^0-9]} + 0 ))"将为缺失值生成零。

Then the resulting number stored in output will be compared to limits and the corresponding output will be printed.

然后存储在输出中的结果数字将与限制进行比较,并打印相应的输出。