Wie man Variablen in Bash zuweist und erneut zuweist

ShellShellBeginner
Jetzt üben

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Introduction

This tutorial will guide you through the process of assigning and reassigning variables in Bash, the popular shell scripting language. Variables are fundamental building blocks in Bash scripting that allow you to store and manipulate data. In this hands-on lab, you will learn how to declare variables, assign values to them, and use them in commands and scripts. By the end of this tutorial, you will have a solid understanding of how to effectively work with variables in Bash, enabling you to write more powerful and flexible scripts.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("Shell")) -.-> shell/VariableHandlingGroup(["Variable Handling"]) shell(("Shell")) -.-> shell/AdvancedScriptingConceptsGroup(["Advanced Scripting Concepts"]) shell/VariableHandlingGroup -.-> shell/variables_decl("Variable Declaration") shell/VariableHandlingGroup -.-> shell/variables_usage("Variable Usage") shell/VariableHandlingGroup -.-> shell/str_manipulation("String Manipulation") shell/AdvancedScriptingConceptsGroup -.-> shell/arith_ops("Arithmetic Operations") shell/AdvancedScriptingConceptsGroup -.-> shell/read_input("Reading Input") shell/AdvancedScriptingConceptsGroup -.-> shell/cmd_substitution("Command Substitution") subgraph Lab Skills shell/variables_decl -.-> lab-392817{{"Wie man Variablen in Bash zuweist und erneut zuweist"}} shell/variables_usage -.-> lab-392817{{"Wie man Variablen in Bash zuweist und erneut zuweist"}} shell/str_manipulation -.-> lab-392817{{"Wie man Variablen in Bash zuweist und erneut zuweist"}} shell/arith_ops -.-> lab-392817{{"Wie man Variablen in Bash zuweist und erneut zuweist"}} shell/read_input -.-> lab-392817{{"Wie man Variablen in Bash zuweist und erneut zuweist"}} shell/cmd_substitution -.-> lab-392817{{"Wie man Variablen in Bash zuweist und erneut zuweist"}} end

Creating and Assigning Bash Variables

In Bash, variables allow you to store data that can be accessed and modified later in your script. Let us start by creating a simple variable and assigning a value to it.

Open a new terminal in the LabEx environment. You should be in the /home/labex/project directory.

To assign a value to a variable in Bash, use the following syntax:

variable_name=value

Note that there must be no spaces around the equals sign.

Let us create our first variable:

  1. In the terminal, type the following command and press Enter:
name="John"
  1. To display the value of the variable, use the echo command with the variable name preceded by a dollar sign ($):
echo $name

You should see the following output:

John
  1. You can also use double quotes around the variable name:
echo "My name is $name"

Output:

My name is John
  1. To reassign a new value to the same variable, simply use the assignment operator (=) again:
name="Alice"
echo "My name is $name"

Output:

My name is Alice

Variable Naming Rules

When creating variables in Bash, follow these naming conventions:

  • Variable names can contain letters, numbers, and underscores
  • Variable names must start with a letter or underscore
  • Variable names are case-sensitive
  • No spaces are allowed in variable names

Let us create a file to practice with variables. In the WebIDE, create a new file named variables.sh in the project directory:

  1. Click on the "New File" icon in the IDE
  2. Name the file variables.sh
  3. Add the following code to the file:
#!/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"
  1. Save the file by pressing Ctrl+S or clicking File → Save

  2. Make the script executable by running the following command in the terminal:

chmod +x variables.sh
  1. Run the script with:
./variables.sh

You should see the following output:

First name: John
Last name: Doe
Age: 25
Updated first name: Jane

This demonstrates how to create variables, assign values to them, and reassign new values.

Working with Variable Values and String Operations

In this step, we will explore different ways to work with variable values in Bash, including string operations and arithmetic calculations.

String Operations

Bash provides several ways to manipulate string values stored in variables.

  1. Create a new file named string_operations.sh in the project directory:
#!/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"
  1. Save the file and make it executable:
chmod +x string_operations.sh
  1. Run the script:
./string_operations.sh

You should see output similar to:

Hello World
The length of 'Welcome to Bash scripting' is 25 characters
Substring: Welcome
Uppercase: WELCOME TO BASH SCRIPTING
Lowercase: welcome to bash scripting

Arithmetic Operations

