2.7.2. Variables
Table of Contents
Understanding Variables in Shell Scripts
In shell scripting, variables give you a way to store values and reuse them. They are one of the most important tools for making scripts flexible instead of hard coding every value.
This chapter focuses on variables in simple shell scripts, mostly with bash. Other shells may add features, but the core ideas stay the same.
Creating and Using Variables
In shell scripts, a variable is created when you assign a value to a name. There is no separate declaration step and there is no data type in the strict sense. Everything is stored as text.
You assign a value like this.
name="Alice"
greeting="Hello"
number=42
pi="3.14"
There are two key rules here. First, do not use spaces around the = sign. Second, a variable name usually uses letters, numbers, and underscores, and it must not start with a number. Names such as USER_NAME, file1, or temp_value are fine. Names such as 1name are not.
To use the value stored in a variable, you add a dollar sign in front of its name.
echo "$greeting, $name"
echo "The number is $number"
Here, "$greeting, $name" is expanded by the shell before echo runs. The shell replaces $greeting with Hello and $name with Alice.
Always remember:
name=value to set a variable, with no spaces around =.
$name to read the value of a variable.
Quoting and Variable Expansion
Quoting controls how the shell interprets special characters such as spaces or the dollar sign. This has a direct effect on variables.
If you use double quotes, variables are expanded inside the quotes.
name="Alice Wonderland"
echo "User: $name"
This prints User: Alice Wonderland. The double quotes protect the space, so the shell passes one argument, not two.
If you use single quotes, variables are not expanded inside the quotes.
name="Alice"
echo 'User: $name'
This prints User: $name literally, because the shell treats everything between single quotes as plain text.
If you use no quotes and the value contains spaces or other special characters, the shell may split the text into several parts or interpret characters in unwanted ways. Beginners often see surprising behavior here. To keep simple scripts predictable, it is safer to wrap variable expansions in double quotes when the value can contain spaces.
Important pattern.
Use "${var}" or "$var" most of the time when expanding variables, especially when values may contain spaces.
Variable Names and Conventions
The shell is case sensitive. The variables name, Name, and NAME are all different. By convention, user defined variables in simple scripts often use lowercase or mixed case, while environment variables are usually all uppercase.
For clarity, you might use patterns such as these.
username="alice"
file_count=10
BACKUP_DIR="/backups"You can also use the value of one variable when setting another.
greeting="Hello"
name="Bob"
message="$greeting, $name"
echo "$message"
The shell evaluates the right side and then stores the resulting text in message.
If you want to clearly separate a variable name from following letters, you can add braces.
name="Bob"
echo "Hello ${name}s friend"
Here the braces tell the shell that the variable name is name, not names.
Reading Variables from User Input
Scripts become interactive when they read values from the user. The read command stores input into variables.
echo "What is your name?"
read name
echo "Hello, $name"
The command read name waits for the user to type a line and press Enter. The shell then puts that text into the variable name.
You can read multiple values at once.
echo "Enter your first and last name:"
read first last
echo "First: $first"
echo "Last: $last"
Here the shell splits the line on whitespace and assigns pieces to first and last.
You can also add a prompt directly in the read command with the -p option when using bash.
read -p "Enter your age: " age
echo "You are $age years old."Command Substitution
Sometimes you want a variable to hold the output of a command. This is common when you need a timestamp, a filename, or some system information.
You can do this with command substitution. The shell runs the command and replaces the whole substitution with the output.
There are two main forms. The modern and recommended form uses $(...).
today=$(date)
echo "Today is: $today"
Here, $(date) is replaced by the output of date. You can use this with more complex commands.
files=$(ls)
echo "Files here:"
echo "$files"The older form uses backticks.
today=`date`
The backtick form is harder to read when commands are nested, so $(...) is usually preferred.
Command substitution removes the trailing newline at the end of command output. If there are several lines, they are kept. The result is still text stored in a variable.
Local Variables and Environment Variables
Not all variables behave the same way. Some variables exist only in the current shell. Others are passed down to child processes, such as commands that your script runs.
Variables you assign simply with name=value are shell variables. They exist only in that shell session or script. When the shell runs a program, those variables are not automatically visible to that program.
Environment variables are special. They are shared with child processes. They are often written in uppercase, for example PATH, HOME, or LANG. To turn a shell variable into an environment variable, you use the export command.
name="Alice"
export name
After export name, any program started from this shell can read name from its environment.
You can also assign and export in one step.
export EDITOR=nano
How to use and manage environment variables more broadly belongs to another chapter. Here, it is enough to understand that export marks a variable to be inherited by child processes.
Variable Scope Inside Scripts
When you run a script as ./script.sh and the file has an interpreter line such as #!/bin/bash, it runs in its own shell process. Variables created inside that script are not visible in the shell that started it.
If you want a script to change variables in your current shell, you do not run it as a separate program. Instead you source it.
. ./setvars.shor
source ./setvars.shSourcing runs the commands in the current shell process, so any variable assignments affect your current shell. This is how many configuration scripts work.
Inside larger scripts you can use functions, and then variables can be declared local to those functions. That topic is covered when functions are introduced. For now, you can think of variables in a simple script as global within that script, unless you deliberately use more advanced features.
Default Values and Parameter Expansion
The shell has a feature called parameter expansion, which lets you handle missing or empty variables in a compact way. You use a slightly extended syntax around variable names.
One common form provides a default value if a variable is unset or empty.
echo "Username: ${USER:-unknown}"
If USER has a value, the shell uses it. If USER is unset or empty, the shell uses unknown instead. The pattern is:
$$
\texttt{\${var:-default}}
$$
which you can read as "use var if set and not empty, otherwise use default."
There is also a form that not only uses a default value for that expansion, but also assigns it to the variable if it was missing.
echo "Starting with PORT=${PORT:=8080}"
If PORT was unset or empty, this expansion sets PORT to 8080 and expands to 8080. If PORT already had a value, it stays unchanged and that value is used.
The pattern here is:
$$
\texttt{\${var:=default}}
$$
That is, "if var is unset or empty, set it to default and use that."
These forms are very useful for building scripts that can accept environment variables or command line options, but also behave sensibly when no values are provided.
Useful parameter expansion patterns.
"${var:-default}" uses default only for that expansion.
"${var:=default}" also assigns default to var if it was empty or unset.
Arithmetic with Variables
While the shell mostly treats variables as text, you can still perform simple integer arithmetic using special syntax. This is enough for basic counters or simple calculations.
The most common form uses double parentheses.
x=5
y=3
sum=$(( x + y ))
echo "$sum"
Inside $(( ... )) you can write expressions with integer operators such as +, -, *, /, and % for remainder. The shell evaluates the expression and returns the result as text.
You can also update a variable in place.
count=0
count=$(( count + 1 ))
echo "$count"
For bash, there is also a shortcut.
(( count++ ))
This increments count by 1. The (( ... )) form is discussed more in the chapter about conditionals and control structures, but here you can see it as a simple arithmetic tool.
Remember that shell arithmetic works with integers only. If you try to use non integer values such as 3.14, they are not handled as floating point numbers. For more complex math, scripts usually call external tools.
Common Pitfalls with Variables
Several mistakes occur frequently when beginners start using variables in shell scripts. Recognizing them early saves debugging time.
A very common error is placing spaces around = during assignment.
name = "Alice" # Incorrect
This does not assign to name. The shell reads name as a command and = and "Alice" as its arguments. To assign, you must write:
name="Alice" # CorrectAnother common issue is forgetting the dollar sign when reading a variable.
name="Bob"
echo "Hello, name" # Prints literally 'name'
echo "Hello, $name" # Prints the value
You must use $name or ${name} to expand the variable.
Not quoting variables is a more subtle problem. If a variable contains spaces, the shell will split it into multiple arguments unless you wrap it in double quotes.
file="My Document.txt"
rm $file # Dangerous. Treated as 'My' and 'Document.txt'
rm "$file" # Safe. One argument
To reduce surprises, get used to writing "$var" when you use variables in commands, particularly when dealing with filenames or input from users.
Finally, remember that variables in a script do not affect your interactive shell when the script is executed normally. If you run:
#!/bin/bash
NAME="Alice"
and then execute ./script.sh, the variable NAME will not exist in your shell afterward. That script had its own shell process. To bring variables into your current shell, you must source the script.
Summary
Variables give shell scripts memory. You store text values with name=value, always without spaces. You read them with $name, usually wrapped in double quotes to keep spaces safe. You can accept user input with read, capture command output with $(...), and adjust behavior with parameter expansion such as ${var:-default}. Arithmetic expansion with $(( ... )) lets you perform simple calculations on integer values.
These tools prepare you for writing scripts that respond to different inputs and contexts, which you will build on in later chapters when you add conditionals, loops, and functions.
Views: 0
Where to Move
Move chapter:
- ☰ 1. PART I — Linux Fundamentals (Beginner)
- ☰ 1.1. What Is Linux?
- ☰ 1.1.1. What is an operating system
- ☰ 1.1.2. History of Unix and Linux
- ☰ 1.1.3. The Linux kernel
- ☰ 1.1.4. GNU and the Free Software Foundation
- ☰ 1.1.5. Open source philosophy
- ☰ 1.1.6. Where Linux is used today
- ☰ 1.1.7. Desktop vs server vs embedded Linux
-
- ☰ 1.2. Choosing a Linux Distribution
- ☰ 1.2.1. What is a distribution?
- ☰ 1.2.2. Package formats (deb, rpm, pacman)
- ☰ 1.2.3. Popular distributions
- ☰ 1.2.3.1. Ubuntu
- ☰ 1.2.3.2. Debian
- ☰ 1.2.3.3. Fedora
- ☰ 1.2.3.4. Arch Linux
- ☰ 1.2.3.5. openSUSE
-
- ☰ 1.2.4. Rolling vs fixed release
- ☰ 1.2.5. Choosing the right distribution
-
- ☰ 1.3. Installing Linux
- ☰ 1.3.1. Creating a bootable USB
- ☰ 1.3.2. Installing on real hardware
- ☰ 1.3.3. Dual booting with Windows
- ☰ 1.3.4. Installing in a virtual machine
- ☰ 1.3.5. Partitioning
- ☰ 1.3.5.1. `/` (root)
- ☰ 1.3.5.2. `/home`
- ☰ 1.3.5.3. Swap
-
- ☰ 1.3.6. First-time setup
-
- ☰ 1.4. First Steps After Installation
- ☰ 1.4.1. Desktop environment basics
- ☰ 1.4.2. Updating the system
- ☰ 1.4.3. Installing essential tools
- ☰ 1.4.4. Setting up drivers
- ☰ 1.4.5. Using the software center
-
- ☰ 1.5. Linux Filesystem Hierarchy
- ☰ 1.5.1. Overview of the root filesystem
- ☰ 1.5.2. Important directories
- ☰ 1.5.2.1. `/etc`
- ☰ 1.5.2.2. `/var`
- ☰ 1.5.2.3. `/usr`
- ☰ 1.5.2.4. `/tmp`
- ☰ 1.5.2.5. `/dev`
- ☰ 1.5.2.6. `/proc`
- ☰ 1.5.2.7. `/sys`
-
- ☰ 1.5.3. File types
- ☰ 1.5.4. Absolute vs relative paths
-
- ☰ 1.6. The Linux Graphical Environment
- ☰ 1.6.1. GNOME
- ☰ 1.6.2. KDE Plasma
- ☰ 1.6.3. XFCE
- ☰ 1.6.4. File managers
- ☰ 1.6.5. System settings
- ☰ 1.6.6. Workspaces and window management
-
-
- ☰ 2. PART II — Command Line Essentials
- ☰ 2.1. Terminal and Shell Basics
- ☰ 2.1.1. What is a shell?
- ☰ 2.1.2. Bash vs Zsh vs Fish
- ☰ 2.1.3. Command structure
- ☰ 2.1.4. Environment variables
- ☰ 2.1.5. Getting help
- ☰ 2.1.6. Command history and autocomplete
-
- ☰ 2.2. Files and Directories
- ☰ 2.2.1. Listing files
- ☰ 2.2.2. Navigating directories
- ☰ 2.2.3. File operations
- ☰ 2.2.4. Wildcards and globbing
- ☰ 2.2.5. Searching files
-
- ☰ 2.3. Viewing and Editing Text Files
- ☰ 2.3.1. Viewing tools
- ☰ 2.3.2. Editing with nano
- ☰ 2.3.3. Introduction to vim
- ☰ 2.3.4. Input/output redirection
-
- ☰ 2.4. Users, Permissions, and Ownership
- ☰ 2.4.1. Users and groups
- ☰ 2.4.2. Permission types (r, w, x)
- ☰ 2.4.3. Changing permissions
- ☰ 2.4.4. Changing ownership
- ☰ 2.4.5. Using sudo
-
- ☰ 2.5. Package Management
- ☰ 2.5.1. Software repositories
- ☰ 2.5.2. APT (Debian/Ubuntu)
- ☰ 2.5.3. DNF (Fedora/RHEL)
- ☰ 2.5.4. Pacman (Arch Linux)
- ☰ 2.5.5. Snap, Flatpak, AppImage
- ☰ 2.5.6. System upgrades
-
- ☰ 2.6. Working with Processes
- ☰ 2.6.1. What is a process?
- ☰ 2.6.2. Viewing processes
- ☰ 2.6.3. Killing processes
- ☰ 2.6.4. Foreground and background jobs
- ☰ 2.6.5. System services and daemons
-
- ☰ 2.7. Introduction to Shell Scripting
- ☰ 2.7.1. Writing your first script
- ☰ 2.7.2. Variables
- ☰ 2.7.3. Conditionals
- ☰ 2.7.4. Loops
- ☰ 2.7.5. Functions
- ☰ 2.7.6. Making scripts executable
-
-
- ☰ 3. PART III — Intermediate System Administration
- ☰ 3.1. Systemd and Service Management
- ☰ 3.1.1. What is systemd?
- ☰ 3.1.2. Managing services (systemctl)
- ☰ 3.1.3. Boot targets
- ☰ 3.1.4. System logs (journalctl)
- ☰ 3.1.5. Creating custom services
-
- ☰ 3.2. Storage and Filesystems
- ☰ 3.2.1. Devices and partitions
- ☰ 3.2.2. Filesystems (EXT4, XFS, Btrfs)
- ☰ 3.2.3. Mounting and unmounting
- ☰ 3.2.4. Disk usage tools
- ☰ 3.2.5. Archiving and compression (tar, gzip, xz)
-
- ☰ 3.3. Networking Fundamentals
- ☰ 3.3.1. IP addressing
- ☰ 3.3.2. Subnets and routing
- ☰ 3.3.3. DNS and hostnames
- ☰ 3.3.4. Networking tools (ip, ss, ping)
- ☰ 3.3.5. Editing network configuration files
-
- ☰ 3.4. User and Group Administration
- ☰ 3.4.1. User information files
- ☰ 3.4.2. Creating and removing users
- ☰ 3.4.3. Password policies
- ☰ 3.4.4. Managing groups
- ☰ 3.4.5. Shell configuration
-
- ☰ 3.5. System Monitoring
- ☰ 3.5.1. CPU and memory monitoring
- ☰ 3.5.2. Disk and I/O monitoring
- ☰ 3.5.3. Log files in /var/log
- ☰ 3.5.4. Boot performance
- ☰ 3.5.5. Monitoring running services
-
- ☰ 3.6. Backup and Restore
- ☰ 3.6.1. Backup strategies
- ☰ 3.6.2. Using rsync
- ☰ 3.6.3. Creating tar archives
- ☰ 3.6.4. Using snapshot systems
- ☰ 3.6.5. Automating backups
-
- ☰ 3.7. Basic System Security
- ☰ 3.7.1. Firewalls (UFW, firewalld)
- ☰ 3.7.2. Authentication policies
- ☰ 3.7.3. SSH security basics
- ☰ 3.7.4. SELinux and AppArmor overview
- ☰ 3.7.5. Intrusion detection basics
-
-
- ☰ 4. PART IV — Advanced Linux Skills
- ☰ 4.1. Advanced Shell Scripting
- ☰ 4.1.1. Script structure
- ☰ 4.1.2. Error handling
- ☰ 4.1.3. Debugging scripts
- ☰ 4.1.4. Scheduled tasks (cron)
-
- ☰ 4.2. The Linux Boot Process
- ☰ 4.2.1. BIOS vs UEFI
- ☰ 4.2.2. Understanding GRUB2
- ☰ 4.2.3. Kernel loading
- ☰ 4.2.4. initramfs
- ☰ 4.2.5. Troubleshooting boot issues
-
- ☰ 4.3. Kernel Management
- ☰ 4.3.1. What is the kernel?
- ☰ 4.3.2. Kernel modules
- ☰ 4.3.3. Kernel parameters
- ☰ 4.3.4. Compiling a custom kernel
- ☰ 4.3.5. Kernel versioning and updates
-
- ☰ 4.4. Advanced Filesystems and Storage
- ☰ 4.4.1. LVM concepts
- ☰ 4.4.2. Logical volumes
- ☰ 4.4.3. RAID levels
- ☰ 4.4.4. Full disk encryption (LUKS)
- ☰ 4.4.5. Snapshots and rollbacks
-
- ☰ 4.5. Network Services
- ☰ 4.5.1. SSH server configuration
- ☰ 4.5.2. NFS
- ☰ 4.5.3. Samba
- ☰ 4.5.4. FTP/SFTP
- ☰ 4.5.5. Firewalls in depth
-
- ☰ 4.6. Logging and Auditing
- ☰ 4.6.1. Systemd logging
- ☰ 4.6.2. Traditional logs in /var/log
- ☰ 4.6.3. Auditd
- ☰ 4.6.4. Log rotation
- ☰ 4.6.5. Creating custom logs
-
- ☰ 4.7. Virtualization and Containers
- ☰ 4.7.1. Virtual machines (KVM/QEMU)
- ☰ 4.7.2. Linux containers (LXC/LXD)
- ☰ 4.7.3. Docker fundamentals
- ☰ 4.7.4. Podman vs Docker
- ☰ 4.7.5. Container networking
-
-
- ☰ 5. PART V — Server Administration (Expert)
- ☰ 5.1. Web Servers
- ☰ 5.1.1. Apache basics
- ☰ 5.1.2. Nginx basics
- ☰ 5.1.3. Virtual hosts
- ☰ 5.1.4. SSL/HTTPS
- ☰ 5.1.5. Reverse proxy concepts
-
- ☰ 5.2. Database Servers
- ☰ 5.2.1. MySQL/MariaDB
- ☰ 5.2.2. PostgreSQL
- ☰ 5.2.3. Database backup strategies
- ☰ 5.2.4. Database hardening
-
- ☰ 5.3. Email Services
- ☰ 5.3.1. SMTP fundamentals
- ☰ 5.3.2. Configuring Postfix
- ☰ 5.3.3. IMAP/POP3 with Dovecot
- ☰ 5.3.4. Spam filtering systems
- ☰ 5.3.5. Email routing concepts
-
- ☰ 5.4. DNS and DHCP
- ☰ 5.4.1. Understanding DNS
- ☰ 5.4.2. Setting up BIND
- ☰ 5.4.3. DNS zones and records
- ☰ 5.4.4. DHCP server configuration
- ☰ 5.4.5. DNS troubleshooting
-
- ☰ 5.5. Load Balancing
- ☰ 5.5.1. HAProxy fundamentals
- ☰ 5.5.2. Nginx as a load balancer
- ☰ 5.5.3. Session persistence
- ☰ 5.5.4. High availability concepts
-
- ☰ 5.6. Clustering and High Availability
- ☰ 5.6.1. Failover principles
- ☰ 5.6.2. Pacemaker
- ☰ 5.6.3. Corosync
- ☰ 5.6.4. Cluster resource management
- ☰ 5.6.5. Distributed filesystems
-
-
- ☰ 6. PART VI — DevOps and Cloud
- ☰ 6.1. Linux for Developers
- ☰ 6.1.1. Compiler toolchains (gcc, make)
- ☰ 6.1.2. Git fundamentals
- ☰ 6.1.3. Debugging tools (gdb, strace)
- ☰ 6.1.4. Build automation (Makefile, CMake)
-
- ☰ 6.2. DevOps on Linux
- ☰ 6.2.1. CI/CD principles
- ☰ 6.2.2. YAML basics
- ☰ 6.2.3. GitHub Actions
- ☰ 6.2.4. GitLab CI/CD
- ☰ 6.2.5. Automated testing
-
- ☰ 6.3. Configuration Management
- ☰ 6.3.1. Ansible basics
- ☰ 6.3.2. Playbooks and inventories
- ☰ 6.3.3. Puppet overview
- ☰ 6.3.4. Chef overview
-
- ☰ 6.4. Infrastructure as Code
- ☰ 6.4.1. Terraform fundamentals
- ☰ 6.4.2. Providers and resources
- ☰ 6.4.3. Modules
- ☰ 6.4.4. Cloud provisioning with Terraform
-
- ☰ 6.5. Cloud Computing with Linux
- ☰ 6.5.1. Linux on AWS
- ☰ 6.5.2. Linux on Azure
- ☰ 6.5.3. Linux on GCP
- ☰ 6.5.4. Cloud networking basics
- ☰ 6.5.5. Scaling and monitoring
-
-
- ☰ 7. PART VII — Master Topics
- ☰ 7.1. Hardening a Linux System
- ☰ 7.1.1. Hardening principles
- ☰ 7.1.2. Kernel hardening
- ☰ 7.1.3. File integrity monitoring
- ☰ 7.1.4. Vulnerability scanning
-
- ☰ 7.2. Forensics and Incident Response
- ☰ 7.2.1. Collecting evidence
- ☰ 7.2.2. Log and file recovery
- ☰ 7.2.3. Analyzing suspicious processes
- ☰ 7.2.4. Incident response workflow
-
- ☰ 7.3. Performance Tuning
- ☰ 7.3.1. CPU tuning
- ☰ 7.3.2. Memory tuning
- ☰ 7.3.3. Disk and I/O optimization
- ☰ 7.3.4. Profiling tools
-
- ☰ 7.4. Writing Linux Tools
- ☰ 7.4.1. Bash-based tools
- ☰ 7.4.2. Python command-line tools
- ☰ 7.4.3. Writing tools in C
- ☰ 7.4.4. Using Linux system APIs
-
- ☰ 7.5. Linux Internals
- ☰ 7.5.1. Process lifecycle
- ☰ 7.5.2. Memory management
- ☰ 7.5.3. Signals and IPC
- ☰ 7.5.4. Namespaces
- ☰ 7.5.5. cgroups
-
- ☰ 7.6. Becoming a Linux Expert
- ☰ 7.6.1. Career paths
- ☰ 7.6.2. Certifications (RHCE, LFCS, LPIC)
- ☰ 7.6.3. Building a homelab
- ☰ 7.6.4. Contributing to open source
-
-
Comments
Please login to add a comment.
Don't have an account? Register now!