bash变量里包含变量_如何在Bash中使用变量

bash变量里包含变量

bash变量里包含变量

A Linux terminal with green text on a laptop.
Fatmawati Achmad Zaenuri/Shutterstock Fatmawati Achmad Zaenuri / Shutterstock

Variables are vital if you want to write scripts and understand what that code you’re about to cut and paste from the web will do to your Linux computer. We’ll get you started!

如果您想编写脚本并了解要从网上剪切和粘贴的代码将对Linux计算机执行的操作,则变量至关重要。 我们将帮助您入门!

变数101 (Variables 101)

Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.

变量是表示字符串或数字值的命名符号。 当您在命令和表达式中使用它们时,会将它们视为您键入了它们所拥有的值而不是变量名。

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.

要创建变量,只需为其提供名称和值。 您的变量名应具有描述性,并提醒您它们所具有的价值。 变量名不能以数字开头,也不能包含空格。 但是,可以从下划线开始。 除此之外,您还可以混合使用大小写字母数字字符。

例子 (Examples)

Here, we’ll create five variables. The format is to type the name, the equals sign =, and the value. Note there isn’t a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

在这里,我们将创建五个变量。 格式是键入名称,等号=和值。 请注意,等号前后没有空格。 给出一个可变的值通常被称为分配给变量。

We’ll create four string variables and one numeric variable, this_year:

我们将创建四个字符串变量和一个数字变量this_year:

me=Dave
my_boost=Linux
him=Popeye
his_boost=Spinach
this_year=2019
Five variables in a terminal window.

To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:

查看变量中保存的值,请使用echo命令。 每当引用变量包含的值时,都必须在变量名称前加一个美元符号$ ,如下所示:

echo $my_name
echo $my_boost
echo $this_year
The "echo" command displaying the values of variables in a terminal window.

Let’s use all of our variables at once:

让我们一次使用所有变量:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"
The "echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" command in a terminal window.

The values of the variables replace their names. You can also change the values of variables. To assign a new value to the variable, my_boost, you just repeat what you did when you assigned its first value, like so:

变量的值替换其名称。 您还可以更改变量的值。 要将新值分配给变量my_boost ,只需重复分配第一个值时所做的操作,如下所示:

my_boost=Tequila
The "my_boost=Tequila" variable in a terminal window.

If you re-run the previous command, you now get a different result:

如果重新运行前面的命令,则现在将得到不同的结果:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"
The echo "$my_boost is to $me as $his_boost is to $him (c) $this_year" command in a terminal window.

So, you can use the same command that references the same variables and get different results if you change the values held in the variables.

因此,如果更改变量中保存的值,则可以使用引用相同变量的相同命令并获得不同的结果。

We’ll talk about quoting variables later. For now, here are some things to remember:

稍后我们将讨论引用变量。 现在,这里要记住一些事情:

  • A variable in single quotes ' is treated as a literal string, and not as a variable.

    单引号'变量被视为文字字符串,而不是变量。

  • Variables in quotation marks "  are treated as variables.

    在引号中的变量"被视为变量。

  • To get the value held in a variable, you have to provide the dollar sign $.

    要获得变量中保存的值,必须提供美元符号$

  • A variable without the dollar sign $ only provides the name of the variable.

    没有美元符号$的变量仅提供变量的名称。

Correct and incorrect examples of referencing variables in a terminal window.

You can also create a variable that takes its value from an existing variable or number of variables. The following command defines a new variable called drink_of_the_Year, and assigns it the combined values of the my_boost and this_year variables:

您还可以创建一个变量,该变量从现有变量或多个变量中获取其值。 以下命令定义了一个名为drink_of_the_Year,的新变量drink_of_the_Year,并为其分配了my_boostthis_year变量的组合值:

drink_of-the_Year="$my_boost $this_year"
echo drink_of_the-Year
The drink_of-the_Year="$my_boost $this_year" command in a terminal window.

如何在脚本中使用变量 (How to Use Variables in Scripts)

Scripts would be completely hamstrung without variables. Variables provide the flexibility that makes a script a general, rather than a specific, solution.  To illustrate the difference, here’s a script that counts the files in the /dev directory.

没有变量,脚本将完全受阻。 变量提供了使脚本成为通用而非特定解决方案的灵活性。 为了说明不同之处,以下是一个脚本,该脚本对/dev目录中的文件进行计数。

