如何在 Shell 脚本中打印变量的值

ShellShellBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

Introduction

Shell scripting is a powerful tool for automating tasks in Linux environments. One of the fundamental skills in shell programming is working with variables - temporary storage locations that hold data. This tutorial will guide you through the process of creating variables and printing their values in shell scripts. By the end of this lab, you will understand how to declare variables, access their values, and incorporate them into practical shell scripts.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("Shell")) -.-> shell/BasicSyntaxandStructureGroup(["Basic Syntax and Structure"]) shell(("Shell")) -.-> shell/VariableHandlingGroup(["Variable Handling"]) shell(("Shell")) -.-> shell/AdvancedScriptingConceptsGroup(["Advanced Scripting Concepts"]) shell/BasicSyntaxandStructureGroup -.-> shell/shebang("Shebang") shell/VariableHandlingGroup -.-> shell/variables_decl("Variable Declaration") shell/VariableHandlingGroup -.-> shell/variables_usage("Variable Usage") shell/VariableHandlingGroup -.-> shell/str_manipulation("String Manipulation") shell/AdvancedScriptingConceptsGroup -.-> shell/read_input("Reading Input") shell/AdvancedScriptingConceptsGroup -.-> shell/cmd_substitution("Command Substitution") subgraph Lab Skills shell/shebang -.-> lab-417569{{"如何在 Shell 脚本中打印变量的值"}} shell/variables_decl -.-> lab-417569{{"如何在 Shell 脚本中打印变量的值"}} shell/variables_usage -.-> lab-417569{{"如何在 Shell 脚本中打印变量的值"}} shell/str_manipulation -.-> lab-417569{{"如何在 Shell 脚本中打印变量的值"}} shell/read_input -.-> lab-417569{{"如何在 Shell 脚本中打印变量的值"}} shell/cmd_substitution -.-> lab-417569{{"如何在 Shell 脚本中打印变量的值"}} end

Creating Your First Shell Script with Variables

Let's start by creating a simple shell script that demonstrates how to declare and use variables.

What are Shell Variables?

Shell variables are named storage locations that can hold values in shell scripts. They allow you to store and retrieve data such as text strings, numbers, file paths, and command outputs. Variables make your scripts more flexible and reusable.

Creating Your First Script

Let's create a shell script file:

  1. Open the WebIDE terminal
  2. Navigate to the project directory (if not already there):
    cd ~/project
  3. Create a new file named myscript.sh using the WebIDE editor:
    • Click on the "New File" icon in the WebIDE
    • Name it myscript.sh
    • Add the following content to the file:
#!/bin/bash

## This is my first shell script with variables

## Declaring a variable
name="LabEx User"

## Printing the variable
echo "Hello, $name!"

## Printing the current date using a variable
current_date=$(date)
echo "Today is: $current_date"
  1. Save the file by pressing Ctrl+S or clicking File > Save

  2. Make the script executable with the following command:

    chmod +x myscript.sh
  3. Run your script:

    ./myscript.sh

You should see output similar to this:

Hello, LabEx User!
Today is: Thu Jul 13 10:30:45 UTC 2023

Understanding the Script

Let's break down what happened in our script:

  1. The first line #!/bin/bash (called a shebang) tells the system to use the Bash shell to execute the script.
  2. We created a variable named name and assigned it the value "LabEx User" using name="LabEx User".
  3. We printed the value of the variable using echo "Hello, $name!". The $ symbol before the variable name tells the shell to substitute the variable's value.
  4. We created another variable current_date and assigned it the output of the date command using $(date).
  5. We printed the value of the current_date variable.

Variable Naming Rules

When creating variables in shell scripts, follow these naming conventions:

  • Variable names can contain letters, numbers, and underscores
  • They must start with a letter or underscore
  • No spaces are allowed around the equal sign when assigning values
  • Variable names are case-sensitive (NAME, name, and Name are three different variables)

Try modifying the script to include your own variables and run it again to see the results.

