Bash:将字符串作为整数进行比较

Uni*_*der 12 string bash if-statement compare

我正在尝试测试是否支持Ubuntu版本,如果不支持,那么我在APT文件夹中更新source.list

我知道我不能<>在内部使用[[ ]],所以我尝试过[( )],尝试过[],甚至尝试使用正则表达式和变量中的" - ",但它不起作用,因为它找不到"file:76".

我应该如何编写比较工作?

我的代码:

#!/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
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 10

像这样:

[[ $supportLeft -lt 1 || $yearCompare -gt 0 ]]
Run Code Online (Sandbox Code Playgroud)

您可以在中找到这些和其他相关的运营商 man test

  • 你需要在`0`和`]]`之间留一个空格 (2认同)
  • 除非这是'bash` 4中的新内容,否则我很确定语法是完全错误的......你不能把`[[`with`]`配对...... (2认同)

Lev*_*sky 5

这似乎有效:

if (( $supportLeft < 1 )) || (( $yearCompare > 0 ))
Run Code Online (Sandbox Code Playgroud)

或者

if (( $supportLeft < 1 || $yearCompare > 0 ))
Run Code Online (Sandbox Code Playgroud)


mmr*_*tnt 5

不知道这是否有帮助,但是当我搜索“比较字符串与bash中的int”时,这个问题在Google中是很高的

您可以通过添加0将字符串“投射”到bash中的int

NUM="99"
NUM=$(($NUM+0))
Run Code Online (Sandbox Code Playgroud)

如果您还必须处理NULL,这将非常有用

NUM=""
NUM=$(($NUM+0))
Run Code Online (Sandbox Code Playgroud)

确保字符串中没有空格!

NUM=`echo $NUM | sed -e 's/ //g'`
Run Code Online (Sandbox Code Playgroud)

(在Solaris 10上测试)