Type this into a text file, and then save it as fcnt.sh (for “file count”):

将其键入文本文件,然后将其另存为fcnt.sh (用于“文件计数”):

#!/bin/bash

folder_to_count=/dev

file_count=$(ls $folder_to_count | wc -l)

echo $file_count files in $folder_to_count

Before you can run the script, you have to make it executable, as shown below:

在运行脚本之前,必须使其成为可执行文件,如下所示:

chmod +x fcnt.sh
"chmod +x fcnt.sh" in a terminal window.

Type the following to run the script:

输入以下内容以运行脚本:

./fcnt.sh
"./fcnt.sh" in a terminal window.

This prints the number of files in the /dev directory. Here’s how it works:

这将打印/dev目录中的文件数。 运作方式如下:

  • A variable called folder_to_count is defined, and it’s set to hold the string “/dev.”

    定义了一个名为folder_to_count的变量,并将其设置为容纳字符串“ / dev”。

  • Another variable, called file_count, is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ). Note there’s a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable. As far as the file_count variable is concerned, it’s passed a value to hold; it isn’t concerned with how the value was obtained.

    定义了另一个变量file_count 。 此变量从命令替换中获取其值。 这是括号$( )之间的命令短语。 请注意,在第一个括号之前有一个美元符号$ 。 该结构$( )计算括号内的命令,然后返回其最终值。 在此示例中,该值已分配给file_count变量。 就file_count变量而言,它传递了一个值来保存; 它与如何获得价值无关。

  • The command evaluated in the command substitution performs an ls file listing on the directory in the folder_to_count variable, which has been set to “/dev.” So, the script executes the command “ls /dev.”

    在命令替换中评估的命令会在folder_to_count变量的目录中执行一个ls文件列表,该变量已设置为“ / dev”。 因此,脚本执行命令“ ls / dev”。

  • The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the “/dev” directory. This value is assigned to the file_count variable.

    该命令的输出通过管道传递到 wc命令。 -l (行数)选项使wc 计数 ls命令输出中的行数 。 由于每个文件都在单独的行中列出,因此这是“ / dev”目录中文件和子目录的数量。 此值分配给file_count变量。

  • The final line uses echo to output the result.

    最后一行使用echo输出结果。

But this only works for the “/dev” directory. How can we make the script work with any directory? All it takes is one small change.

但这仅适用于“ / dev”目录。 我们如何使脚本可以在任何目录下工作? 它所需要的只是一个小改变。

如何在脚本中使用命令行参数 (How to Use Command Line Parameters in Scripts)

Many commands, such as ls and wc, take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files, you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:

许多命令(例如lswc命令行参数。 这些为命令提供了信息,因此它知道您要执行的操作。 如果你想ls你的主目录的工作, 也显示隐藏文件 ,可以使用下面的命令,其中波浪~-a (all)选项是命令行参数:

ls ~ -a

Our scripts can accept command line parameters. They’re referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there’s a $0, as well, but that’s reserved to always hold the script.)

我们的脚本可以接受命令行参数。 第一个参数的引用为$1 ,第二个参数的引用为$1 $2 ,依此类推,第九个参数的引用为$1 $9 。 (实际上,也有一个$0 ,但这保留为始终保存该脚本。)

You can reference command line parameters in a script just as you would regular variables. Let’s modify our script, as shown below, and save it with the new name fcnt2.sh:

您可以像使用常规变量一样在脚本中引用命令行参数。 让我们修改脚本,如下所示,并用新名称fcnt2.sh保存它:

#!/bin/bash

folder_to_count=$1

file_count=$(ls $folder_to_count | wc -l)

echo $file_count files in $folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $1.

这次,为folder_to_count变量分配了第一个命令行参数$1

The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it’s not hardcoded to work only with “/dev.”

脚本的其余部分与以前完全一样。 现在,您的脚本已不再是特定的解决方案,而是通用的解决方案。 您可以在任何目录上使用它,因为它不是硬编码为仅与“ / dev”一起使用。

Here’s how you make the script executable:

这是使脚本可执行的方式:

chmod +x fcnt2.sh
"chmod +x fcnt2.sh" in a terminal window.

Now, try it with a few directories. You can do “/dev” first to make sure you get the same result as before. Type the following:

