Master Bash Built‑In Variables: From $0 to $PATH Explained with Real Examples
This guide explains Bash’s built‑in variables—$0, positional parameters $1…$9, special parameters like $#, $*, "$*", $@, "$@", $!, $_, $$, $PPID, $?, $BASH, $BASH_VERSION, $EUID, $UID, $GROUPS, $HOME, $HOSTNAME, $IFS, $PATH, $OLDPWD, $PWD, $PS1, $PS2, $PS4—detailing their meanings, typical use cases, and providing runnable code snippets and output illustrations.
Bash provides a rich set of built‑in variables that simplify script writing and system interaction. This article introduces each variable, explains its purpose, and shows practical examples.
$0 – Script Name
When a Bash script runs, the variable $0 holds the script's name. Because it reflects the actual file name, renaming the script does not require changes inside the script.
#!/bin/bash
ARGS=3 # this script needs 3 arguments
E_BADARGS=65 # wrong number of arguments
echo "Args number is : $#"
echo $0
if [ $# -ne "$ARGS" ]; then
echo "Usage: $(basename $0) first-parameter second-parameter third-parameter"
exit $E_BADARGS
fi
# start doing real workUsing $(basename $0) removes the path, producing a cleaner output.
Positional Parameters $1, $2, …
Parameters $0, $1, $2, … are called positional parameters. They represent command‑line arguments passed to the script.
#!/bin/bash
echo $1
echo $2
echo $3$# – Number of Arguments
The variable $# holds the count of positional parameters.
$* and "${*}" – All Parameters as One String
$*expands to all arguments separated by the first character of $IFS. Quoted "$*" treats the entire list as a single word.
for arg in $*; do
echo $arg
donefor arg in "$*"; do
echo $arg
done$@ and "${@}" – All Parameters as Separate Words
$@behaves like $* when unquoted, but "$@" expands each argument as a distinct word, which is usually desired.
for arg in "$@"; do
echo $arg
doneA common use case is processing arguments in a Docker‑based Node.js script:
if [ "$1" = 'node' ]; then
SCRIPT_FILE=''
for ARG in "$@"; do
if [ "${ARG}" = 'main.js' ]; then
SCRIPT_FILE='main.js'
break
fi
done
if [ -z "$SCRIPT_FILE" ]; then
exec "$@" "main.js"
exit 0
fi
fi
exec "$@"$! – PID of Last Background Job
The variable $! stores the process ID of the most recent background command.
$ sleep 60 &
[1] 6238
$ echo "$!"
6238When multiple jobs run in background, you can capture each PID and wait for them:
$ sleep 60 &
pid1=$!
$ sleep 100 &
pid2=$!
$ wait $pid1
$ wait $pid2$_ – Last Argument of Previous Command
$_holds the last argument of the previous command.
#!/bin/bash
echo $_ # prints ./test.sh
du >/dev/null # no output
echo $_ # prints du
ls -al >/dev/null
echo $_ # prints -alYou can also use $_ to change to the directory just created:
$ mkdir hello && cd $_$$ – PID of the Current Script
$PPID – Parent Process ID
The variable $PPID contains the PID of the script's parent process.
$? – Exit Status of Last Command
$?stores the exit code of the most recent command (0 for success, non‑zero for failure). It is also used to capture a function's return status or a script's final exit code.
#!/bin/bash
set -x
go get -d -v golang.org/x/net/html
go get -u github.com/jstemmer/go-junit-report
go test -v 2>&1 >tmp
status=$?
$GOPATH/bin/go-junit-report < tmp > test_output.xml
exit ${status}The above script saves the exit status of go test into status and returns it.
$BASH and $BASH_VERSION
$BASHgives the full path to the Bash binary, while $BASH_VERSION shows the installed version.
$EUID and $UID
$EUIDis the effective user ID, while $UID is the real user ID (read‑only).
$GROUPS – User's Group List
$HOME and $HOSTNAME
$HOMEpoints to the user's home directory (e.g., /home/username), and $HOSTNAME is the machine's network name.
$IFS – Internal Field Separator
$IFSdefines how Bash splits strings into words. By default it includes space, tab, and newline, but it can be changed (e.g., to a comma for CSV parsing).
#!/bin/bash
output_args_one_per_line() {
for arg; do
echo "[${arg}]"
done
}
echo "IFS= "
echo "-------"
IFS=" "
var=" a b c "
output_args_one_per_line $var
echo
echo "IFS=:"
echo "-----"
IFS=:
var=":a::b:c:::" # colon‑separated list with empty fields
output_args_one_per_line $var
exit 0$PATH – Executable Search Path
$PATHis a colon‑separated list of directories Bash searches for executables. You can temporarily prepend a directory: PATH=${PATH}:/opt/bin Adding the current directory to $PATH is discouraged for security reasons.
$OLDPWD and $PWD
$OLDPWDstores the previous working directory; you can return to it with cd -. $PWD holds the current directory, equivalent to the pwd command.
A script that safely deletes files only when it is in the intended directory:
#!/bin/bash
E_WRONG_DIRECTORY=73
clear
TargetDirectory=/home/nick/testdir
cd $TargetDirectory
echo "Deleting stale files in $TargetDirectory."
if [ "$PWD" != "$TargetDirectory" ]; then
echo "Wrong directory!"
echo "In $PWD, rather than $TargetDirectory!"
echo "Bailing out!"
exit $E_WRONG_DIRECTORY
fi
rm -rf *
rm .[A-Za-z0-9]*
echo "Done."
echo "Old files deleted in $TargetDirectory."
exit 0$PS1, $PS2, $PS4 – Prompt Variables
$PS1is the primary command prompt, often customized with colors. $PS2 appears for multiline input (default ">"). $PS4 prefixes each line when tracing with set -x (default "+").
Running a script with tracing demonstrates $PS4:
set -x
echo "Hello nick"
echo 'This will show $PS4'For a complete reference, see the original article linked at the end of the source.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
