加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 01:29:05 所属栏目:安全 来源:网络整理
导读:我试图将参数传递给if语句中的函数,然后评估函数返回的内容(在bash中).我得到的结果是不正确的.你怎么做到这一点? #!/bin/bashfoo() { if [ $1 = "zero" ]; then echo "0" else echo "1"fi}arg="zero"if foo $arg -eq 0 ; then echo "entered 0"else echo "
我试图将参数传递给if语句中的函数,然后评估函数返回的内容(在bash中).我得到的结果是不正确的.你怎么做到这一点?
#!/bin/bash

foo() {
    if [ $1 = "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

不是预期的结果:

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

先感谢您.
?克里斯

您可以从函数返回结果,也可以使用$()来捕获其输出:
if [ $(foo $arg) -eq 0 ] ; then

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读