0
0
Bash Scriptingscripting~5 mins

Why variables store and reuse data in Bash Scripting

Choose your learning style9 modes available
Introduction

Variables let you save information so you can use it again later without typing it over and over.

When you want to remember a user's name and use it multiple times in a script.
When you need to store a file path to use it in several commands.
When you want to keep a number to do calculations or comparisons later.
When you want to make your script easier to change by updating one place only.
When you want to avoid repeating long or complex values in your script.
Syntax
Bash Scripting
variable_name=value
# To use the value: $variable_name

Do not put spaces around the equal sign.

Use $ before the variable name to get its value.

Examples
This saves 'Alice' in the variable name and then prints a greeting using it.
Bash Scripting
name=Alice
echo "Hello, $name!"
This stores the number 5 in count and prints it.
Bash Scripting
count=5
echo "Count is $count"
This saves a folder path and uses it in a message.
Bash Scripting
path=/home/user/docs
echo "Files are in $path"
Sample Program

This script shows how you can save a name in a variable and reuse it. Then it changes the name and uses the new one.

Bash Scripting
#!/bin/bash

# Store a name in a variable
user=Bob

# Use the variable to greet
echo "Welcome, $user!"

# Change the variable
user=Carol

# Use it again
echo "Now, hello $user!"
OutputSuccess
Important Notes

Variables in bash are case sensitive: user and User are different.

Always use quotes around variables when printing to avoid word splitting issues.

Summary

Variables store data so you can reuse it easily.

Use $variable_name to get the stored value.

Changing a variable updates the value for later use.