Setting A Variable
Part of the Fundamentals section of Coddy's Terminal journey — lesson 62 of 82.
You've learned how to view environment variables, but you can also create your own. To set a variable in your current shell session, use the assignment syntax with no spaces around the equals sign:
MY_NAME="Alice"The variable name is on the left, and the value is on the right. Once set, you can access it using the $ prefix:
echo $MY_NAMEThis outputs Alice.
Notice there are no spaces around the = sign. This is important because spaces would cause an error. The shell would interpret MY_NAME = "Alice" as trying to run a command called MY_NAME with arguments.
You can use variables to store any text value, including paths or configuration settings:
PROJECT_DIR="/home/user/projects"
echo $PROJECT_DIRVariables set this way only exist in your current shell session. If you close the terminal and open a new one, the variable will be gone.
In the next lesson, you'll learn how to make variables available to other programs using export.
Challenge
EasyCreate a variable called GREETING and set its value to Hello, Terminal!
Then use echo to display the value of your new variable.
Remember: no spaces around the = sign when setting the variable, and use the $ prefix when accessing its value.
Your output should be:
Hello, Terminal!Hint: First set the variable with
GREETING="Hello, Terminal!", then display it withecho $GREETING
Cheat sheet
To create a variable in your current shell session, use the assignment syntax with no spaces around the equals sign:
MY_NAME="Alice"To access a variable, use the $ prefix:
echo $MY_NAMEVariables can store any text value, including paths or configuration settings:
PROJECT_DIR="/home/user/projects"
echo $PROJECT_DIRImportant: No spaces around the = sign. Spaces would cause the shell to interpret the variable name as a command.
Variables set this way only exist in your current shell session and are lost when the terminal is closed.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Directories
Create A DirectoryCopy A DirectoryMove And Rename A DirectoryDelete A DirectoryRecap - Directory Operations7File Content
Head And TailWord CountSort CommandUnique CommandGrep BasicsGrep With FlagsRecap - Text Detective2Navigation
Print Working DirectoryList FilesChange DirectoryAbsolute vs Relative PathsHome And Root DirectoryRecap - Find Your Way8Redirection
Standard OutputOverwrite To A FileAppend To A FileStandard InputStandard ErrorRecap - Log Builder6Wildcards And Patterns
The Star WildcardThe Question Mark WildcardBracket WildcardsCombining WildcardsRecap - Selective Operations9Piping
What Is A PipeChaining Two CommandsChaining Multiple CommandsPipe With GrepRecap - Data Pipeline12Environment
Environment VariablesView All VariablesThe PATH VariableSetting A VariableExport A VariableThe Profile FileRecap - Custom Environment