0
0
Bash Scriptingscripting~10 mins

Variable assignment (no spaces around =) in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Variable assignment (no spaces around =)
Start
Write variable name
Write = with NO spaces
Write value
Variable assigned
Use variable later
Assign a value to a variable by writing name=value with no spaces around =, then use the variable.
Execution Sample
Bash Scripting
name=John
age=30

# Print variables
echo $name
Assigns values to variables 'name' and 'age' without spaces, then prints the value of 'name'.
Execution Table
StepCode LineActionVariableValueOutput
1name=JohnAssign value to variable 'name'nameJohn
2age=30Assign value to variable 'age'age30
3echo $namePrint value of 'name'nameJohnJohn
4End of script
💡 Script ends after printing the value of 'name'.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
nameundefinedJohnJohnJohn
ageundefinedundefined3030
Key Moments - 2 Insights
Why can't I put spaces around the = sign in bash variable assignment?
In bash, spaces around = cause errors because the shell treats spaces as separators. See execution_table steps 1 and 2 where assignment works only without spaces.
What happens if I try to assign with spaces like 'name = John'?
Bash treats 'name' as a command and '= John' as arguments, causing an error. This is why no spaces are allowed, as shown in the successful assignments in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'age' after step 1?
A30
Bundefined
CJohn
Dempty string
💡 Hint
Check the variable_tracker table under 'age' after step 1.
At which step does the script print output?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Output' column in the execution_table.
If you add spaces like 'name = John', what will happen?
ABash throws an error or treats 'name' as a command
BVariable 'name' gets assigned 'John'
CVariable 'name' gets assigned '= John'
DVariable 'name' gets assigned empty string
💡 Hint
Refer to key_moments explanation about spaces around '='.
Concept Snapshot
Bash variable assignment:
Use name=value with NO spaces around '='.
Spaces cause errors because shell splits tokens.
Access variable with $name.
Example:
name=John
age=30
echo $name
Full Transcript
In bash scripting, to assign a value to a variable, write the variable name, then an equal sign with no spaces, then the value. For example, name=John assigns 'John' to the variable 'name'. Spaces around the equal sign cause errors because bash treats spaces as separators. After assignment, you can use the variable by prefixing it with a dollar sign, like echo $name to print its value. The execution table shows step-by-step how variables 'name' and 'age' get assigned and how the value of 'name' is printed. Remember, no spaces around '=' in assignments.