在 bash 中的 if 语句中调用本地函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12633394/
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
Call a local function inside if Statement in bash
提问by user1629986
#!/bin/bash
if [ -z "" ]
then
echo "No argument supplied"
exit
fi
if [ ""="abc" ] ; then
abc
exit
fi
if [ "" = "def" ]; then
def
exit 1
fi
function abc()
{
echo "hello"
}
function def()
{
echo "hi"
}
Here abc is a function which has local definition. But Bash is giving error "./xyz.sh: line 10: abc: command not found". Please give me any Solution?
这里 abc 是一个具有局部定义的函数。但是 Bash 给出了错误“./xyz.sh: line 10: abc: command not found”。请给我任何解决方案?
回答by dogbane
All functions must be declared before they can be used, so move your declarations to the top.
所有函数在使用之前都必须声明,所以将你的声明移到顶部。
Also, you need to have a space on either side of the =in your string comparison test.
此外,您需要=在字符串比较测试中的两边各留一个空格。
The following script should work:
以下脚本应该可以工作:
#!/bin/bash
function abc()
{
echo "hello"
}
function def()
{
echo "hi"
}
if [ -z "" ]
then
echo "No argument supplied"
exit
fi
if [ "" = "abc" ] ; then
abc
exit
fi
if [ "" = "def" ]; then
def
exit 1
fi
回答by TaninDirect
I suspect there is a problem with your declaration of abc. If you provide the code for your script, we'll be more able to provide specific help, but here is an example of what I think you are trying to achive.
我怀疑你的 abc 声明有问题。如果您提供脚本的代码,我们将更有能力提供具体的帮助,但这里有一个我认为您正在努力实现的示例。
#!/bin/bash -x
abc(){
echo "ABC. bam!"
}
foo="bar"
if [ "$foo"="bar" ]; then
abc
else
echo "No bar for you"
fi

