Bash Reference

Shell syntax, commands, expansion, and scripting.

Bash Reference

A practical reference for Bash scripts, parameters, expansions, conditions, arrays, redirections, and builtins.

Updated 2026-07-22

Overview

Bash is both an interactive command interpreter and a programming language. It implements shell features defined by POSIX and adds arrays, extended tests, brace expansion, process substitution, job control, and other extensions.

Bash is not the same language as every shell. A script that uses [[ ]], arrays, brace expansion, or process substitution should explicitly run with Bash instead of assuming /bin/sh provides those features.

CSS #!/usr/bin/env bash name=${1:-World} printf 'Hello, %s\n' "$name"

Invocation and Scripts

CommandMeaning
bashStart an interactive Bash shell
bash script.shRead and execute commands from a file
bash -c 'commands'Execute commands supplied as an argument
bash -n script.shRead commands and check syntax without executing them
bash -x script.shPrint expanded commands while executing
bash --versionDisplay Bash version information
source fileExecute a file in the current shell environment
exec commandReplace the current shell process with command

Quoting

FormBehavior
\characterPreserve the literal value of the next character
'text'Preserve every character literally; a single quote cannot occur inside
"text"Allow parameter, command, and arithmetic expansion while suppressing word splitting and pathname expansion
$'text'Interpret backslash escapes such as \n and \t
$"text"Mark a string for locale translation

Variables and Parameters

SyntaxMeaning
name=valueAssign a shell variable
export nameInclude a variable in environments of subsequently executed commands
readonly namePrevent reassignment or removal
local name=valueCreate a variable local to the current function
declare -i count=0Declare a variable with the integer attribute
unset nameRemove a variable or function
${name}Expand a parameter
${name:-word}Use word when name is unset or empty
${name:=word}Assign and use word when name is unset or empty
${name:?message}Write an error when name is unset or empty
${name:+word}Use word when name is set and nonempty
${#name}String length
${name:offset:length}Substring expansion
${name#pattern}Remove shortest matching prefix
${name##pattern}Remove longest matching prefix
${name%pattern}Remove shortest matching suffix
${name%%pattern}Remove longest matching suffix
${name/pattern/replacement}Replace the first matching pattern
Special parameterMeaning
$0Shell or script name
$1 … $9Positional parameters
${10}Positional parameters above 9 require braces
$#Number of positional parameters
"$@"Each positional parameter as a separate word
"$*"All positional parameters joined into one word
$?Status of the most recent foreground pipeline
$$Process ID of the shell
$!Process ID of the most recent asynchronous command
$-Current shell option flags

Shell Expansions

Bash performs expansions in a defined sequence. Brace expansion occurs first, followed by tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, and process substitution. Word splitting and pathname expansion follow, and quote removal occurs last.

SyntaxExpansion
{one,two}Brace expansion
{1..5}Sequence expression
~ or ~userHome-directory expansion
$name or ${name}Parameter expansion
$(( expression ))Arithmetic expansion
$(command)Command substitution
<(command)Process substitution supplying a readable filename
>(command)Process substitution supplying a writable filename
*.txtPathname expansion using a glob pattern

Conditions and Tests

ExpressionTrue when
[[ -e $path ]]Path exists
[[ -f $path ]]Path is a regular file
[[ -d $path ]]Path is a directory
[[ -r $path ]]Path is readable
[[ -w $path ]]Path is writable
[[ -x $path ]]Path is executable
[[ -n $value ]]String has nonzero length
[[ -z $value ]]String has zero length
[[ $left == $right ]]Strings are equal
[[ $value == pattern ]]Value matches a shell pattern when pattern is unquoted
[[ $value =~ regex ]]Value matches an extended regular expression
(( left < right ))Arithmetic comparison is true
commandCommand exits with status 0
CSS if [[ -f $path && -r $path ]]; then printf 'Readable file: %s\n' "$path" elif [[ -e $path ]]; then printf 'The path exists but is not a readable file\n' else printf 'The path does not exist\n' >&2 fi

Control Flow and Functions

CSS for file in "$@"; do printf '%s\n' "$file" done while read -r line; do printf 'Line: %s\n' "$line" done < input.txt case $answer in [Yy]|[Yy][Ee][Ss]) printf 'yes\n' ;; [Nn]|[Nn][Oo]) printf 'no\n' ;; *) printf 'unknown\n' ;; esac
CSS greet() { local name=${1:?name is required} printf 'Hello, %s\n' "$name" } greet Ada

