-2
#!/bin/bash

if [ "$1" == "" ] || [ "$2" == "" ] || [ "$3" == "" ]
    then
    echo This is empty or does not have all 3 parameters
    exit
elif [ "$1" -lt 0 ]
    then
    echo This aint a number
    exit

fi

Trying to run a script it is suppose first check if 3 positional parameters were entered, secondly check if the input are numbers and then display the largest. I got the first if statement to work but when I input a string for the first parameter to test the elif statement an error that says integer expected.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
djwalla
  • 1
  • 2
  • What string, exactly, are you entering? If it's not an integer, `[` can't use it to compare it to 0 using `-lt`. – chepner May 24 '20 at 13:12
  • Does this answer your question? [Integer expression expected error in shell script](https://stackoverflow.com/questions/19505227/integer-expression-expected-error-in-shell-script) – Quasímodo May 24 '20 at 13:20
  • when i run the script i put ./largest.sh Test 2 4, Using "Test" as a string see if the if statement in the script will work – djwalla May 24 '20 at 13:22

2 Answers2

0

you have to review the regex to check if string only contains digits, but you may try this:

#!/bin/bash

if [[ "$1" == "" ]] || [[ "$2" == "" ]] || [[ "$3" == "" ]]
    then
    echo "This is empty or does not have all 3 parameters"
    exit
elif ! [[ "$1" =~ ^[0-9]+$ ]]
    then
    echo "This aint a number"
    exit

fi

Note that [[ is actually a command/program that returns either 0 (true) or 1 (false). Any program that obeys the same logic (like all base utils, such as grep(1) or ping(1)) can be used as condition :

[[ -z STRING ]] #Empty string
[[ -n STRING ]] #Not empty string
[[ STRING == STRING ]]  #Equal
[[ STRING != STRING ]]  #Not Equal
[[ NUM -eq NUM ]]   #Equal
[[ NUM -ne NUM ]]   #Not equal
[[ NUM -lt NUM ]]   #Less than
[[ NUM -le NUM ]]   #Less than or equal
[[ NUM -gt NUM ]]   #Greater than
[[ NUM -ge NUM ]]   #Greater than or equal
[[ STRING =~ STRING ]]  #Regexp
(( NUM < NUM )) #Numeric conditions

also to check if the string contains only digits/numerical cheracter

[[ "$1" =~ ^[0-9]+$ ]]
Mahmoud Odeh
  • 942
  • 1
  • 7
  • 19
0

Please use a regex to check for number

#!/bin/bash
if [ $1 == "" ] || [ $2 == "" ] || [ $3 == "" ]
    then
    echo This is empty or does not have all 3 parameters
    exit
elif ! [[ $1 =~ ^[0-9]+$ ]]
    then
    echo This aint a number
    exit

fi
aruN
  • 161
  • 1
  • 6