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.
Variables
name="Ana"sets a shell variable (no spaces around=);$nameor"${name}"uses it.export API_URL=https://...makes it an environment variable, visible to programs you start.$HOME,$USER,$PWDand$PATHare 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 pipefailmakes the script stop on errors and unset variables: use it in real scripts.exit 1signals failure;$?holds the last command's exit code (0 = success).
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?
Speeds the script upStops the script on errors, unset variables and failures inside pipelinesPrints every commandMakes variables global
Show answer
Answer: Stops the script on errors, unset variables and failures inside pipelines