[英]What's the correct syntax for matching a variable in bash?
What's the correct syntax for matching a variable in bash? 在bash中匹配变量的正确语法是什么?
#!/bin/bash
# test1.sh
say_hello()
{
if [ "$1" = true ]; then
echo "hello"
else
echo "goodbye"
fi
}
say_hello
$ sh test1.sh true
> goodbye
If I remove the function, then it works as I expect it to. 如果删除该功能,则它将按预期运行。
#!/bin/bash
# test2.sh
if [ "$1" = true ]; then
echo "hello"
else
echo "goodbye"
fi
$ sh test2.sh true
> hello
I'm not sure what's wrong with the first script's syntax. 我不确定第一个脚本的语法有什么问题。
Solved and explained by you all, thank you for teaching me. 大家解决并解释了,谢谢您教我。
A function in bash has its own list of positional parameters - the arguments, you passed to the function. bash中的函数具有自己的位置参数列表-传递给函数的参数。
As in other programming languages, you need to pass the parameter from the main script to the function: 与其他编程语言一样,您需要将参数从主脚本传递给函数:
say_hello()
{
if [ "$1" = "true" ]; then
echo "hello"
else
echo "goodbye"
fi
}
say_hello "$1"
Btw, "true"
is just a string in this context, not a boolean value like in other programming languages. 顺便说一句,在这种情况下,
"true"
只是一个字符串 ,而不是其他编程语言中的布尔值 。 I would quote it, simply to express that. 我只想表达这一点。
Another thing, you are using #!/bin/bash
in the shebang line, but you call the script using sh script.sh
. 另一件事,您在shebang行中使用
#!/bin/bash
,但是使用sh script.sh
调用脚本。 While /bin/sh
is a link to /bin/bash
in some systems, it does not necessarily need to be. 虽然
/bin/sh
在某些系统中是/bin/bash
的链接,但不一定必须如此。 Even then, bash will recognize that is has started as /bin/sh
and will run in compatibility mode. 即使这样,bash仍会识别出它已经以
/bin/sh
开头并且将以兼容模式运行。 If you want to call a script with bash , use bash script.sh
. 如果你想调用使用bash脚本,使用
bash script.sh
。
$1
is the first input argument to the script, but inside the scope of a function it is the first argument to that function. $1
是脚本的第一个输入参数,但在函数范围内,它是该函数的第一个参数。 So, this would work: 因此,这将起作用:
#!/bin/bash
# test1.sh
say_hello()
{
if [ "$1" = true ]; then
echo "hello"
else
echo "goodbye"
fi
}
say_hello "$1"
$ sh test1.sh true
> goodbye
Note that here we are passing the $1
argument along to the function. 请注意,这里我们将
$1
参数传递给函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.