现在,尝试一些目录。 您可以先执行“ / dev”,以确保获得与以前相同的结果。 输入以下内容:

./fnct2.sh /dev
./fnct2.sh /etc
./fnct2.sh /bin
"./fnct2.sh /dev" in a terminal window.

You get the same result (207 files) as before for the “/dev” directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.

您将获得与“ / dev”目录相同的结果(207个文件)。 这令人鼓舞,您会获得其他每个命令行参数的特定于目录的结果。

To shorten the script, you could dispense with the variable, folder_to_count, altogether, and just reference $1 throughout, as follows:

为了缩短脚本,您可以完全省去变量folder_to_count ,并始终引用$1 ,如下所示:

#!/bin/bash 

file_count=$(ls $1  wc -l) 

echo $file_count files in $1

使用特殊变量 (Working with Special Variables)

We mentioned $0, which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it’s renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.

我们提到了$0 ,它始终设置为脚本的文件名。 这使您可以使用脚本来执行某些操作,例如正确重命名其名称。 这在日志记录情况下很有用,在这种情况下,您想知道添加条目的进程的名称。

The following are the other special preset variables:

以下是其他特殊的预设变量:

  • $#: How many command line parameters were passed to the script.

    $# :向脚本传递了多少命令行参数。

  • $@: All the command line parameters passed to the script.

    $ @ :传递给脚本的所有命令行参数。

  • $?: The exit status of the last process to run.

    $? :最后运行的进程的退出状态。

  • $$: The Process ID (PID) of the current script.

    $$ :当前脚本的进程ID(PID)。

  • $USER: The username of the user executing the script.

    $ USER :执行脚本的用户的用户名。

  • $HOSTNAME: The hostname of the computer running the script.

    $ HOSTNAME :运行脚本的计算机的主机名。

  • $SECONDS: The number of seconds the script has been running for.

    $ SECONDS :脚本已运行的秒数。

  • $RANDOM: Returns a random number.

    $ RANDOM :返回一个随机数。

  • $LINENO: Returns the current line number of the script.

    $ LINENO :返回脚本的当前行号。

You want to see all of them in one script, don’t you? You can! Save the following as a text file called, special.sh:

您想在一个脚本中看到所有这些内容,不是吗? 您可以! 将以下内容另存为名为special.sh的文本文件:

#!/bin/bash

echo "There were $# command line parameters"
echo "They are: $@"
echo "Parameter 1 is: $1"
echo "The script is called: $0"
# any old process so that we can report on the exit status
pwd
echo "pwd returned $?"
echo "This script has Process ID $$"
echo "The script was started by $USER"
echo "It is running on $HOSTNAME"
sleep 3
echo "It has been running for $SECONDS seconds"
echo "Random number: $RANDOM"
echo "This is line number $LINENO of the script"

Type the following to make it executable:

输入以下内容使其可执行:

chmod +x special.sh
"chmod +x special.sh" in a terminal window.

Now, you can run it with a bunch of different command line parameters, as shown below.

现在,您可以使用许多不同的命令行参数来运行它,如下所示。

"./special.sh alpha bravo charlie 56 2048 Thursday" in a terminal window.

环境变量 (Environment Variables)

Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.

Bash使用环境变量来定义和记录启动时创建的环境的属性。 Bash可以轻松访问这些保留信息,例如您的用户名,语言环境,历史文件可以保留的命令数量,默认编辑器等等。

To see the active environment variables in your Bash session, use this command:

要查看Bash会话中的活动环境变量,请使用以下命令:

env | less
The "env | less" command in a terminal window

If you scroll through the list, you might find some that would be useful to reference in your scripts.

如果您在列表中滚动,可能会发现一些有用的脚本来引用。

A list of active environment variables in a terminal window.

如何导出变量 (How to Export Variables)

When a script runs, it’s in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We’ll show you how to this with two scripts.

当脚本运行时,它在自己的进程中,并且在该进程之外无法看到其使用的变量。 如果要与脚本启动的另一个脚本共享变量,则必须导出该变量。 我们将通过两个脚本向您展示如何做到这一点。

First, save the following with the filename script_one.sh:

首先,使用文件名script_one.sh保存以下script_one.sh

#!/bin/bash

first_var=alpha
second_var=bravo

# check their values
echo "$0: first_var=$first_var, second_var=$second_var"

export first_var
export second_var

./script_two.sh

