How to understand Environment Variables in BASH

How To Understand Environment Variables In BASH

Environment variables play a crucial role in the BASH shell, allowing you to customize and configure your shell environment. In this article, we’ll explore various examples of how to work with environment variables in BASH.

  1. Viewing Environment Variables: To view all the environment variables currently set in your BASH session, you can use the env command or printenv command. For example:

$ env
$ printenv
  1. Setting Environment Variables: You can set environment variables using the export command. Here’s an example:

$ export MY_VARIABLE="Hello, World!"
  1. Accessing Environment Variables: To access the value of an environment variable, you can use the $ symbol followed by the variable name. For example:

$ echo $MY_VARIABLE
  1. Default Values: If an environment variable is not set, you can provide a default value using the ${VAR_NAME:-default} syntax. Here’s an example:

$ echo ${UNKNOWN_VARIABLE:-"No value found."}
  1. Modifying Environment Variables: You can modify the value of an environment variable using the = operator. For example:

$ MY_VARIABLE="New value" 
  1. Environment Variables in Scripts: To use environment variables in a BASH script, you can export them before running the script. For example:

$ export MY_VARIABLE="Hello, World!"
$ ./my_script.sh
  1. PATH Variable: The PATH variable specifies the directories where the shell looks for executable files. You can append directories to the PATH variable to make your scripts or programs accessible. For example:

$ export PATH=$PATH:/path/to/new_directory
  1. HOME Variable: The HOME variable stores the home directory of the current user. You can use it to refer to the home directory in your scripts. For example:

$ echo $HOME
  1. USER Variable: The USER variable holds the username of the current user. You can use it to perform actions based on the current user. For example:

$ echo $USER
  1. PS1 Variable: The PS1 variable defines the format of your shell prompt. You can customize it to display useful information. For example:

$ export PS1="\u@\h:\w\$ "

 

Conclusion:

Understanding and utilizing environment variables in BASH can greatly enhance your command-line experience. With the examples provided in this article, you should now have a better grasp of how to work with environment variables.