Different Ways to Print Variable Values

Now that you understand the basics of creating variables, let's explore different methods to print their values in shell scripts.

Using Double Quotes

The most common way to print variables is using double quotes with the echo command. Double quotes allow the shell to interpret variable names and substitute their values.

Create a new file named print_variables.sh:

  1. Click on the "New File" icon in the WebIDE
  2. Name it print_variables.sh
  3. Add the following content:
#!/bin/bash

## Declaring variables
name="LabEx"
version=1.0
is_active=true

## Printing variables with double quotes
echo "Application name: $name"
echo "Version: $version"
echo "Active status: $is_active"

## Printing multiple variables in one statement
echo "The $name application version $version is $is_active"
  1. Save the file (Ctrl+S or File > Save)
  2. Make it executable:
    chmod +x print_variables.sh
  3. Run the script:
    ./print_variables.sh

You should see output similar to:

Application name: LabEx
Version: 1.0
Active status: true
The LabEx application version 1.0 is true

Using Curly Braces

Sometimes you need to be more precise about where a variable name begins and ends. Curly braces help with this by clearly delineating the variable name.

Add the following lines to your print_variables.sh script:

## Using curly braces to clearly define variable boundaries
app="${name}App"
echo "Application full name: $app"

## This avoids confusion when you want to append text directly to a variable's value
echo "Application name with text: ${name}Text"

Save and run the script again:

./print_variables.sh

The additional output should show:

Application full name: LabExApp
Application name with text: LabExText

Using Single Quotes

Unlike double quotes, single quotes prevent variable substitution and print the literal text.

Add these lines to your script:

## Using single quotes (no variable substitution)
echo 'With single quotes: $name is not replaced'

## Mixing quote types for complex output
echo "This is the variable value: '$name'"

Save and run the script again. You should see:

With single quotes: $name is not replaced
This is the variable value: 'LabEx'

Using printf for Formatted Output

The printf command offers more control over the formatting of your output:

## Using printf for formatted output
printf "Name: %s\nVersion: %.1f\n" "$name" "$version"

## Formatting numbers with printf
number=42.5678
printf "Formatted number: %.2f\n" $number

Save and run the script again. The additional output will show:

Name: LabEx
Version: 1.0
Formatted number: 42.57

Try experimenting with the different printing methods to see which ones work best for your needs.

Creating a Practical Shell Script with User Input

Now let's create a more practical shell script that takes user input, stores it in variables, and displays the results.

Reading User Input

The read command allows your script to accept input from users. Let's create a simple greeting script:

  1. Create a new file named greeting.sh:
    • Click on the "New File" icon in the WebIDE
    • Name it greeting.sh
    • Add the following content:
#!/bin/bash

## Simple greeting script that takes user input

## Prompt the user for their name
echo "What is your name?"
read username

## Prompt for age
echo "How old are you?"
read age

## Display a greeting with the provided information
echo "Hello, $username! You are $age years old."

## Calculate birth year (approximately)
current_year=$(date +%Y)
birth_year=$((current_year - age))

echo "You were born around the year $birth_year."

## Adding a personalized message based on age
if [ $age -lt 18 ]; then
  echo "You are a minor."
elif [ $age -ge 18 ] && [ $age -lt 65 ]; then
  echo "You are an adult."
else
  echo "You are a senior."
fi
  1. Save the file (Ctrl+S or File > Save)

  2. Make it executable:

    chmod +x greeting.sh
  3. Run the script:

    ./greeting.sh
  4. When prompted, enter your name and age. You should see personalized output based on your input.

Understanding the Script Components

Let's break down the key parts of this script:

  1. The read command stores user input in variables (username and age).
  2. We use the variables in echo statements to create personalized output.
  3. We perform arithmetic using the $((expression)) syntax to calculate the birth year.
  4. We use conditional statements (if, elif, else) to provide different messages based on the age value.
  5. We utilize the date command with formatting options to get the current year.

