Bash Script Compare and Run a Command

I have a shell script that gives me a txt file containing certain numbers. For instance, " 48 347 345 221 1029 3943 1245 7899 " . It only contains one line.

I want to trigger another shell script if one of those numbers exceeds 500. How can and compare the numbers and run the shell script? Thanks in advance

cat text.txt | if [ awk '{print $1}' -ge 500 ] then command.sh fi 
728x90

5 Answers Bash Script Compare and Run a Command

Using awk you can try this:

awk '{for(i=1;i<=NF;i++)if($i > 500)exit 1}' text.txt || ./command.sh

command.sh will be executed if the awk command exits with a non-zero code because of the || operator.

4 months ago

Throw the file contents into an array -

$: declare -a lst=( $(<text.txt) )

Then run a quick loop. If you want to run the command for each hit,

$: for n in "${lst[@]}"
do (( n > 500 )) && echo "command.sh # $n > 500"
done
command.sh # 1029 > 500
command.sh # 3943 > 500
command.sh # 1245 > 500
command.sh # 7899 > 500

If you just want a quick and dirty version,

$: for n in $(<text.txt); do (( n > 500 )) && command.sh; done

But I recommend you take the time to do the horribly complicated 2 steps, lol

If you want to run it just once if any number is over 500,

$: for n in "${lst[@]}"
do (( n > 500 )) && { echo "command.sh # $n > 500"; break; }
done
command.sh # 1029 > 500

And don't use cat like that. Try to never use cat like that.

If you *REALLY needed the file as input to an if, then do this:

if condition
then action
fi < text.txt 

4 months ago

You could use a simple for loop like this:

for n in $(cat test.txt)
do
    if [ $n -gt 500 ]; then
        something.sh
    fi
done

4 months ago

You can simply :

[[ "48 347 345 221 500" =~ ([ ][5-9][0-9][0-9]|[ ][1-9][0-9]{3,}) ]] && echo "Hi"
Hi
[[ "48 347 345 221" =~ ([ ][5-9][0-9][0-9]|[ ][1-9][0-9]{3,}) ]] && echo "Hi"

Hope this helps!

4 months ago

When you don't want to convert the sring to numbers, it will become nasty.
Look for a number with at least 4 digits (first not 0), or a number with 3 digits, first 5 or higher will give

# incorrect, includes 500 
grep -Eq "([1-9][0-9]|[5-9])[0-9][0-9]" text.txt && command.sh

This will also perform command.sh with number 500.

# incorrect, will fail for 5000 and 1500
grep -E "([1-9][0-9]|[5-9])[0-9][0-9]" text.txt | grep -qv 500 && command.sh

Fixing it becomes too complex. awk seems to be the most natural way.
An artificial way is converted the input to lines with one number and add an extra line with the border:

(echo "500 border"; tr ' '  '\n' < text.txt) |
   sort -n |
   tail -1 | 
   grep -qv "border" && command.sh

4 months ago