Skip to main content
Bash Scripting – Complete Beginner to Advanced Guide
CHAPTER 03 Intermediate

Variables and User Input

Updated: May 16, 2026
25 min read

# CHAPTER 3

Variables and User Input

1. Introduction

A script that deletes the exact same file every time it runs is useful, but highly limited. True automation requires adaptability. If you write an account creation script, the script must be able to ask, "What is the new employee's name?" and store that answer in memory to use later. In shell scripting, this dynamic memory is achieved through Variables. In this chapter, we will learn the strict syntactical rules for defining local variables, intercept keyboard data using the read command, and introduce the devastatingly powerful concept of Command Substitution—allowing our scripts to capture the output of native Linux commands directly into variable storage.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Declare and initialize string and numeric variables strictly.
  • Call (expand) variable data using the Dollar Sign ($).
  • Pause script execution to capture keyboard input using the read command.
  • Utilize built-in Unix Environment Variables (e.g., $USER, $HOME).
  • Store the standard output of terminal commands into variables using Command Substitution.

3. Declaring and Calling Variables

A variable is a labeled container in the computer's RAM.

1. Creating a Variable: To create a container, you write the name, an equals sign, and the data. *ABSOLUTE RULE:* You cannot have any spaces around the equals sign!

sh
12345678
#!/bin/sh

# Correct Syntax
CITY="Tokyo"
PORT=8080

# FATAL SYNTAX ERROR (Will crash the script)
# CITY = "Tokyo"

2. Calling a Variable: To pull the data out of the container to use it, prepend the Dollar Sign ($) to the variable name.

sh
1
echo "The target server is located in $CITY."

4. Reading User Input (read)

Scripts become interactive using the read command. When the shell encounters read, it pauses the script entirely, waits for the user to type on the keyboard, and presses Enter. It then takes that text and stuffs it into a variable.
sh
1234567
#!/bin/sh

echo "Enter the target IP address to deploy:"
# The script pauses here and waits for typing
read TARGET_IP

echo "Deployment sequence initiated for $TARGET_IP."

*Note: In advanced shells like Bash, read supports a -p flag for prompts. In strict POSIX sh scripting, you must use an echo statement before the read command, as shown above.*

5. Environment Variables

When your script runs, the operating system injects dozens of pre-configured "free" variables into your script. You do not have to define them; you simply call them.
  • $USER : The username of the person executing the script.
  • $PWD : Print Working Directory (where the script is running from).
  • $HOME : The path to the user's home folder.
  • $HOSTNAME : The network name of the physical server.
sh
12
#!/bin/sh
echo "Audit Log: Script executed by $USER on server $HOSTNAME."

6. Command Substitution (The Superpower)

What if you want to store the current date and time in a variable? You cannot just type TIME="date", because that literally stores the word "date", not the actual time. You must use Command Substitution. You wrap the Linux command inside $( ). The shell runs the command, catches the output, and stores it in the variable.
sh
123456789
#!/bin/sh

# The shell runs the 'date' command and stores the result
CURRENT_TIME=$(date)

# The shell runs the 'whoami' command and stores the result
ADMIN=$(whoami)

echo "At $CURRENT_TIME, the user $ADMIN modified the system."

*(Legacy Syntax Note: You may see older scripts using backticks ` date instead of $(). Both work, but $() is the modern, readable standard).*

7. Diagrams/Visual Suggestions

*Visual Concept: Command Substitution Mechanics* Draw a standard variable box:
TIME = [ ]. Above the box, draw a gear icon labeled date command. Draw an arrow from the gear dropping text (e.g., "Mon Oct 31 10:00") directly into the variable box. Below it, show the syntax representation: TIME=$(date). This clearly visualizes how a live terminal command is executed in a subshell and injected into variable storage.

8. Best Practices

  • Double Quotes Around Variables: Always place double quotes around your variables when printing them (e.g., echo "Hello $NAME"). If you use single quotes (echo 'Hello $NAME'), the shell will take it literally and print the exact text "$NAME" instead of the person's actual name.

9. Common Mistakes

  • Variable Isolation (The Underscore Trap): If you define FILE="report" and want to print reportbackup.txt, typing echo "$FILEbackup.txt" will fail. The shell looks for a variable literally named FILEbackup, finds nothing, and prints a blank space. You must isolate the variable using curly braces: echo "${FILE}backup.txt".

10. Mini Project: Build an Automated Server Greeter

Let's build an interactive script that dynamically pulls system data.
  1. 1. nano greeter.sh`
  1. 2. Write the code:
sh
1234567891011121314151617181920212223
#!/bin/sh

# Gather dynamic system data using Command Substitution
KERNEL_VER=$(uname -r)
UPTIME_STATS=$(uptime -p)

# Clear the screen for a clean UI
clear

echo "======================================"
echo "    SYSTEM DIAGNOSTIC INTERFACE       "
echo "======================================"

echo "Welcome, $USER."
echo "Please enter your Department ID:"
read DEPT_ID

echo ""
echo "Authenticating $USER for Department: $DEPT_ID..."
echo "Server Hostname : $HOSTNAME"
echo "Kernel Version  : $KERNEL_VER"
echo "System Uptime   : $UPTIME_STATS"
echo "======================================"
  1. 3. chmod +x greeter.sh
  1. 4. Run ./greeter.sh. You have built a fully interactive, dynamic terminal application!

11. Practice Exercises

  1. 1. Analyze the following variable declaration: IPADDR = "10.0.0.1". Why will this completely crash a shell script, and what is the exact fix?
  1. 2. Detail the functional mechanics of Command Substitution ($()). Why is it required when assigning dynamic system metrics (like active RAM usage) to a variable?

12. MCQs with Answers

Question 1

A script must pause its execution to allow an administrator to type a specific database name into the terminal. Which shell command facilitates this keyboard interception?

Question 2

An engineer needs to print a variable named TARGET, but immediately append the word "Server" to it without any spaces (e.g., producing the text WebNodeServer). Which syntax securely isolates the variable name to prevent evaluation errors?

13. Interview Questions

  • Q: Explain the operational difference between executing echo 'The user is $USER' and echo "The user is $USER". How does the shell interpreter treat single quotes versus double quotes?
  • Q: A legacy shell script contains the line DISKUSAGE=\df -h / | awk '{print $5}'\`. Explain what this syntax accomplishes, and describe the modern, POSIX-compliant alternative syntax that is universally preferred for nested substitution.
  • Q: Walk me through the exact scenario where the lack of spaces around the equals sign (=) in a variable assignment prevents the shell interpreter from misidentifying the variable name as an executable terminal command.

14. FAQs

Q: Do I need to declare the "type" of variable? (Like specifying it's an Integer or a String)? A: No. Unlike languages such as Java or C++, Shell scripting is "untyped". Everything is fundamentally treated as a text string.
x=5 is just the text character '5'. The shell only performs math on it if you explicitly use mathematical operators.

15. Summary

In Chapter 3, we breathed life into our static scripts by introducing dynamic memory architecture. We enforced the strict, space-free syntax required to assign strings and numbers to local variables, and we successfully extracted that data using the standard
$ expansion. We transitioned scripts from unilateral commands to interactive dialogues by intercepting keyboard data via the read utility. Finally, we unlocked the extraordinary power of Command Substitution ($()`), allowing our variables to ingest the live, standard output of complex Linux background commands.

16. Next Chapter Recommendation

Your script can store data, but what if you need to perform calculations or compare two pieces of data against each other? Proceed to Chapter 4: Working with Operators.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·