Making the Script More Interactive

Let's enhance our script to make it more interactive and useful. Add the following to your greeting.sh file:

## Ask if the user wants to see the current system information
echo "Would you like to see some system information? (yes/no)"
read response

## Convert the response to lowercase for easier comparison
response_lower=$(echo "$response" | tr '[:upper:]' '[:lower:]')

if [ "$response_lower" = "yes" ] || [ "$response_lower" = "y" ]; then
  echo "System information for user $username:"
  echo "-------------------------------------"
  echo "Hostname: $(hostname)"
  echo "Kernel version: $(uname -r)"
  echo "System uptime: $(uptime -p)"
  echo "CPU information: $(grep "model name" /proc/cpuinfo | head -1 | cut -d: -f2 | sed 's/^[ \t]*//')"
  echo "Memory available: $(free -h | grep Mem | awk '{print $7}')"
  echo "-------------------------------------"
else
  echo "No problem, $username. Have a great day!"
fi

Save the file and run it again:

./greeting.sh

Follow the prompts and enter "yes" when asked if you want to see system information. You should see detailed information about the system.

This script demonstrates how to:

  • Read and process user input
  • Store and manipulate variables
  • Perform calculations
  • Make decisions based on variable values
  • Execute system commands and store their outputs in variables
  • Display formatted output to the user

Try modifying the script to add more interactive features or different types of system information.

Creating a Shell Script for File Operations

Let's apply our knowledge of shell variables to create a useful script that performs file operations. This script will demonstrate how variables can help automate file management tasks.

Creating a Backup Script

Let's create a script that makes a backup of files in a specified directory:

  1. First, let's create a test directory and some sample files to work with:

    mkdir -p ~/project/test_files
    echo "This is file 1" > ~/project/test_files/file1.txt
    echo "This is file 2" > ~/project/test_files/file2.txt
    echo "This is file 3" > ~/project/test_files/file3.txt
  2. Now, create a new file named backup.sh:

    • Click on the "New File" icon in the WebIDE
    • Name it backup.sh
    • Add the following content:
#!/bin/bash

## A script to backup files from a source directory to a backup directory

## Define variables for directories
source_dir="$HOME/project/test_files"
backup_dir="$HOME/project/backup"
date_stamp=$(date +"%Y%m%d_%H%M%S")
backup_name="backup_$date_stamp"

## Print the script's purpose
echo "File Backup Script"
echo "==================="
echo "Source directory: $source_dir"
echo "Backup directory: $backup_dir/$backup_name"

## Create the backup directory if it doesn't exist
if [ ! -d "$backup_dir" ]; then
  echo "Creating backup directory: $backup_dir"
  mkdir -p "$backup_dir"
fi

## Create a timestamped backup directory
mkdir -p "$backup_dir/$backup_name"

## Check if source directory exists
if [ ! -d "$source_dir" ]; then
  echo "Error: Source directory $source_dir does not exist!"
  exit 1
fi

## Count the number of files in the source directory
file_count=$(ls -1 "$source_dir" | wc -l)
echo "Found $file_count files in the source directory."

