【问题标题】:Bash Linux - call function in a if statement [duplicate]Bash Linux - 在 if 语句中调用函数 [重复]
【发布时间】:2020-03-30 13:46:28
【问题描述】:

我可能有一些棘手的问题

如何在 bash 的 if 语句中调用定义的函数?

看看我的例子:

#!/bin/bash -x
Variable_A=xyz

function_x() {

echo "hello everyone"
}

#here I want to define a if statement after the function
if Variable_A == working;then
function_x()

#here I have a while for the parameters in bash example:
while [[ $# -gt 0 ]]
do
key="$1"
    case $key in
        -s|--status)
        Variable_A="$2"
        shift
        shift
        ;;
    esac
done

所以我的想法是,当我运行脚本时,我们称它为 test.sh,它会在 bash 中运行脚本 exp:

./test.sh working

我不知道如何创建这样的东西,也许你们中的一些人可以帮助我。

提前谢谢你

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    您的if 应如下所示:

    #here I want to define a if statement after the function
    if [ "$Variable_A" = "working" ]
    then
      function_x
    fi
    

    您需要以 fi 结束每个 if 语句,并且在没有 () 的情况下调用函数。
    https://www.thegeekdiary.com/bash-if-loop-examples-if-then-fi-if-then-elif-fi-if-then-else-fi/

    关于if 语句的另一个重要说明。 [] 前后需要一个空格。

    您的if 逻辑也应该在读取脚本参数并设置Variable_A 之后。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    相关资源
    最近更新 更多