bash 中变量声明和赋值的解耦

发布于 2025-01-10 20:55:29 字数 402 浏览 0 评论 0原文

在这里猛击。我想编写一个脚本来声明多个变量,根据条件为它们分配不同的值,然后稍后使用它们(无论它们有条件地分配给什么):

#!/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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2025-01-17 20:55:29

您的脚本存在一些问题:

  1. 仅包含 $variable 的行不是声明。它将被评估并扩展为空行(因为您的变量不存在)。

  2. Bash 不允许在 = 符号周围有空格

在声明变量时,你实际上不需要这样做,因为如果变量不存在,bash 不会给你一个错误 - 它只会展开为空字符串。如果确实需要,可以使用 variable== 后面不包含任何内容)将变量设置为空字符串。

我建议将其更改为:

#!/usr/bin/env bash

if [ -z "$1" ]
then
  fizz="Jane Smith"
  buzz=true
  foo=44
else
  fizz="John Smith"
  buzz=false
  foo=31
fi

顺便说一下,请记住 bash 没有变量类型的概念 - 这些都是字符串,包括 false、true44 等。

There are a few problems with your script:

  1. 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).

  2. Bash does not allow spaces around the = sign

On 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:

#!/usr/bin/env bash

if [ -z "$1" ]
then
  fizz="Jane Smith"
  buzz=true
  foo=44
else
  fizz="John Smith"
  buzz=false
  foo=31
fi

By the way, keep in mind that bash has no concept of variable types - these are all strings, including false, true, 44, etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文