## Copy the files to the backup directory
echo "Copying files to backup location..."
cp -r "$source_dir"/* "$backup_dir/$backup_name"

## Verify the copy operation
copied_count=$(ls -1 "$backup_dir/$backup_name" | wc -l)
echo "Copied $copied_count files to the backup directory."

## Check if all files were copied successfully
if [ "$file_count" -eq "$copied_count" ]; then
  echo "Backup completed successfully!"
else
  echo "Warning: Not all files were copied. Please check for errors."
fi

## List the contents of the backup directory
echo "Contents of the backup directory:"
ls -la "$backup_dir/$backup_name"

## Display the total size of the backup
backup_size=$(du -sh "$backup_dir/$backup_name" | cut -f1)
echo "Total backup size: $backup_size"
  1. Save the file (Ctrl+S or File > Save)
  2. Make it executable:
    chmod +x backup.sh
  3. Run the script:
    ./backup.sh

You should see output showing the backup process, including:

  • The source and backup directories
  • The number of files found
  • Confirmation of the copy operation
  • The contents of the backup directory
  • The total size of the backup

Understanding the Script

This backup script demonstrates several important concepts:

  1. Variable usage: We use variables to store directory paths, date stamps, and counts
  2. Command substitution: We use $(command) syntax to capture command output in variables
  3. Conditional statements: We use if statements to check if directories exist
  4. String manipulation: We create a unique backup name using the date stamp
  5. Path variables: We use $HOME to reference the user's home directory
  6. Command execution: We use shell commands like mkdir, cp, and ls within our script
  7. Exit codes: We use exit 1 to terminate the script with an error status

Enhancing the Backup Script

Let's modify our script to accept a custom source directory from the user:

  1. Open backup.sh in the editor
  2. Replace the content with the following:
#!/bin/bash

## A script to backup files from a source directory to a backup directory

## Check if a source directory was provided
if [ $## -eq 0 ]; then
  ## No argument provided, use default directory
  source_dir="$HOME/project/test_files"
  echo "No source directory specified, using default: $source_dir"
else
  ## Use the provided directory
  source_dir="$1"
  echo "Using specified source directory: $source_dir"
fi

## Define variables for directories
backup_dir="$HOME/project/backup"
date_stamp=$(date +"%Y%m%d_%H%M%S")
backup_name="backup_$date_stamp"

## Print the script's purpose
echo "File Backup Script"
echo "==================="
echo "Source directory: $source_dir"
echo "Backup directory: $backup_dir/$backup_name"

## Create the backup directory if it doesn't exist
if [ ! -d "$backup_dir" ]; then
  echo "Creating backup directory: $backup_dir"
  mkdir -p "$backup_dir"
fi

## Create a timestamped backup directory
mkdir -p "$backup_dir/$backup_name"

## Check if source directory exists
if [ ! -d "$source_dir" ]; then
  echo "Error: Source directory $source_dir does not exist!"
  exit 1
fi

## Count the number of files in the source directory
file_count=$(ls -1 "$source_dir" | wc -l)
echo "Found $file_count files in the source directory."

## Copy the files to the backup directory
echo "Copying files to backup location..."
cp -r "$source_dir"/* "$backup_dir/$backup_name"

## Verify the copy operation
copied_count=$(ls -1 "$backup_dir/$backup_name" | wc -l)
echo "Copied $copied_count files to the backup directory."

## Check if all files were copied successfully
if [ "$file_count" -eq "$copied_count" ]; then
  echo "Backup completed successfully!"
else
  echo "Warning: Not all files were copied. Please check for errors."
fi

## List the contents of the backup directory
echo "Contents of the backup directory:"
ls -la "$backup_dir/$backup_name"

## Display the total size of the backup
backup_size=$(du -sh "$backup_dir/$backup_name" | cut -f1)
echo "Total backup size: $backup_size"
  1. Save the file
  2. Run the script with a custom directory:
    ./backup.sh ~/project

The enhanced script now demonstrates:

  • Command-line arguments using $1 (the first argument passed to the script)
  • Default values when no arguments are provided
  • Parameter checking with $# (the number of arguments)

This backup script is a practical example of how shell variables can be used to create useful, flexible tools for automating file management tasks.

Summary

In this lab, you have learned the essential skills for working with variables in shell scripts:

  • Creating and declaring shell variables
  • Different ways to print variable values using echo, printf, and quotes
  • Reading and processing user input
  • Performing calculations with shell variables
  • Using variables for file operations and backup tasks
  • Handling command-line arguments

These skills form a solid foundation for shell scripting and will enable you to create more dynamic and flexible scripts for automating various tasks in a Linux environment. As you continue your shell scripting journey, you can build on these concepts to develop more complex scripts for system administration, file management, and data processing tasks.