Overview
This lecture explains how to assign variables in Bash, covering variable scope (local vs global), assignment methods, and useful built-in commands like let and read.
Variable Scope: Local vs Global
- Local variables are defined inside functions or code blocks and only accessible there.
- Global variables are defined outside functions/blocks and accessible everywhere in the script.
- Local variables' values are lost once the function/block ends.
- Echoing a variable outside a function displays the global variable value.
Single Variable Assignment
- Assign variables using
var_name=value with no spaces around =.
- Bash does not require specifying data type during assignment.
Integer Assignment
- Assign integers directly, e.g.,
num=1.
String Assignment
- Assign single words without quotes; multi-word strings use single (
') or double (") quotes.
- Single quotes prevent variable expansion; double quotes allow expansion.
Boolean Assignment
- Assign booleans as
true_val=true and false_val=false.
- Use these variables in conditionals to control script flow.
Multi-variable Assignment
- Assign multiple variables in one line, e.g.,
a=1 b=2 c=3.
Default Value Assignment
- Use
${var:-default} to assign a default if var is undefined.
- This prevents errors from uninitialized variables.
Using let Command for Assignments
let is used for numeric assignments and arithmetic/bitwise/logical operations.
- Example:
let "num2 = num1 + 2" performs addition.
Using read Command
read gets user input and assigns it to variables.
read animal color splits user input into two variables.
- Use
-p for prompt text, -s for silent input (useful for passwords), -a to read into arrays.
Key Terms & Definitions
- Variable — Named storage location for values in a script.
- Local Variable — Variable scoped within a function/block.
- Global Variable — Variable accessible throughout a script.
- let command — Bash built-in for arithmetic and logical operations.
- read command — Bash built-in for reading user input.
Action Items / Next Steps
- Practice assigning and using variables with various data types in Bash.
- Experiment with
let and read commands.
- Use default value assignment to avoid uninitialized variables.