Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SH
Bash Scripting
0/12 completed
Beginner
Your first scriptVariables and argumentsQuoting and expansionInput, output and redirection
Intermediate
Conditions and testsLoopsFunctionsArrays and string tricks
Advanced
Text processing: grep, sed and awkError handling and debugging
Pro
Cron and schedulingProduction-ready scripts
Tracks / Bash Scripting / Beginner

Variables and arguments

Scripts become useful when they work on different things each time: a different file, server, or user name. That's what variables and arguments are for.

Creating variables

bash
name="Asha"
city=Pune
count=3
echo "$name lives in $city and has $count cats."
Output
Asha lives in Pune and has 3 cats.

The rules are strict:

  • No spaces around =. name = "Asha" means "run a command called name with the arguments = and Asha".
  • Read a variable with $name. Write ${name} when letters follow it: "${name}_backup".
  • Names use letters, digits and _, and can't start with a digit. By convention, your own variables are lowercase; UPPERCASE is for environment variables like PATH and HOME.
bash
name = "Asha"
file="report"
echo "$file_2026.txt"     # Bash looks for a variable called file_2026
echo "${file}_2026.txt"
Output
bash: name: command not found
.txt
report_2026.txt

An unset variable is just empty, with no error. That's why typos are dangerous, and why ShellCheck and set -u (see Error handling) are so useful.

Everything is text

Bash variables hold strings. count=3 stores the character 3. To do math, use arithmetic expansion $(( )):

bash
apples=5
pears=7
echo "$apples + $pears"
echo "$(( apples + pears ))"
total=$(( apples * 2 + pears ))
echo "total: $total"
echo "10 / 3 = $(( 10 / 3 )), remainder $(( 10 % 3 ))"
(( apples++ ))
echo "apples now: $apples"
Output
5 + 7
12
total: 17
10 / 3 = 3, remainder 1
apples now: 6

Inside $(( )) you don't need $ before variable names. Bash only does whole-number math: 10 / 3 is 3. For decimals, call bc or awk:

bash
echo "scale=2; 10 / 3" | bc
awk 'BEGIN { printf "%.2f\n", 10 / 3 }'
Output
3.33
3.33

Command substitution

$(command) runs a command and uses its output as a value. It's how scripts collect information:

bash
today=$(date -u +%F)
lines=$(wc -l < /etc/passwd)
kernel=$(uname -s)
echo "On $today this $kernel machine has $lines user accounts."
backup="backup-$(date -u +%Y%m%d).tar.gz"
echo "$backup"
Output
On 2026-11-22 this Linux machine has 21 user accounts.
backup-20261122.tar.gz

You may see the old backtick form `date` in older scripts. It does the same thing, but $( ) is easier to read and can be nested.

Script arguments

Words you type after a script's name arrive as positional parameters:

Variable Holds
$0 The script's name
$1, $2, … ${10} The first, second, … tenth argument
$# How many arguments there are
"$@" All arguments, each kept separate (use this one)
"$*" All arguments joined into one string
greet.sh
#!/usr/bin/env bash
echo "Script: $0"
echo "You gave me $# argument(s)."
echo "First: $1"
echo "Second: $2"
for arg in "$@"; do
  echo "  - $arg"
done
bash
chmod +x greet.sh
./greet.sh Asha "Ravi Kumar" Lee
Output
Script: ./greet.sh
You gave me 3 argument(s).
First: Asha
Second: Ravi Kumar
  - Asha
  - Ravi Kumar
  - Lee

Quotes group words: "Ravi Kumar" is one argument. And "$@" kept it in one piece. You'll see why that matters in the next lesson.

Default values

What if an argument is missing? Use ${var:-default}:

deploy.sh
#!/usr/bin/env bash
env=${1:-staging}
branch=${2:-main}
echo "Deploying $branch to $env"
bash
chmod +x deploy.sh
./deploy.sh
./deploy.sh production
./deploy.sh production release-2.4
Output
Deploying main to staging
Deploying main to production
Deploying release-2.4 to production
Syntax Meaning
${var:-text} Use text if var is unset or empty
${var:=text} Same, and also assign text to var
${var:?message} Stop the script with message if var is unset or empty
${var:+text} Use text only if var is set

${1:?} is a quick way to insist on a required argument:

backup.sh
#!/usr/bin/env bash
folder=${1:?usage: backup.sh FOLDER}
echo "Backing up $folder"
bash
bash backup.sh
echo "exit code: $?"
bash backup.sh /var/www
Output
backup.sh: line 2: 1: usage: backup.sh FOLDER
exit code: 1
Backing up /var/www

shift

shift drops $1 and moves every argument down one place. It's handy when the first argument is a command and the rest are its inputs:

tool.sh
#!/usr/bin/env bash
action=$1
shift
echo "action: $action"
echo "remaining ($#): $*"
bash
bash tool.sh resize photo1.jpg photo2.jpg
Output
action: resize
remaining (2): photo1.jpg photo2.jpg

Environment variables

Some variables are exported to every program the shell starts. They're called environment variables, and they're how configuration reaches programs (for example DATABASE_URL, NODE_ENV, PORT).

bash
echo "home: $HOME, user: $USER, shell: $SHELL"
greeting="hi"
bash -c 'echo "child sees greeting=[$greeting]"'
export greeting
bash -c 'echo "child sees greeting=[$greeting]"'
PORT=8080 bash -c 'echo "PORT for this one command: $PORT"'
echo "PORT afterwards: [$PORT]"
Output
home: /home/you, user: you, shell: /bin/bash
child sees greeting=[]
child sees greeting=[hi]
PORT for this one command: 8080
PORT afterwards: []
  • A plain variable lives only in the current shell.
  • export copies it into the environment of every program started afterwards.
  • NAME=value command sets a variable just for that one command. It's common in package.json scripts and Dockerfiles.

Child processes get a copy: a script can't change its parent shell's variables. That's why cd inside a script doesn't move your terminal. To run a file in your current shell (for example to load settings), use source file (or . file).

Reading configuration from a file

A tiny .env file of KEY=value lines can be loaded with source:

app.env
APP_NAME="Shop API"
PORT=3000
DEBUG=true
bash
set -a          # export every variable assigned from now on
source app.env
set +a
echo "$APP_NAME on port $PORT (debug: $DEBUG)"
bash -c 'echo "a child process sees PORT=$PORT"'
Output
Shop API on port 3000 (debug: true)
a child process sees PORT=3000

⚠️ source runs the file as Bash code. Only source files you trust.

Read-only and local variables

bash
readonly VERSION="1.4.0"
VERSION="2.0"
echo "still $VERSION"
Output
bash: VERSION: readonly variable
still 1.4.0

readonly (or declare -r) protects constants. Inside functions, local keeps a variable from leaking out; you'll use it in the Functions lesson.

Practice

  1. Write rect.sh that takes a width and height as arguments and prints the area and perimeter. Default both to 1.
  2. Make hello.sh print Hello, NAME using $1, or Hello, stranger when no name is given.
  3. Print a file name like log-2026-11-22.txt using $(date +%F).
✎ Check your understanding

1.What's wrong with count = 5?

2.A script is run as ./copy.sh "my file.txt" /tmp. What is $#?

3.What does ${1:-8080} give when the script gets no arguments?

4.What does echo $(( 7 / 2 )) print?

← Your first script