Phase 2Master bash

#8 Variables and bash scripts

$VAR, export, loops

Environment variables

The system maintains environment variables that contain useful information. You access them with the $ prefix:

System variables
$ echo $HOME
/home/user

$ echo $USER
user

Some common variables: $HOME (home directory), $USER (username), $PATH (executable paths), $PWD (current directory).

Declaring your own variables

You create a variable using the format NAME=value. Important: no spaces around the = sign!

Create and use a variable
$ NAME="Alice"
$ echo $NAME
Alice

$ FILE="report.txt"
$ cat $FILE

Variables created this way are only visible in the current shell.

export -- Share variables

By default, a variable is not passed to child processes (scripts, subshells). To make it available everywhere, use export:

Export a variable
$ export MY_VAR="test"
$ echo $MY_VAR
test

# MY_VAR is now accessible in scripts launched from this shell

Creating a bash script

A bash script is a text file containing a series of commands. The first line must be the shebang #!/bin/bash which indicates which interpreter to use:

Example: script.sh
#!/bin/bash

# For loop
for NAME in Alice Bob Charlie; do
  echo "Hello $NAME!"
done

You run the script with bash script.sh or, after making it executable with chmod +x, directly with ./script.sh:

Run a script
$ bash script.sh
Hello Alice!
Hello Bob!
Hello Charlie!

For loop and if condition

The for loop allows you to repeat commands for each item in a list:

For loop
for FILE in *.txt; do
  echo "Processing $FILE"
done

The if structure allows you to execute code based on a condition:

If condition
if [ -f "notes.txt" ]; then
  echo "The file exists"
else
  echo "File not found"
fi

Arithmetic operations

Bash allows you to perform calculations with the $(( )) syntax:

Calculations
$ echo $((2 + 3))
5

$ echo $((10 * 4))
40

Summary

Summary
NAME="value"         # Declare a variable
echo $NAME           # Use a variable
export NAME="value"  # Export for subprocesses
bash script.sh       # Run a script
./script.sh          # Run (if chmod +x)
echo $((2 + 3))      # Arithmetic operation

Your turn

Try creating variables, using export, and running bash script.sh in the terminal below.

terminal — bash
user@stemlegacy:~$