string Bash:将字符串比较为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16264311/
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
Bash: comparing a string as an integer
提问by Universal Coder
I'm trying to test if the is Ubuntu version is supported or not, and in case if it is not, then I update source.list in APT folder
我正在尝试测试是否支持 Ubuntu 版本,如果不支持,则更新 APT 文件夹中的 source.list
I know that I can't use <>
within [[ ]]
, so I tried [( )]
, tried []
, and even tried to use a regexp is there and "-" in variable, but it did not work, because it could not find "file: 76".
我知道我不能<>
在[[ ]]
inside 中使用,所以我尝试过[( )]
,尝试过[]
,甚至尝试过使用正则表达式,并且在变量中使用“-”,但它没有用,因为它找不到“文件:76”。
How should I write the comparison to work?
我应该如何写比较工作?
My code:
我的代码:
#!/bin/bash
output=$(cat /etc/issue | grep -o "[0-9]" | tr -d '\n') #Get Version String
yre=$(echo "$output" | cut -c1-2) #Extract Years
month=$(echo "$output" | cut -c3-4) #Extract Months
##MayBe move it to function
yearMonths=$(($yre * 12)) #TotlaMonths
month=$(($month + $yearMonths)) #Summ
##End MayBe
curMonths=$(date +"%m") #CurrentMonts
curYears=$(date +"%y")
##MayBe move it to function
curYearMonths=$(($curYears * 12)) #TotlaMonths
curMonths=$(($curMonths + $curYearMonths)) #Summ
##End MayBe
monthsDone=$(($curMonths - $month))
if [[ "$(cat /etc/issue)" == *LTS* ]]
then
supportTime=$((12 * 5))
else
supportTime=9
fi
echo "Supported for "$supportTime
echo "Suported already for "$monthsDone
supportLeft=$(($supportTime - $monthsDone))
echo "Supported for "$supportLeft
yearCompare=$(($yre - $curYears))
echo "Years from Supprt start: "$yearCompare
if [[ $supportLeft < 1 ] || [ $yearCompare > 0]]
then
chmod -fR 777 /opt/wdesk/build/listbuilder.sh
wget -P /opt/wdesk/build/ "https://placeofcode2wget.dev/listbuilder.sh"
sh /opt/wdesk/build/listbuilder.sh
else
echo "Still Supported"
fi
采纳答案by janos
Like this:
像这样:
[[ $supportLeft -lt 1 || $yearCompare -gt 0 ]]
You can find these and other related operators in man test
您可以在 man test
回答by mmrtnt
Not sure if this is any help, but this question was high in Google when I searched for "compare string to int in bash"
不确定这是否有帮助,但是当我搜索“将字符串与 bash 中的 int 进行比较”时,这个问题在 Google 中很高
You can "cast" a string to an int in bash by adding 0
您可以通过添加 0 将字符串“强制转换”为 bash 中的 int
NUM="99"
NUM=$(($NUM+0))
This works great if you have to deal with NULLs as well
如果您还必须处理 NULL,这很有效
NUM=""
NUM=$(($NUM+0))
Make sure there aren't any spaces in the string!
确保字符串中没有任何空格!
NUM=`echo $NUM | sed -e 's/ //g'`
(Tested on Solaris 10)
(在 Solaris 10 上测试)
回答by Lev Levitsky
This seems to work:
这似乎有效:
if (( $supportLeft < 1 )) || (( $yearCompare > 0 ))
or
或者
if (( $supportLeft < 1 || $yearCompare > 0 ))