Introduction to Using Variables in Shell Scripts

Welcome back to the world of shell scripting. In the previous lesson, you crafted your very first shell script that printed "Hello, World!" to the screen. Today, we will take the next step by exploring how to use variables in shell scripts. This lesson will introduce you to variable declaration, reassignment, and some basic arithmetic operations.

Using variables can make your scripts more dynamic and flexible, allowing you to store information, reuse values, and perform calculations. Let's get started!

Creating and Using Variables
Variable Reassignment
Defining and Using Integers
Common Arithmetic Pitfalls
Correctly Naming Variables

When naming variables in shell scripts, it's important to follow certain rules to ensure your script runs correctly. Here are the key rules for proper variable naming:

  • Variable names must begin with a letter (a-z, A-Z) or an underscore (_).
  • After the first character, variable names can include letters, numbers (0-9), and underscores, but no other special characters.
  • Variable names cannot contain spaces or special characters like !, @, #, $, %, ^, &, *, (, ), -, +, =, etc.
  • Variable names are case-sensitive. For example, Var and var are considered different variables.
  • Do not use reserved words or keywords (such as if, then, else, fi, for, while, etc.) as variable names, as they have special meanings in shell scripting.

Proper variable naming is crucial to avoid errors and improve code readability. Let’s see some correct and incorrect ways to name variables:

#!/bin/bash

# Correctly naming variables
var=1
var1=1
_var_1=1

# Incorrectly naming variables (commented out to avoid errors)
# 1Var=1
# 123=1
# !var=1
# @var=1
# var*1=1
Summary and Next Steps

Excellent job! Today, you've learned how to create and use variables, reassign variable values, define and use integers, and understand proper variable naming conventions in shell scripts. This knowledge is fundamental for writing dynamic and flexible scripts.

By mastering variables, you can already see how much more powerful your scripts can become. The next step is to dive into the practice problems to reinforce your understanding and apply what you've learned. Get ready to tackle the challenges ahead and enhance your scripting skills!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal