bash 中变量声明和赋值的解耦
在这里猛击。我想编写一个脚本来声明多个变量,根据条件为它们分配不同的值,然后稍后使用它们(无论它们有条件地分配给什么):
#!/usr/bin/bash
$fizz
$buzz
$foo
if [ -z "$1" ]
then
fizz = "Jane Smith"
buzz = true
foo = 44
else
fizz = "John Smith"
buzz = false
foo = 31
fi
# now do stuff with fizz, buzz and foobar regardless of what their values are
当我运行此(bash myscript.sh
) 我收到错误。谁能发现我是否在任何地方有语法错误?提前致谢!
Bash here. I want to write a script that declares several variables, assigns them different values based on a conditional, and then uses them later on (whatever they were conditionally assigned to):
#!/usr/bin/bash
$fizz
$buzz
$foo
if [ -z "$1" ]
then
fizz = "Jane Smith"
buzz = true
foo = 44
else
fizz = "John Smith"
buzz = false
foo = 31
fi
# now do stuff with fizz, buzz and foobar regardless of what their values are
When I run this (bash myscript.sh
) I get errors. Can anyone spot if I have a syntax error anywhere? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的脚本存在一些问题:
仅包含
$variable
的行不是声明。它将被评估并扩展为空行(因为您的变量不存在)。Bash 不允许在
=
符号周围有空格在声明变量时,你实际上不需要这样做,因为如果变量不存在,bash 不会给你一个错误 - 它只会展开为空字符串。如果确实需要,可以使用
variable=
(=
后面不包含任何内容)将变量设置为空字符串。我建议将其更改为:
顺便说一下,请记住 bash 没有变量类型的概念 - 这些都是字符串,包括 false、
true
、44
等。There are a few problems with your script:
a line with just
$variable
is not a declaration. That will be evaluated and expanded to an empty line (since your variables don't exist).Bash does not allow spaces around the
=
signOn declaring variables, you don't really need to do that, since bash won't give you an error if an variable doesn't exist - it will just expand to an empty string. If you really need to, you can use
variable=
(with nothing after the=
) to set the variable to an empty string.I'd suggest changing it to this:
By the way, keep in mind that
bash
has no concept of variable types - these are all strings, includingfalse
,true
,44
, etc.