mirror of
https://github.com/LCTT/TranslateProject.git
synced 2025-03-27 02:30:10 +08:00
translated
This commit is contained in:
parent
822b252902
commit
144fd0702a
@ -1,181 +0,0 @@
|
||||
[#]: subject: "Bash Basics Series #2: Using Variables in Bash"
|
||||
[#]: via: "https://itsfoss.com/bash-use-variables/"
|
||||
[#]: author: "Abhishek Prakash https://itsfoss.com/author/abhishek/"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: "geekpi"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
Bash Basics Series #2: Using Variables in Bash
|
||||
======
|
||||
|
||||
In the first part of the Bash Basics Series, I briefly mentioned variables. It is time to take a detailed look at them in this chapter.
|
||||
|
||||
If you have ever done any kind of coding, you must be familiar with the term 'variable'.
|
||||
|
||||
If not, think of a variable as a box that holds up information, and this information can be changed over time.
|
||||
|
||||
Let's see about using them.
|
||||
|
||||
### Using variables in Bash shell
|
||||
|
||||
Open a terminal and use initialize a variable with a random number 4:
|
||||
|
||||
```
|
||||
var=4
|
||||
```
|
||||
|
||||
So now you have a variable named `var` and its value is `4`. Want to verify it? **Access the value of a variable by adding $ before the variable name**. It's called parameter expansion.
|
||||
|
||||
```
|
||||
[email protected]:~$ echo The value of var is $var
|
||||
The value of var is 4
|
||||
```
|
||||
|
||||
> 🚧 There must NOT be a space before or after`=`during variable initialization.
|
||||
|
||||
If you want, you can change the value to something else:
|
||||
|
||||
![Using variables in shell][1]
|
||||
|
||||
In Bash shell, a variable can be a number, character, or string (of characters including spaces).
|
||||
|
||||
![Different variable types in Bash shell][2]
|
||||
|
||||
> 💡 Like other things in Linux, the variable names are also case-sensitive. They can consist of letters, numbers and the underscore "_".
|
||||
|
||||
### Using variables in Bash scripts
|
||||
|
||||
Did you notice that I didn't run a shell script to show the variable examples? You can do a lot of things in the shell directly. When you close the terminal, those variables you created will no longer exist.
|
||||
|
||||
However, your distro usually adds global variables so that they can be accessed across all of your scripts and shells.
|
||||
|
||||
Let's write some scripts again. You should have the script directory created earlier but this command will take care of that in either case:
|
||||
|
||||
```
|
||||
mkdir -p bash_scripts && cd bash_scripts
|
||||
```
|
||||
|
||||
Basically, it will create `bash_scripts` directory if it doesn't exist already and then switch to that directory.
|
||||
|
||||
Here. let's create a new script named `knock.sh` with the following text.
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
echo knock, knock
|
||||
echo "Who's there?"
|
||||
echo "It's me, $USER"
|
||||
```
|
||||
|
||||
Change the file permission and run the script. You learned it in the previous chapter.
|
||||
|
||||
Here's what it produced for me:
|
||||
|
||||
![Using global variable in Bahs script][3]
|
||||
|
||||
**Did you notice how it added my name to it automatically?** That's the magic of the global variable $USER that contains the username.
|
||||
|
||||
You may also notice that I used the " sometimes with echo but not other times. That was deliberate. [Quotes in bash][4] have special meanings. They can be used to handle white spaces and other special characters. Let me show an example.
|
||||
|
||||
### Handling spaces in variables
|
||||
|
||||
Let's say you have to use a variable called `greetings` that has the value `hello and welcome`.
|
||||
|
||||
If you try initializing the variable like this:
|
||||
|
||||
```
|
||||
greetings=Hello and Welcome
|
||||
```
|
||||
|
||||
You'll get an error like this:
|
||||
|
||||
```
|
||||
Command 'and' not found, but can be installed with:
|
||||
sudo apt install and
|
||||
```
|
||||
|
||||
This is why you need to use either single quotes or double quotes:
|
||||
|
||||
```
|
||||
greetings="Hello and Welcome"
|
||||
```
|
||||
|
||||
And now you can use this variable as you want.
|
||||
|
||||
![Using spaces in variable names in bash][5]
|
||||
|
||||
### Assign the command output to a variable
|
||||
|
||||
Yes! You can store the output of a command in a variable and use them in your script. It's called command substitution.
|
||||
|
||||
```
|
||||
var=$(command)
|
||||
```
|
||||
|
||||
Here's an example:
|
||||
|
||||
```
|
||||
[email protected]:~$ today=$(date +%D)
|
||||
[email protected]:~$ echo "Today's date is $today"
|
||||
Today's date is 06/19/23
|
||||
[email protected]:~$
|
||||
```
|
||||
|
||||
![Command substitution in bash][6]
|
||||
|
||||
The older syntax used backticks instead of $() for the command substitution. While it may still work, you should use the new, recommended notation.
|
||||
|
||||
> 💡 Variables change the value unless you declare a 'constant' variable like this:`readonly pi=3.14`. In this case, the value of variable`pi`cannot be changed because it was declared`readlonly`.
|
||||
|
||||
### 🏋️ Exercise time
|
||||
|
||||
Time to practice what you learned. Here are some exercise to test your learning.
|
||||
|
||||
**Exercise 1**: Write a bash script that prints your username, present working directory, home directory and default shell in the following format.
|
||||
|
||||
```
|
||||
Hello, there
|
||||
My name is XYZ
|
||||
My current location is XYZ
|
||||
My home directory is XYZ
|
||||
My default shell is XYZ
|
||||
```
|
||||
|
||||
**Hint**: Use global variables $USER, $PWD, $HOME and $SHELL.
|
||||
|
||||
**Exercise 2:** Write a bash script that declares a variable named `price`. Use it to get the output in the following format:
|
||||
|
||||
```
|
||||
Today's price is $X
|
||||
Tomorrow's price is $Y
|
||||
```
|
||||
|
||||
Where X is the initial value of the variable `price` and it is doubled for tomorrow's prices.
|
||||
|
||||
**Hint**: Use / to escape the special character $.
|
||||
|
||||
The answers to the exercises can be discussed in this dedicated thread in the community.
|
||||
|
||||
In the next chapter of the Bash Basics Series, you'll see how to make the bash scripts interactive by passing arguments and accepting user inputs.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://itsfoss.com/bash-use-variables/
|
||||
|
||||
作者:[Abhishek Prakash][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://itsfoss.com/author/abhishek/
|
||||
[b]: https://github.com/lkxed/
|
||||
[1]: https://itsfoss.com/content/images/2023/06/Using-variables-in-shell.png
|
||||
[2]: https://itsfoss.com/content/images/2023/06/bash-variables-types.png
|
||||
[3]: https://itsfoss.com/content/images/2023/06/using-global-variable-bash-script.png
|
||||
[4]: https://linuxhandbook.com:443/quotes-in-bash/
|
||||
[5]: https://itsfoss.com/content/images/2023/06/using-spaces-in-bash-variable.png
|
||||
[6]: https://itsfoss.com/content/images/2023/06/command-substitue-bash-variable.png
|
@ -0,0 +1,183 @@
|
||||
[#]: subject: "Bash Basics Series #2: Using Variables in Bash"
|
||||
[#]: via: "https://itsfoss.com/bash-use-variables/"
|
||||
[#]: author: "Abhishek Prakash https://itsfoss.com/author/abhishek/"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: "geekpi"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
Bash 基础知识系列 #2:在 Bash 中使用变量
|
||||
======
|
||||
|
||||
在 Bash 基础知识系列的第一部分中,我简要提到了变量.现在是时候在本章中详细了解它们了。
|
||||
|
||||
如果你曾经进行过任何类型的编码,你一定熟悉术语“变量”。
|
||||
|
||||
如果没有,请将变量视为保存信息的盒子,并且该信息可以随着时间的推移而改变。
|
||||
|
||||
让我们看看如何使用它们。
|
||||
|
||||
### 在 Bash shell 中使用变量
|
||||
|
||||
打开终端并使用随机数 4 初始化变量:
|
||||
|
||||
```
|
||||
var=4
|
||||
```
|
||||
|
||||
现在你有一个名为 `var` 的变量,它的值为 `4`.想验证一下吗? **通过在变量名前添加 $ 来访问变量的值**.这称为参数扩展。
|
||||
|
||||
```
|
||||
[abhishek@itsfoss]:~$ echo The value of var is $var
|
||||
The value of var is 4
|
||||
```
|
||||
|
||||
> 🚧 变量初始化时 `=` 前后不能有空格。
|
||||
|
||||
如果需要,你可以将该值更改为其他值:
|
||||
|
||||
![Using variables in shell][1]
|
||||
|
||||
在 Bash shell 中,变量可以是数字、字符或字符串(包括空格在内的字符)。
|
||||
|
||||
![Different variable types in Bash shell][2]
|
||||
|
||||
> 💡 与 Linux 中的其他事物一样,变量名称也区分大小写.它们可以由字母、数字和下划线 “\_” 组成。
|
||||
|
||||
|
||||
### 在 Bash 脚本中使用变量
|
||||
|
||||
你是否注意到我没有运行 shell 脚本来显示变量示例? 你可以直接在 shell 中做很多事情.当你关闭终端时,你创建的那些变量将不再存在。
|
||||
|
||||
但是,你的发行版通常会添加全局变量,以便可以在所有脚本和 shell 中访问它们。
|
||||
|
||||
让我们再写一些脚本.你应该之前创建了脚本目录,但无论哪种情况,此命令都会处理该目录:
|
||||
|
||||
```
|
||||
mkdir -p bash_scripts && cd bash_scripts
|
||||
```
|
||||
|
||||
基本上,如果 `bash_scripts` 目录尚不存在,它将创建它,然后切换到该目录。
|
||||
|
||||
这里让我们使用以下文本创建一个名为 `knock.sh` 的新脚本。
|
||||
|
||||
```
|
||||
#!/bin/bash
|
||||
|
||||
echo knock, knock
|
||||
echo "Who's there?"
|
||||
echo "It's me, $USER"
|
||||
```
|
||||
|
||||
更改文件权限并运行脚本.你在上一章中已经学到了。
|
||||
|
||||
这是它为我生成的内容:
|
||||
|
||||
![Using global variable in Bahs script][3]
|
||||
|
||||
**你是否注意到它如何自动将我的名字添加到其中?** 这就是包含用户名的全局变量 $USER 的魔力。
|
||||
|
||||
你可能还注意到,我有时将 " 与 echo 一起使用,但其他时候则不使用。这是故意的。[bash 中的引号][4] 有特殊含义。它们可用于处理空格和其他特殊字符。让我展示一个 例子。
|
||||
|
||||
### 处理变量中的空格
|
||||
|
||||
Let's say you have to use a variable called `greetings` that has the value `hello and welcome`.
|
||||
假设你必须使用一个名为 `greetings` 的变量,其值为 `hello and welcome`。
|
||||
|
||||
如果你尝试像这样初始化变量:
|
||||
|
||||
```
|
||||
greetings=Hello and Welcome
|
||||
```
|
||||
|
||||
你会得到这样的错误:
|
||||
|
||||
```
|
||||
Command 'and' not found, but can be installed with:
|
||||
sudo apt install and
|
||||
```
|
||||
|
||||
这就是为什么你需要使用单引号或双引号:
|
||||
|
||||
```
|
||||
greetings="Hello and Welcome"
|
||||
```
|
||||
|
||||
现在你可以根据需要使用该变量。
|
||||
|
||||
![Using spaces in variable names in bash][5]
|
||||
|
||||
### 将命令输出分配给变量
|
||||
|
||||
是的! 你可以将命令的输出存储在变量中并在脚本中使用它们.这称为命令替换。
|
||||
|
||||
```
|
||||
var=$(command)
|
||||
```
|
||||
|
||||
这是一个例子:
|
||||
|
||||
```
|
||||
[abhishek@itsfoss]:~$ today=$(date +%D)
|
||||
[abhishek@itsfoss]:~$ echo "Today's date is $today"
|
||||
Today's date is 06/19/23
|
||||
[abhishek@itsfoss]:~$
|
||||
```
|
||||
|
||||
![Command substitution in bash][6]
|
||||
|
||||
旧语法使用反引号而不是 $() 进行命令替换.虽然它可能仍然有效,但你应该使用新的推荐符号。
|
||||
|
||||
> 💡 变量会更改值,除非你声明一个“常量”变量,如下所示:`readonly pi=3.14`.在这种情况下,变量 `pi` 的值无法更改,因为它被声明为 `readlonly`。
|
||||
|
||||
### 🏋️ 练习时间
|
||||
|
||||
是时候练习你所学到的东西了.这里有一些练习来测试你的学习情况。
|
||||
|
||||
**练习 1**:编写一个 bash 脚本,以以下格式打印你的用户名、当前工作目录、主目录和默认 shell。
|
||||
|
||||
```
|
||||
Hello, there
|
||||
My name is XYZ
|
||||
My current location is XYZ
|
||||
My home directory is XYZ
|
||||
My default shell is XYZ
|
||||
```
|
||||
|
||||
**提示**:使用全局变量 $USER、$PWD、$HOME 和 $SHELL。
|
||||
|
||||
**练习 2:** 编写一个 bash 脚本,声明一个名为 `price` 的变量.使用它来获取以下格式的输出:
|
||||
|
||||
```
|
||||
Today's price is $X
|
||||
Tomorrow's price is $Y
|
||||
```
|
||||
|
||||
其中 X 是变量 `price` 的初始值,并且明天价格翻倍。
|
||||
|
||||
**提示**:使用 / 转义特殊字符 $。
|
||||
|
||||
练习的答案可以在社区的这个专用帖子中讨论。
|
||||
|
||||
在 Bash 基础知识系列的下一章中,你将了解如何通过传递参数和接受用户输入来使 bash 脚本具有交互性。
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://itsfoss.com/bash-use-variables/
|
||||
|
||||
作者:[Abhishek Prakash][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[geekpi](https://github.com/geekpi)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://itsfoss.com/author/abhishek/
|
||||
[b]: https://github.com/lkxed/
|
||||
[1]: https://itsfoss.com/content/images/2023/06/Using-variables-in-shell.png
|
||||
[2]: https://itsfoss.com/content/images/2023/06/bash-variables-types.png
|
||||
[3]: https://itsfoss.com/content/images/2023/06/using-global-variable-bash-script.png
|
||||
[4]: https://linuxhandbook.com:443/quotes-in-bash/
|
||||
[5]: https://itsfoss.com/content/images/2023/06/using-spaces-in-bash-variable.png
|
||||
[6]: https://itsfoss.com/content/images/2023/06/command-substitue-bash-variable.png
|
Loading…
Reference in New Issue
Block a user