Bash变量


文档摘要

Bash 变量 与任何其他编程语言一样,你也可以在 Bash 脚本中使用变量。不过,Bash 中没有数据类型的概念,一个变量既可以包含数字,也可以包含字符。 要为变量赋值,只需使用 符号: {notice} 请注意, 符号的前后不能有空格。 之后,要访问该变量,你需要使用 并按如下方式引用它: 将变量名用花括号括起来并不是必需的,但被认为是一种良好的编程习惯,我建议你尽可能使用花括号: 上面的代码会输出: as this is the value of our variable. Next, let's update our script and include a variable in it.

Bash 变量

与任何其他编程语言一样,你也可以在 Bash 脚本中使用变量。不过,Bash 中没有数据类型的概念,一个变量既可以包含数字,也可以包含字符。

要为变量赋值,只需使用 = 符号:

name="DevDojo"

{notice} 请注意,= 符号的前后不能有空格。

之后,要访问该变量,你需要使用 $ 并按如下方式引用它:

echo $name

将变量名用花括号括起来并不是必需的,但被认为是一种良好的编程习惯,我建议你尽可能使用花括号:

echo ${name}

上面的代码会输出:DevDojo as this is the value of our name variable.

Next, let's update our devdojo.sh script and include a variable in it.

Again, you can open the file devdojo.sh 使用你喜欢的文本编辑器打开文件,这里我使用 nano 来打开文件:

nano devdojo.sh

在文件中加入我们的 name 变量,并添加一条欢迎消息。现在文件看起来像这样:

#!/bin/bash name="DevDojo" echo "Hi there $name"

保存文件,并使用以下命令运行脚本:

./devdojo.sh

你将在屏幕上看到如下输出:

Hi there DevDojo

以下是文件中脚本的简要说明:

  • #!/bin/bash - At first, we specified our shebang.
  • name=DevDojo - Then, we defined a variable called name and assigned a value to it.
  • echo "Hi there $name" - Finally, we output the content of the variable on the screen as a welcome message by using echo

你还可以在文件中添加多个变量,如下所示:

#!/bin/bash name="DevDojo" greeting="Hello" echo "$greeting $name"

保存文件并再次运行:

./devdojo.sh

你将在屏幕上看到如下输出:

Hello DevDojo

请注意,你并不一定需要在每行末尾添加分号 ;。这与 JavaScript 等其他编程语言类似,两种写法都可以正常工作!

你还可以在 Bash 脚本之外的命令行中添加变量,并将它们作为参数读取:

./devdojo.sh Bobby buddy!

这个脚本接受两个参数 Bobbyand buddy! separated by space. In the devdojo.sh 文件的内容如下:

#!/bin/bash echo "Hello there" $1

$1 is the first input (Bobby) in the Command Line. Similarly, there could be more inputs and they are all referenced to by the $ sign and their respective order of input. This means that buddy! is referenced to using $2. Another useful method for reading variables is the $@ which reads all inputs.

So now let's change the devdojo.sh 文件,以便更好地理解:

#!/bin/bash echo "Hello there" $1 # $1 : first parameter echo "Hello there" $2 # $2 : second parameter echo "Hello there" $@ # $@ : all

对于以下命令:

./devdojo.sh Bobby buddy!

输出将是:

Hello there Bobby Hello there buddy! Hello there Bobby buddy!

免责声明
本文件由基于人工智能的机器翻译服务翻译而成。尽管我们力求翻译准确,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言版本的文件为准。对于关键信息,建议使用专业的人工翻译。对于因使用本翻译而产生的任何误解或误读,我们概不负责。


发布者: 作者: 转发
评论区 (0)
U