Working with Variables in Shell

Summary: Create and use variables in your scripts.


When automating tasks or scripting in the shell (Bash, Zsh, or similar environments), variables are essential for storing and manipulating data. They make your scripts flexible, readable, and powerful. In this guide, we’ll discuss how to create, use, and manage variables efficiently in shell scripting.


What is a Variable in Shell?

A variable is a symbolic name that references a value. In shell scripting, variables are used to store strings, numbers, commands, or other data. Unlike many programming languages, shell variables are untyped, which means they can hold any kind of value without explicitly declaring a data type.


Defining and Assigning Variables

You assign a value to a variable using the = operator, without spaces around the operator:

greeting="Hello, world!"
user_name="Alice"
count=5

Tip: No spaces before or after the = sign. foo=bar is correct, foo = bar is invalid.


Accessing Variable Values

To retrieve the value of a variable, prefix its name with a dollar sign ($):

echo $greeting
# Output: Hello, world!

You can also use curly braces to clearly define variable boundaries:

echo "Welcome, ${user_name}!"
# Output: Welcome, Alice!

This is useful when appending text directly to a variable’s value:

echo "The file name is: ${user_name}_data.txt"

Environment Variables vs. Local Variables

  • Local variables are visible only within the shell or script in which they are defined.
  • Environment variables are inherited by child processes and other programs executed from the shell.

To make a variable an environment variable, use export:

export PATH_TO_DATA="/home/alice/data"

Best Practices for Naming Variables

  • Use descriptive, clear names.
  • By convention, all uppercase is used for environment variables (HOME, PATH), and lowercase or mixed case for local variables (fileName, counter).
  • Variable names must start with a letter or underscore and can contain letters, numbers, and underscores.

Valid:

home_dir
HOME_DIR
user1_val

Invalid:

1stuser   # starts with a number
user-name # contains a dash

Reading User Input into Variables

The read command lets you store user input in a variable:

echo "Enter your name:"
read name
echo "Hello, $name!"

Using Command Substitution

You can assign the output of a command to a variable using $():

today=$(date +%Y-%m-%d)
echo "Today's date: $today"

Unsetting Variables

To remove a variable from the environment, use the unset command:

unset my_variable

Practical Examples

Example 1: Simple Greeting Script

#!/bin/bash

name="Sam"
echo "Good morning, $name!"

Example 2: Dynamic Values

#!/bin/bash

directory=$(pwd)
echo "You are in: $directory"

Example 3: Read and Use User Input

#!/bin/bash

echo "What is your favorite color?"
read color
echo "Your favorite color is $color."

Conclusion

Variables are a foundational concept in shell scripting, enabling you to write adaptable, efficient scripts. By understanding how to declare, use, and manage variables, you unlock the real power and flexibility of the shell. Start experimenting with variables in your own scripts and see how much more dynamic they can become!