Module 2: Variables, Quoting & Input/Output
In this module, you will learn how to use variables, understand quoting rules,
and work with basic input and output in Bash scripts.
These are the foundation of any dynamic shell script.
✅ Variables in Bash
- Variables store data that can be reused in scripts.
- No data types – everything is treated as a string unless used in arithmetic.
- Define variables without spaces around the equals sign:
#!/bin/bash
name="Alice"
age=25
echo "My name is $name and I am $age years old."
Output:
My name is Alice and I am 25 years old.
✅ Environment Variables
- Environment variables are predefined system variables.
- Examples:
$HOME,$USER,$PATH. - Display all environment variables with:
printenv
echo "Logged in as: $USER"
✅ Quoting in Bash
- Double quotes (” “): Allow variable expansion.
- Single quotes (‘ ‘): Treat everything literally (no expansion).
- Backticks or $(): Command substitution.
#!/bin/bash
echo "Double quotes: Hello $USER"
echo 'Single quotes: Hello $USER'
echo "Today is $(date)"
Output (example):
Double quotes: Hello alice
Single quotes: Hello $USER
Today is Tue Sep 2 12:34:56 IST 2025
✅ Input with read
- Use
readto take input from the user. - Syntax:
read variable_name
#!/bin/bash
echo "Enter your city:"
read city
echo "You live in $city."
✅ Redirecting Input/Output
>→ Redirect output (overwrite file)>>→ Append output<→ Redirect input|→ Pipe output to another command
echo "Hello World" > output.txt # overwrite
echo "Another line" >> output.txt # append
cat < output.txt # input redirection
ls -l | grep ".sh" # pipe example
✅ Summary
- Variables store reusable values with
name=valueformat. - Environment variables like
$USERand$HOMEare system-wide. - Double quotes allow expansion, single quotes prevent it.
readtakes input, and redirection manages file I/O.- Pipes (
|) send output of one command to another.
✅ By the end of this module, you can use variables, handle input/output,
and apply quoting rules to build interactive scripts.
