在 bash 中的 if 语句中将参数传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14919819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:35:04  来源:igfitidea点击:

Passing arguments to a function within an if statement in bash

bashshellunix

提问by user1117603

I am trying to pass arguments to a function within an if statement and then evaluating what the function returns (in bash). The result I am getting is incorrect. How do you properly do this?

我试图在 if 语句中将参数传递给函数,然后评估函数返回的内容(在 bash 中)。我得到的结果不正确。你如何正确地做到这一点?

#!/bin/bash

foo() {
    if [  = "zero" ]; then
        echo "0"
    else 
        echo "1"
fi
}

arg="zero"
if foo $arg -eq 0 ; then
    echo "entered 0"
else
    echo "entered something else"
fi

arg="blah"
if foo $arg -eq 0 ; then
    echo "entered 0"
else
    echo "entered something else"
fi

Not the desired results:

不是想要的结果:

cknight@macbook:~/work$ ./test.sh
0
entered 0
1
entered 0

Thank you in advance. ~Chris

先感谢您。~克里斯

回答by cnicutar

You can either returna result from your function or use $()to capture its output:

您可以return从您的函数$()中获取结果或用于捕获其输出:

if [ $(foo $arg) -eq 0 ] ; then

回答by chepner

Are you sure you need your function to echo 0 or 1? It looks more like you want something like

你确定你需要你的函数来回显 0 或 1 吗?看起来更像是你想要的东西

foo() {
  if [  = "zero" ]; then
    return 0
  else 
    echo 1
  fi
}

# Or even just simply foo () { [  = "zero ]; }

arg="zero"
if foo $arg; then
    echo "entered 0"
else
    echo "entered something else"
fi

arg="blah"
if foo $arg; then
    echo "entered 0"
else
    echo "entered something else"
fi

回答by Karoly Horvath

Not sure what you want to do...

不知道你想做什么...

Your foo()function always returns with success, use return.

您的foo()函数总是成功返回,请使用return.

You pass to your foo()function a second and a third parameter -eq 0but they aren't used. Do you want to check the exit status? That's simply if foo $arg; then ..; fi.

您将foo()第二个和第三个参数传递给您的函数-eq 0,但未使用它们。是否要检查退出状态?那简直了if foo $arg; then ..; fi