gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:59:33 24 4
gpt4 key购买 nike

我试图在 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

关于bash - 在 bash 中的 if 语句中将参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14919819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com