Arrays

CSS items=("first value" second third) printf 'First: %s\n' "${items[0]}" printf 'Count: %d\n' "${#items[@]}" for item in "${items[@]}"; do printf 'Item: %s\n' "$item" done declare -A colors=([error]=red [success]=green) printf '%s\n' "${colors[success]}"
SyntaxMeaning
${array[index]}One indexed element
"${array[@]}"Every element as a separate word
${#array[@]}Number of elements
${!array[@]}All assigned indexes or keys
array+=(value)Append an indexed element
unset 'array[index]'Remove an element
declare -a arrayDeclare an indexed array
declare -A mapDeclare an associative array

Redirections and Pipelines

SyntaxMeaning
command > fileRedirect standard output and truncate file
command >> fileAppend standard output
command < fileRead standard input from file
command 2> fileRedirect standard error
command > file 2>&1Redirect output, then duplicate standard error to it
command &> fileBash shorthand for redirecting output and error
left | rightConnect left standard output to right standard input
left |& rightPipe both output and error from left
command <<< "$text"Supply a here string as standard input
command <<EOFSupply a here document
command <<'EOF'Supply a here document without expanding its body
exec 3> fileOpen file descriptor 3 for writing
exec 3>&-Close file descriptor 3

Common Builtins

BuiltinPurpose
alias / unaliasDefine or remove interactive command aliases
builtinRun a shell builtin explicitly
cd / pwdChange or display the working directory
commandRun a command while bypassing shell functions with the same name
declare / typesetSet variables and their attributes
echoWrite arguments; printf is preferable when formatting matters
enableEnable or disable shell builtins
helpDisplay help for Bash builtins
mapfile / readarrayRead lines into an indexed array
printfWrite formatted output
readRead a line and split it into variables
shiftRemove leading positional parameters
source / .Execute commands in the current shell
typeDescribe how a command name would be interpreted
waitWait for processes or jobs and return their statuses
CSS help printf type -a printf command -V sed

Options, Traps, and Debugging

SyntaxEffect
set -uReport an error when expanding an unset parameter
set -o pipefailUse the rightmost nonzero status from a failed pipeline
set -x / set +xEnable or disable execution tracing
set -eExit in some contexts when a command fails; behavior has important exceptions
shopt -s nullglobRemove unmatched pathname patterns instead of leaving them literal
shopt -s globstarLet ** match recursively in pathname expansion
trap handler EXITRun a handler when the shell exits
trap handler INT TERMRun a handler for selected signals
trap - SIGNALRestore the original disposition of a signal
CSS temporary_directory=$(mktemp -d) cleanup() { rm -rf -- "$temporary_directory" } trap cleanup EXIT

Interactive Use and Job Control

Command or keyEffect
command &Run a pipeline asynchronously
jobsList jobs known to the current shell
fg %1 / bg %1Resume job 1 in the foreground or background
disown %1Remove job 1 from the shell’s job table
Ctrl-CInterrupt the foreground job
Ctrl-ZSuspend the foreground job
Ctrl-RSearch history backward
Ctrl-A / Ctrl-EMove to the beginning or end of the line
Meta-B / Meta-FMove backward or forward one word

Description

Shell syntax, commands, expansion, and scripting.

References

Similar or alternative tools

Don't forget to set a bookmark for tool.io!
Privacy | Imprint | Cookies