如何在Bash的if语句中使用带参数的函数?

时间:2017-10-21 15:47:26

标签: bash shell

这就是我要做的事情:

#!/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

然而,无论我怎么说,shellcheck都在抱怨:

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.

我不知道为什么这不起作用......

2 个答案:

答案 0 :(得分:3)

将参数传递给check_for_int的方式在bash中无效。将其修改为:

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

答案 1 :(得分:0)

与标题中的问题一样,这是一个有效的解决方案(更新了使用@usr传递参数到if语句中函数的更好方法)

#!/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

注意:

这包括正面和负面的信号

<强>&#34; $变种&#34; -eq&#34; $ var&#34;有一些消极方面:How do I test if a variable is a number in Bash?

<强>输出

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$