Bash — Variables
Assigning variables
#!/bin/bash
# No spaces around =!
name="Alice"
age=30
path="/home/user"
# Use variables
echo "Name: $name"
echo "Age: ${age}"
Read input
#!/bin/bash
read -p "Enter name: " name
read -sp "Enter password: " pass
echo
echo "Hello, $name"
Environment variables
#!/bin/bash
echo "Home: $HOME"
echo "User: $USER"
echo "Shell: $SHELL"
echo "Path: $PATH"
# Export to make available to child processes
export MY_VAR="hello"
Default values
#!/bin/bash
# Use default if unset
name="${1:-World}"
echo "Hello, $name!"
# Use default if unset or empty
name="${1:-World}"
echo "Hello, $name!"
Read-only variables
#!/bin/bash
readonly PI=3.14159
# PI=3.14 # Error: readonly variable
Array variables
#!/bin/bash
# Indexed array
fruits=("Apple" "Banana" "Cherry")
echo "${fruits[0]}" # Apple
echo "${fruits[@]}" # All elements
echo "${#fruits[@]}" # Length: 3
# Associative array
declare -A ages
ages[Alice]=30
ages[Bob]=25
echo "${ages[Alice]}"
Variable scope
#!/bin/bash
global_var="I am global"
function test_scope() {
local local_var="I am local"
echo "$global_var"
echo "$local_var"
}
test_scope
echo "$global_var"
# echo "$local_var" # Error: not defined
Mini Practice
Write Bash code that:
- Assigns and uses variables
- Reads user input with
read - Uses environment variables
- Creates an indexed array
Up Next
In the next lesson, you'll learn about Strings — working with text in Bash.
Related Topics
Frequently Asked Questions about Variables
What is Variables in Bash?
Variables is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Variables?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Variables.
Why is Variables important in Bash?
Variables is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.