Shell variables vs. Environment variables

I've been doing a lot of work within the AWS Command Line and it's been forcing me to make the best use of environment and shell variables. Below are really simple examples of how to store both types.

Environment Variables

Environmental variables are system variables that cannot be changed by any user. Although they are dynamic in nature, they do not change much.

View a list of your environment variables.

printenv

View the details of a specific environmental variable.

echo $HOME

Shell Variables

Shell variables are also known as user variables. They do vary based on the user and their permissions. Think of these as temporary variables that will disappear once you close your terminal window.

List all shell variables.

set

Create a shell variable.

MY_NAME_IS=chris

View the details of a specific shell variable.

echo $MY_NAME_IS

Find your shell variable with only partial information.

set | grep MY

Note: Once you close your terminal account, they may dissapear.


Advanced Variable Assignment

You can assign more complicated strings to shell variables but they require a bit more work. Since we're only using Terminal right now, here's how to create a JSON file using cat. cat will allow you to create a multiline text file and export it.

cat << 'EOF' > myjson.json
{
  "fname": "chris", 
  "lname": "mendez", 
  "city": "los angeles", 
}
EOF

Once you've created a JSON file, you can then assign the JSON to a shell variable.

JSON=$(cat myjson.json)

View JSON variable.

echo $JSON

Other tools

You can use declare to show both types of variables.

declare -p

Show only environmental variables.

declare -xp

Resources