Bash also allows you to perform arithmetic operations with variables.

  1. Create a new file named arithmetic_operations.sh in the project directory:
#!/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"
  1. Save the file and make it executable:
chmod +x arithmetic_operations.sh
  1. Run the script:
./arithmetic_operations.sh

You should see output similar to:

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

Reading User Input into Variables

Variables can also store input provided by users. Let us create a script that prompts the user for input:

  1. Create a file named 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."
  1. Save the file and make it executable:
chmod +x user_input.sh
  1. Run the script:
./user_input.sh
  1. When prompted, enter your name and age. The script will display a greeting and calculate your approximate birth year.

This step has shown you how to perform various operations with variables, including string manipulation, arithmetic calculations, and reading user input.

Using Variables in Scripts and Commands

In this step, we will explore how to use variables effectively in Bash scripts and commands. We will create a practical script that demonstrates variable usage in various scenarios.

Creating a Basic Script with Variables

Let us create a script that calculates the total cost of items in a shopping cart:

  1. Create a new file named shopping_cart.sh in the project directory:
#!/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
  1. Save the file and make it executable:
chmod +x shopping_cart.sh
  1. Run the script:
./shopping_cart.sh

You should see the following output:

Shopping Cart:
-------------
Laptop: $999
Headphones: $149
Mouse: $25
-------------
Total: $1173
Discount (10%): -$117
Final Total: $1056

Using Variables with Command Substitution

Command substitution allows you to capture the output of a command and store it in a variable. Let us create a script that demonstrates this:

  1. Create a new file named 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"
  1. Save the file and make it executable:
chmod +x system_info.sh
  1. Run the script:
./system_info.sh

You should see output similar to the following (with values specific to your system):

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

Using Variables in Loops

Variables are particularly useful in loops. Let us create a script that demonstrates this:

  1. Create a new file named 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!"
  1. Save the file and make it executable:
chmod +x countdown.sh
  1. Run the script:
./countdown.sh
  1. Enter a small number (like 5) when prompted.

The script will count down from the number you entered, printing each number and then "Blast off!" at the end.

These examples demonstrate how variables can be used in different contexts within Bash scripts, making them more dynamic and flexible.

Variable Scope and Special Variables

In this final step, we will explore variable scope in Bash and learn about special variables that Bash provides.

Understanding Variable Scope

In Bash, variables can have different scopes, which determine where they can be accessed:

  1. Global variables: These are accessible throughout the entire script
  2. Local variables: These are accessible only within a specific function or block

Let us create a script to demonstrate variable scope:

  1. Create a new file named 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"
  1. Save the file and make it executable:
chmod +x variable_scope.sh
  1. Run the script:
./variable_scope.sh

You should see output similar to:

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 =

Notice that:

  • The global variable global_var is accessible both inside and outside the function
  • The local variable local_var is only accessible within the function
  • Changes to the global variable persist after the function ends

Working with Special Variables

Bash provides several special variables that hold specific information. Let us explore some of them:

  1. Create a new file named 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"
  1. Save the file and make it executable:
chmod +x special_variables.sh
  1. Run the script with some arguments:
./special_variables.sh arg1 arg2 arg3

You should see output similar to:

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

Environment Variables

Environment variables are special variables that affect the behavior of the shell and programs. Let us create a script to explore them:

  1. Create a new file named 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)"
  1. Save the file and make it executable:
chmod +x environment_variables.sh
  1. Run the script:
./environment_variables.sh

You should see output showing various environment variables and demonstrating how they can be created, accessed, and removed.

This step has shown you how variable scope works in Bash and introduced you to special variables that provide useful information within your scripts.

Summary

In this lab, you have learned the fundamentals of working with variables in Bash scripting. You have gained practical experience with:

  • Creating and assigning values to variables
  • Working with string operations and arithmetic calculations
  • Using variables in scripts and commands
  • Understanding variable scope and working with special variables

These skills form the foundation of Bash scripting and will enable you to write more sophisticated and powerful scripts. Variables are an essential tool for making your scripts dynamic and reusable, allowing them to adapt to different inputs and scenarios.

As you continue your journey in Bash scripting, remember these key points:

  • Always choose descriptive variable names
  • Be mindful of variable scope when writing functions
  • Use special variables to access useful information within your scripts
  • Leverage environment variables for configuration and customization

With these skills, you are now well-equipped to create more complex Bash scripts for automating tasks and managing your system.