Variables let you store data and reuse it. In shell scripts they are a bit different from other languages — no types, no declarations, and some surprising rules about spaces. Get the rules down and variables become incredibly handy.
Assigning and using variables
To assign a variable, use NAME=value. No spaces around the =. To use the value, put a $ in front of the name: $NAME. Curly braces like ${NAME} are optional but help when the variable name runs into other text.
$ NAME="Alice"
$ echo $NAME
Alice
$ echo "Hello, ${NAME}!"
Hello, Alice!
Try it Yourself →
Quoting matters
Double quotes let variables expand. Single quotes treat everything as literal text. This is one of the most common sources of bugs in shell scripts.
$ COLOR="blue"
$ echo "The sky is $COLOR"
The sky is blue
$ echo 'The sky is $COLOR'
The sky is $COLOR
Try it Yourself →
Script arguments: $1, $2, etc.
When you run a script, you can pass arguments. Inside the script, $1 is the first argument, $2 is the second, and so on. $# gives you the count of arguments. $@ gives you all of them.
#!/bin/bash
echo "Hello, $1!"
echo "You passed $# arguments"
echo "All arguments: $@"
Run it: ./greet.sh Alice friend prints "Hello, Alice!" and "You passed 2 arguments" and "All arguments: Alice friend".
Special variables
The shell has several built-in variables. $HOME is your home directory. $USER is your username. $PWD is the current directory. $? holds the exit code of the last command — 0 means success, anything else means failure.
$ echo "Home: $HOME"
Home: /home/alice
$ echo "User: $USER"
User: alice
$ ls /nonexistent
ls: /nonexistent: No such file or directory
$ echo $?
1
Try it Yourself →