Variables and User Input
# 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 theread 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
readcommand.
-
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!
2. Calling a Variable:
To pull the data out of the container to use it, prepend the Dollar Sign ($) to the variable name.
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.
*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.
6. Command Substitution (The Superpower)
What if you want to store the current date and time in a variable? You cannot just typeTIME="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.
*(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.
nano greeter.sh`
- 2. Write the code:
-
3.
chmod +x greeter.sh
-
4.
Run
./greeter.sh. You have built a fully interactive, dynamic terminal application!
11. Practice Exercises
-
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?
-
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
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?
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'andecho "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.