Bash Variables: Storing and Using Data

Learn how to create, assign, and use variables in Bash scripting. This beginner-friendly guide covers variable syntax, types, environment variables, special variables, and best practices with practical examples.

Bash Variables: Storing and Using Data

Variables are one of the fundamental building blocks of any programming language, and Bash is no exception. Think of a variable as a labeled container that stores data you can use throughout your script. Whether you're automating network configurations, processing log files, or building system administration tools, understanding how to work with variables will make your Bash scripts more powerful and flexible.

Creating and Assigning Variables

In Bash, creating a variable is straightforward. You simply assign a value to a name without any special declaration. Here's the basic syntax:

variable_name=value

Important: Notice there are no spaces around the equals sign. This is crucial in Bash - spaces will cause an error.

Let's look at some examples:

name="John"
age=25
server_ip="192.168.1.100"
log_file="/var/log/system.log"

For strings containing spaces, always use quotes. Single quotes preserve the literal value, while double quotes allow variable expansion (we'll cover this shortly).

Accessing Variable Values

To use a variable's value, you prefix the variable name with a dollar sign ($):

name="Alice"
echo "Hello, $name!"
echo "Hello, ${name}!"

Both lines above will output: Hello, Alice!

The curly braces ${} are optional in simple cases but become necessary when you need to separate the variable name from surrounding text:

prefix="test"
echo "${prefix}_file.txt"  # Outputs: test_file.txt
echo "$prefix_file.txt"    # This won't work as expected

Variable Types and Behavior

Bash treats all variables as strings by default, but it can perform arithmetic operations when needed:

# String operations
greeting="Hello"
target="World"
message="$greeting, $target!"
echo $message  # Outputs: Hello, World!

# Numeric operations (using arithmetic expansion)
num1=10
num2=5
sum=$((num1 + num2))
echo "Sum: $sum"  # Outputs: Sum: 15

Environment Variables vs Local Variables

Variables you create in a script are local by default - they only exist within that script. To make a variable available to other programs or scripts, you export it:

# Local variable
database_name="production_db"

# Environment variable (available to child processes)
export PATH="/usr/local/bin:$PATH"
export DATABASE_URL="mysql://localhost/$database_name"

You can view all environment variables with the env command, or check a specific one with echo $VARIABLE_NAME.

Special Variables

Bash provides several built-in special variables that are incredibly useful:

  • $0 - The name of the script
  • $1, $2, $3... - Command line arguments
  • $# - Number of arguments passed to the script
  • $@ - All arguments as separate words
  • $$ - Process ID of the current shell
  • $? - Exit status of the last command

Here's a practical example using these special variables:

#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Number of arguments: $#"
echo "All arguments: $@"

# Check if previous command succeeded
ls /nonexistent 2>/dev/null
if [ $? -ne 0 ]; then
    echo "Command failed!"
fi

Best Practices

Follow these conventions to write cleaner, more maintainable scripts:

  • Use descriptive variable names: server_count instead of sc
  • Use uppercase for environment variables: export DATABASE_URL
  • Use lowercase for local script variables: temp_file
  • Always quote variables when using them: echo "$variable"
  • Initialize variables to avoid unexpected behavior: counter=0

Common Pitfalls

Watch out for these frequent mistakes:

# Wrong: spaces around equals sign
name = "John"  # This will cause an error

# Wrong: not quoting variables with spaces
file_name="my file.txt"
ls $file_name  # This breaks on the space

# Correct: quote the variable
ls "$file_name"

What's Next

Now that you understand how to store and access data with variables, you're ready to make your scripts more interactive. In our next post, we'll explore how to get input from users and make decisions based on that input using conditional statements and user prompts.

🔧
Use a good text editor with syntax highlighting like VS Code or vim to write your Bash scripts - it'll help you catch syntax errors and make your code more readable. Visual Studio Code, vim and nano.