# check their values again
echo "$0: first_var=$first_var, second_var=$second_var"

This creates two variables, first_var and second_var, and it assigns some values. It prints these to the terminal window, exports the variables, and calls script_two.sh. When script_two.sh terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.

这将创建两个变量first_varsecond_var ,并分配一些值。 它将这些打印到终端窗口,导出变量,并调用script_two.sh 。 当script_two.sh终止,并且流程返回此脚本时,它将再次将变量输出到终端窗口。 然后,您可以查看它们是否更改。

The second script we’ll use is script_two.sh. This is the script that script_one.shcalls. Type the following:

我们将使用的第二个脚本是script_two.sh 。 这是script_one.sh调用的脚本。 输入以下内容:

#!/bin/bash

# check their values
echo "$0: first_var=$first_var, second_var=$second_var"

# set new values
first_var=charlie
second_var=delta

# check their values again
echo "$0: first_var=$first_var, second_var=$second_var"

This second script prints the values of the two variables, assigns new values to them, and then prints them again.

第二个脚本打印两个变量的值,为它们分配新值,然后再次打印它们。

To run these scripts, you have to type the following to make them executable:

要运行这些脚本,您必须输入以下内容以使其可执行:

chmod +x script_one.sh
chmod +x script_two.sh
"chmod +x script_one.sh" and "chmod +x script_two.sh" in a terminal window.

And now, type the following to launch script_one.sh:

现在,键入以下内容以启动script_one.sh

./script_one.sh
"./script_one.sh" in a terminal window.

This is what the output tells us:

这是输出告诉我们的:

  • script_one.sh prints the values of the variables, which are alpha and bravo.

    script_one.sh打印变量的值,即alpha和bravo。

  • script_two.sh prints the values of the variables (alpha and bravo) as it received them.

    script_two.sh在接收变量时会输出它们的值(alpha和bravo)。

  • script_two.sh changes them to charlie and delta.

    script_two.sh将它们更改为charlie和delta。

  • script_one.sh prints the values of the variables, which are still alpha and bravo.

    script_one.sh打印变量的值,它们仍然是alpha和bravo。

What happens in the second script, stays in the second script. It’s like copies of the variables are sent to the second script, but they’re discarded when that script exits. The original variables in the first script aren’t altered by anything that happens to the copies of them in the second.

在第二个脚本中发生的情况将保留在第二个脚本中。 就像变量的副本已发送到第二个脚本一样,但是当该脚本退出时,它们将被丢弃。 第一个脚本中的原始变量不会被第二个脚本中的副本所发生的任何更改。

如何引用变量 (How to Quote Variables)

You might have noticed that when scripts reference variables, they’re in quotation marks ". This allows variables to be referenced correctly, so their values are used when the line is executed in the script.

你可能已经注意到,当脚本引用变量,他们是在引号" 。这让变量被正确引用,所以当行执行脚本中使用它们的值。

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.

如果您分配给变量的值包含空格,则将它们分配给变量时,空格必须用引号引起来。 这是因为,默认情况下,Bash使用空格作为定界符。

Here’s an example:

这是一个例子:

site_name=How-To Geek
"site_name=How-To Geek" in a terminal window.

Bash sees the space before “Geek” as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing—not even the “How-To” text.

Bash将“ Geek”之前的空格视为新命令正在启动的指示。 它报告没有这样的命令,并放弃了这一行。 echo向我们显示site_name变量不包含任何内容,甚至不包含“操作方法”文本。

Try that again with quotation marks around the value, as shown below:

再次尝试使用该值周围的引号,如下所示:

site_name="How-To Geek"
site_name="How-To Geek" in a terminal window.

This time, it’s recognized as a single value and assigned correctly to the site_name variable.

这次,它将被识别为单个值,并已正确分配给site_name变量。

回声是你的朋友 (echo Is Your Friend)

It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.

习惯于命令替换,引用变量以及记住何时包括美元符号可能需要一些时间。

Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what’s going to happen is what you want. You can also catch any mistakes you might have made in the syntax.

在按Enter键并执行一行Bash命令之前,请在其前面使用echo进行尝试。 这样,您可以确保将要发生的事就是您想要的。 您还可以捕获语法中可能犯的任何错误。

翻译自: https://www.howtogeek.com/442332/how-to-work-with-variables-in-bash/

bash变量里包含变量

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值