← Back to Bash Course | Chapter 2: Variables & Types | Lesson 11 of 13

Special Variables ($0 $1 $?)

Special variables are like the name tag and the delivery slip on a package: one tells you the script's own name, some hold the items handed to it, and one tells you whether the last job went well.
Syntax
bash
$0    # script name
$1    # first argument
$#    # argument count
$?    # exit status of last command

Special Variables ($0 $1 $?)

$0 is the script's own name, $1, $2, etc. are positional arguments passed to the script, and $? holds the exit status of the most recently run command.

$# gives the number of arguments, and $@ expands to all of them. These special variables are essential for writing scripts that accept input and check for errors.

Note: Always check $? right after the command you care about — it gets overwritten by every subsequent command.

Example: Special Variables ($0 $1 $?)

bash
#!/bin/bash
echo "Script name: $0"
echo "First arg: $1"
echo "Arg count: $#"

true
echo "Exit status of true: $?"

false
echo "Exit status of false: $?"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using $? after another command has run, so it holds the wrong exit status.
  2. Forgetting to quote "$@", so arguments with spaces are split.
  3. Expecting $0 to always be the script name, when it may include the path used to call it.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.