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.
In this page:
Syntax
$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 $?)
#!/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: $?"
Login to try C/C++/Java/PHP code in the editor
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
- Using
$?after another command has run, so it holds the wrong exit status. - Forgetting to quote
"$@", so arguments with spaces are split. - Expecting
$0to always be the script name, when it may include the path used to call it.
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: