当前位置: 动力学知识库 > 问答 > 编程问答 >

linux - bash not recognizing double digit number

问题描述:

I have a script like this:

#!/bin/bash

let sleepCount=0

while [[ $sleepCount < 15 ]]; do

let sleepCount++

sleep 1

echo $sleepCount

done

I expected it to give a sequence of 1 to 15. However, it exited after giving 1 and 2. I changed the 15 to 5, then I got 1 to 5. So, it looks like bash is not recognizing double-digit number and is only taking the leading digit. So, how can I achieve my original purpose?

BTW, this is some version information of bash:

bash --version GNU bash, version 4.1.2(1)-release

(x86_64-redhat-linux-gnu)

网友答案:

use -lt instead of <

#!/bin/bash
    let sleepCount=0
    while [[ $sleepCount -lt 15 ]]; do
        let sleepCount++
        sleep 1
        echo $sleepCount
    done

lt checks if $sleepCount is less than 15

EDIT:

The < performs a string comparison. To be clear consider the following commands

$[[ 0 < 15 ]]
$ echo $?
0
$ [[ 1 < 15 ]]
$ echo $?
0
$ [[ 2 < 15 ]]
$ echo $?
1
$ [[ 3 < 15 ]]
$ echo $?
1
$ [[ 4 < 15 ]]
$ echo $?
1
$ [[ 44 < 15 ]]
$ echo $?
1
$ [[ 44 < 5 ]]
$ echo $?
0
$ [[ "a" < "b" ]]
$ echo $?
0
$ [[ "b" < "a" ]]
$ echo $?
1
网友答案:

Use An Arithmetic Expression

Instead of a conditional expression, you can use an arithmetic expression instead.

let sleepCount=0
while (( $sleepCount < 15 )); do
    let sleepCount++
    sleep 1
    echo $sleepCount
done
网友答案:

Your question has already been (well) answered. I'll just add that in your case you could benefit from a C-style for loop:

#!/bin/bash
for((sleepcount=1;sleepcount<=15;++sleepcount)); do
    sleep 1
    echo "$sleepcount"
done
分享给朋友:
您可能感兴趣的文章:
随机阅读: