questions about bash variables

Hello! Here are some questions & answers. The goal isn't to get all the questions "right". Instead, the goal is to learn something! If you find a topic you're interested in learning more about, I'd encourage you to look it up and learn more.

which ones(s) of these are valid ways to set a variable in bash?
$animal=panda
$animal = panda
ANIMAL=panda
animal=panda
animal = panda

only ANIMAL=panda and animal=panda are valid

Also, ANIMAL=panda and animal=panda will set different variables: variable names are case sensitive.

do you always need a $ to print out the value of a variable? (like $VARNAME?)

yes!

here's what setting & printing out a variable looks like:

x=2
echo $x

what does the code
animal = panda
do?

it runs the program 'animal' with the arguments '=' and 'panda'

That's almost certainly not what you wanted to do if you typed that, but that's what it does!

Will this code:
FILENAME="file 1.txt"
cat $FILENAME
print out the contents of file 1.txt?

no!

$ cat $FILENAME will run `cat` with 2 arguments: `file` and `1.txt`.

Always double quote your variables to prevent this: $ cat "$FILENAME" instead

You have a variable called filename. What bash code will print out the value of filename with 2 after it? (no spaces)

echo ${filename}2

The way to concatenate bash strings is by just putting them next to each other. ${filename} is another way to refer to $filename

do these two lines of code do the same thing?
x=2
x="2"

yes!

there are no numbers in bash

is every bash variable an environment variable?

nope!

in bash, environment variables are referred to the same way as regular variables ($VARNAME), but not all variables are environment variables

how can you tell if a bash variable is an environment variable?

one option:
env | grep VARNAME

env prints out all environment variables you have set, so you can grep its output

how do you set an environment variable?

export VARNAME=value

you can also turn a non-environment variable into an environment variable, like this:

VARNAME=value
export VARNAME

do child processes inherit environment variables?

yes!

for example, when you run env, what it's actually doing is just printing out all its environment variables. These are the same as the environment variables in your shell because env inherits all the environment variables from your shell.

do child processes inherit shell variables that aren't environment variables?

nope!

if you started a subprocess in a Python program, you wouldn't expect the subprocess to automatically get all of your Python's program's variables -- it's the same with bash shell variables.

more reading