简体   繁体   中英

bash -bc curl comparing variables

pretty simple script but I am having issues with it. It will not compare the 2 variables, is this due to floating points or? I tried to use the | bc but still not working...

    #!/bin/bash

    x=$(curl -o /dev/null -s -w %{time_total}\\n  http://www.google.com) | bc
    y=.5 | bc

    if [[ $x -gt $y ]]; then 
        echo “fast”
    else
        echo “not as fast”
    fi

updated code to: #!/bin/bash

    x=$(curl -o /dev/null -s -w %{time_total}\\n  http://www.google.com)
    y=.5

    if (( $(bc <<<'$x > $y') )); then
        echo “fast”
    else
        echo “not as fast”
    fi

Receiving errors: (standard_in) 1: illegal character: $ (standard_in) 1: illegal character: $ “not as fast”

cmd | bc cmd | bc means "redirect the output of cmd into the utility bc . It is not an obscure shell syntax for declaring numbers.

For example,

y=.5 | bc

executes the command y=.5 (which sets a local variable named y to the string .5 ), which produces no output, and then feeds that into bc . Since bc receives no input, it produces no output. Moreover, the variable y disappears when the left-hand command terminates.

Similarly,

x=$(curl ...) | bc

sets a local variable named x to the output of the curl command (using command substitution syntax). Again, the assignment produces no output, bc receives no input and thus does nothing, and the x variable disappears.

If you remove |bc from both assignments, then you will at least have managed to set x and y . You could then use bc to compare the floating point values:

if (( $(bc <<<"$x > $y") )); then

Here the (( ... )) conditional computation is being used to test whether the numerical expression inside it is non-zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM