介绍
本教程将指导你完成在 Bash(一种流行的 shell 脚本语言)中分配和重新分配变量的过程。变量是 Bash 脚本编写中的基本构建块,允许你存储和操作数据。在这个实践实验(Lab)中,你将学习如何声明变量,为它们赋值,并在命令和脚本中使用它们。通过本教程,你将对如何在 Bash 中有效地使用变量有一个扎实的理解,从而能够编写更强大、更灵活的脚本。
创建和分配 Bash 变量
在 Bash 中,变量允许你存储数据,这些数据可以在你的脚本中稍后被访问和修改。让我们从创建一个简单的变量并为其赋值开始。
在 LabEx 环境中打开一个新的终端。你应该位于 /home/labex/project 目录中。
要在 Bash 中为变量赋值,请使用以下语法:
variable_name=value
请注意,等号周围不能有空格。
让我们创建第一个变量:
- 在终端中,键入以下命令并按 Enter 键:
name="John"
- 要显示变量的值,请使用
echo命令,并在变量名前面加上美元符号($):
echo $name
你应该看到以下输出:
John
- 你也可以在变量名周围使用双引号:
echo "My name is $name"
输出:
My name is John
- 要为同一个变量重新分配一个新值,只需再次使用赋值运算符(
=):
name="Alice"
echo "My name is $name"
输出:
My name is Alice
变量命名规则
在 Bash 中创建变量时,请遵循以下命名约定:
- 变量名可以包含字母、数字和下划线
- 变量名必须以字母或下划线开头
- 变量名区分大小写
- 变量名中不允许有空格
让我们创建一个文件来练习使用变量。在 WebIDE 中,在项目目录中创建一个名为 variables.sh 的新文件:
- 单击 IDE 中的“新建文件”图标
- 将文件命名为
variables.sh - 将以下代码添加到文件中:
#!/bin/bash
## Assigning variables
first_name="John"
last_name="Doe"
age=25
## Displaying variables
echo "First name: $first_name"
echo "Last name: $last_name"
echo "Age: $age"
## Reassigning variables
first_name="Jane"
echo "Updated first name: $first_name"
通过按 Ctrl+S 或单击文件 → 保存来保存文件
通过在终端中运行以下命令使脚本可执行:
chmod +x variables.sh
- 使用以下命令运行脚本:
./variables.sh
你应该看到以下输出:
First name: John
Last name: Doe
Age: 25
Updated first name: Jane
这演示了如何创建变量,为它们赋值,以及重新分配新值。
使用变量值和字符串操作
在这一步中,我们将探索在 Bash 中使用变量值的不同方法,包括字符串操作和算术计算。
字符串操作
Bash 提供了几种方法来操作存储在变量中的字符串值。
- 在项目目录中创建一个名为
string_operations.sh的新文件:
#!/bin/bash
## String concatenation
greeting="Hello"
name="World"
message="$greeting $name"
echo $message
## String length
text="Welcome to Bash scripting"
length=${#text}
echo "The length of '$text' is $length characters"
## Extracting substrings
substring=${text:0:7}
echo "Substring: $substring"
## Converting to uppercase and lowercase
uppercase=${text^^}
lowercase=${text,,}
echo "Uppercase: $uppercase"
echo "Lowercase: $lowercase"
- 保存文件并使其可执行:
chmod +x string_operations.sh
- 运行脚本:
./string_operations.sh
你应该看到类似于以下的输出:
Hello World
The length of 'Welcome to Bash scripting' is 25 characters
Substring: Welcome
Uppercase: WELCOME TO BASH SCRIPTING
Lowercase: welcome to bash scripting
算术运算
Bash 也允许你使用变量执行算术运算。
- 在项目目录中创建一个名为
arithmetic_operations.sh的新文件:
#!/bin/bash
## Assigning numeric values
x=5
y=3
## Basic arithmetic operations
sum=$((x + y))
difference=$((x - y))
product=$((x * y))
quotient=$((x / y))
remainder=$((x % y))
## Display results
echo "x = $x, y = $y"
echo "Sum: $x + $y = $sum"
echo "Difference: $x - $y = $difference"
echo "Product: $x * $y = $product"
echo "Quotient: $x / $y = $quotient"
echo "Remainder: $x % $y = $remainder"
## Increment and decrement
echo "Initial value of x: $x"
x=$((x + 1))
echo "After increment: $x"
x=$((x - 1))
echo "After decrement: $x"
## Compound assignment operators
x+=5
echo "After x+=5: $x"
x-=2
echo "After x-=2: $x"
- 保存文件并使其可执行:
chmod +x arithmetic_operations.sh
- 运行脚本:
./arithmetic_operations.sh
你应该看到类似于以下的输出:
x = 5, y = 3
Sum: 5 + 3 = 8
Difference: 5 - 3 = 2
Product: 5 * 3 = 15
Quotient: 5 / 3 = 1
Remainder: 5 % 3 = 2
Initial value of x: 5
After increment: 6
After decrement: 5
After x+=5: 10
After x-=2: 8
将用户输入读取到变量中
变量也可以存储用户提供的输入。让我们创建一个提示用户输入的脚本:
- 创建一个名为
user_input.sh的文件:
#!/bin/bash
## Prompt the user for their name
echo "What is your name?"
read user_name
## Prompt the user for their age
echo "How old are you?"
read user_age
## Display the information
echo "Hello, $user_name! You are $user_age years old."
## Calculate birth year (approximate)
current_year=$(date +%Y)
birth_year=$((current_year - user_age))
echo "You were likely born in $birth_year."
- 保存文件并使其可执行:
chmod +x user_input.sh
- 运行脚本:
./user_input.sh
- 当被提示时,输入你的姓名和年龄。脚本将显示一个问候语并计算你大概的出生年份。
这一步向你展示了如何使用变量执行各种操作,包括字符串操作、算术计算和读取用户输入。
在脚本和命令中使用变量
在这一步中,我们将探讨如何在 Bash 脚本和命令中有效地使用变量。我们将创建一个实用的脚本,演示变量在各种场景中的用法。
创建一个带有变量的基本脚本
让我们创建一个脚本,计算购物车中商品的 total 价格:
- 在项目目录中创建一个名为
shopping_cart.sh的新文件:
#!/bin/bash
## Initialize variables for items and their prices
item1="Laptop"
price1=999
item2="Headphones"
price2=149
item3="Mouse"
price3=25
## Calculate the total price
total=$((price1 + price2 + price3))
## Display the shopping cart
echo "Shopping Cart:"
echo "-------------"
echo "$item1: \$$price1"
echo "$item2: \$$price2"
echo "$item3: \$$price3"
echo "-------------"
echo "Total: \$$total"
## Apply a discount if the total is over $1000
discount_threshold=1000
discount_rate=10
if [ $total -gt $discount_threshold ]; then
discount_amount=$((total * discount_rate / 100))
discounted_total=$((total - discount_amount))
echo "Discount (${discount_rate}%): -\$$discount_amount"
echo "Final Total: \$$discounted_total"
fi
- 保存文件并使其可执行:
chmod +x shopping_cart.sh
- 运行脚本:
./shopping_cart.sh
你应该看到以下输出:
Shopping Cart:
-------------
Laptop: $999
Headphones: $149
Mouse: $25
-------------
Total: $1173
Discount (10%): -$117
Final Total: $1056
使用命令替换(Command Substitution)的变量
命令替换允许你捕获命令的输出并将其存储在变量中。让我们创建一个演示此功能的脚本:
- 创建一个名为
system_info.sh的新文件:
#!/bin/bash
## Get current date and time
current_date=$(date +"%Y-%m-%d")
current_time=$(date +"%H:%M:%S")
## Get system information
hostname=$(hostname)
os_type=$(uname -s)
kernel_version=$(uname -r)
uptime_info=$(uptime -p)
memory_free=$(free -h | awk '/^Mem:/ {print $4}')
disk_free=$(df -h / | awk 'NR==2 {print $4}')
## Display the information
echo "System Information Report"
echo "========================="
echo "Date: $current_date"
echo "Time: $current_time"
echo "Hostname: $hostname"
echo "OS Type: $os_type"
echo "Kernel Version: $kernel_version"
echo "Uptime: $uptime_info"
echo "Free Memory: $memory_free"
echo "Free Disk Space: $disk_free"
- 保存文件并使其可执行:
chmod +x system_info.sh
- 运行脚本:
./system_info.sh
你应该看到类似于以下的输出(具体数值取决于你的系统):
System Information Report
=========================
Date: 2023-11-20
Time: 14:30:25
Hostname: labex
OS Type: Linux
Kernel Version: 5.15.0-1015-aws
Uptime: up 2 hours, 15 minutes
Free Memory: 1.2Gi
Free Disk Space: 15G
在循环中使用变量
变量在循环中特别有用。让我们创建一个演示此功能的脚本:
- 创建一个名为
countdown.sh的新文件:
#!/bin/bash
## Get countdown start value from user
echo "Enter a number to start countdown:"
read count
## Validate that input is a number
if [[ ! $count =~ ^[0-9]+$ ]]; then
echo "Error: Please enter a valid number"
exit 1
fi
## Perform countdown
echo "Starting countdown from $count:"
while [ $count -gt 0 ]; do
echo $count
count=$((count - 1))
sleep 1
done
echo "Blast off!"
- 保存文件并使其可执行:
chmod +x countdown.sh
- 运行脚本:
./countdown.sh
- 当被提示时,输入一个小数字(例如 5)。
该脚本将从你输入的数字开始倒数,打印每个数字,然后在最后打印“Blast off!”。
这些示例演示了如何在 Bash 脚本的不同上下文中,使用变量,使它们更具动态性和灵活性。
变量作用域和特殊变量
在最后一步中,我们将探索 Bash 中的变量作用域,并了解 Bash 提供的特殊变量。
理解变量作用域
在 Bash 中,变量可以具有不同的作用域,这决定了它们可以在哪里被访问:
- 全局变量:这些变量可以在整个脚本中访问
- 局部变量:这些变量只能在特定的函数或代码块中访问
让我们创建一个脚本来演示变量作用域:
- 创建一个名为
variable_scope.sh的新文件:
#!/bin/bash
## Global variable
global_var="I am a global variable"
## Function that demonstrates variable scope
demo_scope() {
## Local variable
local local_var="I am a local variable"
## Access global variable
echo "Inside function: global_var = $global_var"
## Access local variable
echo "Inside function: local_var = $local_var"
## Modify global variable
global_var="Global variable modified"
}
## Main script
echo "Before function call: global_var = $global_var"
## This will fail because local_var doesn't exist yet
echo "Before function call: local_var = $local_var"
## Call the function
demo_scope
## After function call
echo "After function call: global_var = $global_var"
## This will fail because local_var is only accessible within the function
echo "After function call: local_var = $local_var"
- 保存文件并使其可执行:
chmod +x variable_scope.sh
- 运行脚本:
./variable_scope.sh
你应该看到类似于以下的输出:
Before function call: global_var = I am a global variable
Before function call: local_var =
Inside function: global_var = I am a global variable
Inside function: local_var = I am a local variable
After function call: global_var = Global variable modified
After function call: local_var =
请注意:
- 全局变量
global_var可以在函数内部和外部访问 - 局部变量
local_var只能在函数内部访问 - 对全局变量的更改在函数结束后仍然存在
使用特殊变量
Bash 提供了几个包含特定信息的特殊变量。让我们来探索其中的一些:
- 创建一个名为
special_variables.sh的新文件:
#!/bin/bash
## Special variables demonstration
echo "Script name: $0"
echo "Process ID: $$"
echo "Number of arguments: $#"
echo "All arguments: $@"
echo "Exit status of last command: $?"
echo "Current user: $USER"
echo "Current hostname: $HOSTNAME"
echo "Random number: $RANDOM"
## Function to demonstrate positional parameters
show_params() {
echo "Function received $## parameters"
echo "Parameter 1: $1"
echo "Parameter 2: $2"
echo "Parameter 3: $3"
}
## Call the function with parameters
echo -e "\nCalling function with parameters:"
show_params apple banana cherry
## Demonstrate positional parameters to the script
echo -e "\nScript positional parameters:"
echo "Parameter 1: $1"
echo "Parameter 2: $2"
echo "Parameter 3: $3"
- 保存文件并使其可执行:
chmod +x special_variables.sh
- 使用一些参数运行脚本:
./special_variables.sh arg1 arg2 arg3
你应该看到类似于以下的输出:
Script name: ./special_variables.sh
Process ID: 12345
Number of arguments: 3
All arguments: arg1 arg2 arg3
Exit status of last command: 0
Current user: labex
Current hostname: labex
Random number: 23456
Calling function with parameters:
Function received 3 parameters
Parameter 1: apple
Parameter 2: banana
Parameter 3: cherry
Script positional parameters:
Parameter 1: arg1
Parameter 2: arg2
Parameter 3: arg3
环境变量
环境变量是影响 shell 和程序行为的特殊变量。让我们创建一个脚本来探索它们:
- 创建一个名为
environment_variables.sh的新文件:
#!/bin/bash
## Display common environment variables
echo "HOME directory: $HOME"
echo "Current user: $USER"
echo "Shell: $SHELL"
echo "Path: $PATH"
echo "Current working directory: $PWD"
echo "Terminal: $TERM"
echo "Language: $LANG"
## Creating and exporting a new environment variable
echo -e "\nCreating a new environment variable:"
MY_VAR="Hello from environment variable"
export MY_VAR
echo "MY_VAR = $MY_VAR"
## Demonstrate that child processes inherit environment variables
echo -e "\nAccessing environment variable from a child process:"
bash -c 'echo "Child process sees MY_VAR = $MY_VAR"'
## Remove the environment variable
echo -e "\nRemoving the environment variable:"
unset MY_VAR
echo "MY_VAR = $MY_VAR (should be empty)"
- 保存文件并使其可执行:
chmod +x environment_variables.sh
- 运行脚本:
./environment_variables.sh
你应该看到输出,显示了各种环境变量,并演示了如何创建、访问和删除它们。
这一步向你展示了变量作用域在 Bash 中的工作方式,并向你介绍了在脚本中提供有用信息的特殊变量。
总结
在这个实验中,你已经学习了在 Bash 脚本中处理变量的基础知识。你获得了以下方面的实践经验:
- 创建变量并为其赋值
- 使用字符串操作和算术计算
- 在脚本和命令中使用变量
- 理解变量作用域并使用特殊变量
这些技能构成了 Bash 脚本的基础,并将使你能够编写更复杂和强大的脚本。变量是使你的脚本具有动态性和可重用性的重要工具,它们允许脚本适应不同的输入和场景。
在继续你的 Bash 脚本之旅时,请记住以下关键点:
- 始终选择描述性的变量名
- 在编写函数时,要注意变量作用域
- 使用特殊变量来访问脚本中的有用信息
- 利用环境变量进行配置和自定义
有了这些技能,你现在已经能够创建更复杂的 Bash 脚本,以实现任务自动化和系统管理。



