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
name="Asha"
city=Pune
count=3
echo "$name lives in $city and has $count cats."Asha lives in Pune and has 3 cats.
The rules are strict:
- No spaces around
=.name = "Asha"means "run a command callednamewith the arguments=andAsha". - 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 likePATHandHOME.
name = "Asha"
file="report"
echo "$file_2026.txt" # Bash looks for a variable called file_2026
echo "${file}_2026.txt"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 $(( )):
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"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:
echo "scale=2; 10 / 3" | bc
awk 'BEGIN { printf "%.2f\n", 10 / 3 }'3.33 3.33
Command substitution
$(command) runs a command and uses its output as a value. It's how scripts collect information:
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"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 |
#!/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"
donechmod +x greet.sh
./greet.sh Asha "Ravi Kumar" LeeScript: ./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}:
#!/usr/bin/env bash
env=${1:-staging}
branch=${2:-main}
echo "Deploying $branch to $env"chmod +x deploy.sh
./deploy.sh
./deploy.sh production
./deploy.sh production release-2.4Deploying 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:
#!/usr/bin/env bash
folder=${1:?usage: backup.sh FOLDER}
echo "Backing up $folder"bash backup.sh
echo "exit code: $?"
bash backup.sh /var/wwwbackup.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:
#!/usr/bin/env bash
action=$1
shift
echo "action: $action"
echo "remaining ($#): $*"bash tool.sh resize photo1.jpg photo2.jpgaction: 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).
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]"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.
exportcopies it into the environment of every program started afterwards.NAME=value commandsets a variable just for that one command. It's common inpackage.jsonscripts 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_NAME="Shop API"
PORT=3000
DEBUG=trueset -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"'Shop API on port 3000 (debug: true) a child process sees PORT=3000
⚠️
sourceruns the file as Bash code. Only source files you trust.
Read-only and local variables
readonly VERSION="1.4.0"
VERSION="2.0"
echo "still $VERSION"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
- Write
rect.shthat takes a width and height as arguments and prints the area and perimeter. Default both to1. - Make
hello.shprintHello, NAMEusing$1, orHello, strangerwhen no name is given. - Print a file name like
log-2026-11-22.txtusing$(date +%F).
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?