Zsh Variables & Data Types - Shell Scripting Tutorial for Beginners (Lesson 7)
Video: Zsh Variables & Data Types - Shell Scripting Tutorial for Beginners (Lesson 7) by Taught by Celeste AI - AI Coding Coach
Watch full page →Zsh Variables & Data Types - Shell Scripting Tutorial for Beginners (Lesson 7)
In this lesson, you will learn how to declare and use variables in Zsh scripting, including the correct syntax and differences between single and double quotes. You'll also explore arithmetic operations and how to manage environment variables using commands like export, readonly, and unset.
Code
# Declaring variables (no spaces around '=')
name="Alice"
age=30
city='New York'
# Accessing variables
echo "Name: $name"
echo "Age: ${age}"
echo "City: $city"
# Combining variables with text (curly braces help)
file_backup="backup"
echo "File backup: $file_backup" # prints "backup"
echo "Filebackup: ${file_backup}" # prints "backup"
# String quoting
fruit="apple"
echo "Double quotes expand variable: $fruit" # prints "apple"
echo 'Single quotes treat literally: $fruit' # prints "$fruit"
echo "Escape dollar sign: \$fruit" # prints "$fruit"
# Arithmetic operations using $(( ))
result=$((5 + 3))
echo "5 + 3 = $result" # prints 8
count=0
((count++)) # increments count by 1
echo "Count after increment: $count" # prints 1
# Environment variables
echo "Home directory: $HOME"
echo "Current user: $USER"
echo "Current shell: $SHELL"
# Exporting a variable to child processes
export MYVAR="Hello"
echo "MYVAR is $MYVAR"
# Making a variable readonly
readonly PI=3.14
# PI=3.15 # This would cause an error
# Unsetting a variable
temp="temporary"
echo "Temp before unset: $temp"
unset temp
echo "Temp after unset: $temp" # prints nothing
Key Points
- Declare variables with no spaces around the equal sign, e.g.,
name="value". - Double quotes allow variable expansion, while single quotes treat content literally.
- Use
$(( ))for arithmetic operations like addition, subtraction, and increments. - Environment variables like
HOME,USER, andSHELLprovide system info. exportshares variables with child processes;readonlyprevents changes;unsetdeletes variables.