Git & Command Line Tutorial · Command Line Basics · Lesson 6 of 20

Variables, PATH and Your First Script

Use shell and environment variables, understand PATH and which, and write a reusable bash script with arguments and exit codes.

Create a free account to save this page, take notes and track your progress. Sign in

Variables

  • name="Ana" sets a shell variable (no spaces around =); $name or "${name}" uses it.
  • export API_URL=https://... makes it an environment variable, visible to programs you start.
  • $HOME, $USER, $PWD and $PATH are set for you.

PATH is the list of folders the shell searches for commands. which python3 shows which file runs. Installing a tool usually means putting it in a folder on your PATH.

Scripts

A script is a text file of commands. Start it with #!/usr/bin/env bash, make it executable with chmod +x deploy.sh, and run ./deploy.sh. Inside:

  • $1, $2… are arguments, $# their count, $@ all of them.
  • set -euo pipefail makes the script stop on errors and unset variables: use it in real scripts.
  • exit 1 signals failure; $? holds the last command's exit code (0 = success).
A bash script with arguments, validation and exit codes
cat > greet.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

name="${1:-world}"            # first argument, or "world" if missing
times="${2:-1}"
if ! [[ "$times" =~ ^[0-9]+$ ]]; then
  echo "usage: ./greet.sh NAME [TIMES]" >&2
  exit 1
fi
for ((i = 1; i <= times; i++)); do
  echo "Hello, $name! ($i/$times)"
done
EOF
chmod +x greet.sh

./greet.sh
./greet.sh Ana 2
./greet.sh Ben lots 2>/dev/null || echo "exit code: $?"

export GREETING_STYLE=formal
bash -c 'echo "a child process sees GREETING_STYLE=$GREETING_STYLE"'
echo "bash lives at: $(which bash)"

Output

Hello, world! (1/1)
Hello, Ana! (1/2)
Hello, Ana! (2/2)
exit code: 1
a child process sees GREETING_STYLE=formal
bash lives at: /usr/bin/bash

Run this on your computer — see “Get Started” for setup.

Test yourself

What does set -euo pipefail do in a bash script?

  1. Speeds the script up
  2. Stops the script on errors, unset variables and failures inside pipelines
  3. Prints every command
  4. Makes variables global
Show answer

Answer: Stops the script on errors, unset variables and failures inside pipelines

Was this page helpful?