dan9er
dan9er

Reputation: 389

How to use a function with parameters in an if statement in Bash?

This is what I'm trying to do:

#!/bin/bash

check_for_int()
{
    if [ "$1" -eq "$1" ] 2>/dev/null
    then
        return 0
    else
        return 1
    fi
}

if [[check_for_int($1) == 1]]
    echo "FATAL: argument must be an integer!"
    exit 1
fi

# do stuff

However, no matter how I put it, shellcheck is complaining:

if [[ check_for_int($1) == 1 ]]; then
^-- SC1009: The mentioned parser error was in this if expression.
   ^-- SC1073: Couldn't parse this test expression.
               ^-- SC1036: '(' is invalid here. Did you forget to escape it?
               ^-- SC1072: Expected "]". Fix any mentioned problems and try again.

I have no idea why this isn't working...

Upvotes: 2

Views: 2196

Answers (2)

Darby_Crash
Darby_Crash

Reputation: 446

Like asked from title this is a working solution (Updated with better method used from @usr of pass arguments to a function in the if statement)

#!/bin/bash

check_for_int () {
    if [[ $1 =~ ^\+?[0-9]+$ ]] || [[ $1 =~ ^\-?[0-9]+$ ]]; then
        return 0
    else
        return 1
    fi
}

if ! check_for_int "$1"; then
    echo "FATAL: argument must be an integer!"
    exit 1
else
    echo "${0}: ${1} is a integer!"
    exit 0
fi

NOTE:

This include positive and negative sign

"$var" -eq "$var" have some negative side: How do I test if a variable is a number in Bash?

OUTPUT

darby@Debian:~/Scrivania$ bash ex -+33
FATAL: argument must be an integer!
darby@Debian:~/Scrivania$ bash ex +33
ex: +33 is a integer!
darby@Debian:~/Scrivania$ bash ex -33
ex: -33 is a integer!
darby@Debian:~/Scrivania$ bash ex 3e33
FATAL: argument must be an integer!
darby@Debian:~/Scrivania$ bash ex '333 8'
FATAL: argument must be an integer!
darby@Debian:~/Scrivania$

Upvotes: 0

P.P
P.P

Reputation: 121397

The way you pass argument to check_for_int is not valid in bash. Modify it to:

if ! check_for_int "$1"; then
    echo "FATAL: argument must be an integer!"
    exit 1
fi

Upvotes: 4

Related Questions