Bookmarks

Bash

Bash is a command shell and scripting language for automating tasks in Linux. In this reference: variables, quotes, conditionals, loops, redirection and shell scripts.

checked 1 Nov · next check 8 Nov · 41 min read

Sections
13
Reading
41 min
Current version
5.3.20 (5.3 + патч bash53-020)
Written from
gnu.org/software/bash/manual

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Bash is and how it works

Bash is the GNU Project’s shell: a program that reads commands from a terminal or a file and executes them. It serves both as the working environment in a Linux terminal and as a scripting language that understands the classic sh syntax and extends it.

Bash is the default shell on Linux. On macOS, /bin/bash is the long-standing Bash 3.2, and many of the features covered in this reference are missing from it: install a recent Bash from Homebrew or MacPorts. On Windows, Bash runs in WSL — the Windows Subsystem for Linux — or in Cygwin.

Bash processes every line according to the same scheme:

  1. Reads the input: a line from the terminal, a script file, or the argument of bash -c.
  2. Splits the input into words and operators according to the quoting rules and expands aliases.
  3. Assembles the words into simple and compound commands.
  4. Performs the expansions — in the order shown in the diagram.
  5. Performs the redirections and removes them from the list of arguments.
  6. Runs the command and, unless it runs in the background, waits for its exit status.

The order of expansions is strict. First comes brace expansion. Then, from left to right, come tilde, parameter and variable expansion, arithmetic and command substitution. Last come word splitting, filename expansion and quote removal. Only brace expansion, word splitting and filename expansion can increase the number of words, and so can "$@" and "${arr[@]}". Only what expands outside double quotes is split into words: $opts yields two arguments, while "$f" yields one.

Example: opts='-l -h', f='my file', with app.log and err.log in the directory. What each stage changed is highlighted.

How Bash differs from sh

Bash understands the grammar, expansions, redirections and quoting of the classic Bourne shell (sh) and adds a great deal of its own. Run a script that uses the constructs from the table with Bash itself: sh does not have them.

Bash featureExample
The [[ ]] conditional with glob patterns and regular expressions[[ $file == *.log ]]
Arrayshosts=(web1 web2)
Brace expansionmkdir -p app/{src,tests}
Arithmetic (( )) and the for (( )) loop(( total = a + b ))
Here-string and process substitutiongrep -c x <<< "$s", diff <(sort a.txt) <(sort b.txt)
Replacement and substring in a variable’s value${version//./_}, ${name:0:3}

Prerequisites

  • Linux basics: files and directories, permissions, processes — the Linux reference.
  • The grep, sed, awk and sort utilities — the Linux reference, the section “Text processing: grep, sed, awk”.

Section sources

the section is written from these pages

Cheat sheet

Typical Bash constructs by task: variables, quotes, conditionals, loops, functions, redirections and scripts. For details and pitfalls, see the reference sections.

Variables and arrays

TaskHow to write it
Set a variablename=web — no spaces around =
Pass a variable to programs you runexport APP_ENV=prod
Default value${port:-8080}
Stop the script if the variable is empty${DB_URL:?not set}
File name without the path${path##*/}
Strip the extension${file%.log}
Replace all occurrences${s//old/new}
Command output into a variabletoday=$(date +%F)
An array and all its elementshosts=(web1 web2), "${hosts[@]}"

Quotes

TaskHow to write it
Text as is, with no expansions'$HOME stays as is'
Insert a variable into text"Hello, $USER"
A single character literally\$, \*
Tab and newline$'a\tb\n'
Pass all arguments unchanged"$@"

Conditionals and tests

TaskHow to write it
File exists and is a regular file[[ -f app.conf ]]
String is empty or not[[ -z $s ]], [[ -n $s ]]
String matches a glob pattern[[ $file == *.log ]]
String matches a regular expression[[ $s =~ ^[0-9]+$ ]]
Compare numbers(( n > 10 ))
Do arithmetic$(( a * 2 + 1 ))
Branch on a patterncase $1 in start) run ;; *) usage ;; esac

Loops

TaskHow to write it
Over filesfor f in *.log; do gzip -- "$f"; done
Over numbersfor i in {1..5}; do echo "$i"; done
C-style counterfor (( i = 0; i < n; i++ )); do …; done
Over the lines of a filewhile IFS= read -r line; do …; done < hosts.txt
Until a condition holdsuntil [[ -f ready.flag ]]; do sleep 1; done
Exit the loop, skip to the next stepbreak, continue

Functions

TaskHow to write it
Declare onegreet() { echo "Hello, $1"; }
Call with an argumentgreet Ali
Local variablelocal tmp
Return an exit statusreturn 1
Get a string resultmsg=$(greet Ali)

Redirections

TaskHow to write it
Output to a file or append to a filemake > build.log, make >> build.log
Errors to a filemake 2> errors.log
Output and errors into one filemake > build.log 2>&1 or make &> build.log
Discard outputmake > /dev/null 2>&1
Text straight into a commandcat <<'EOF' … EOF, grep -c x <<< "$s"
Output to the screen and a filemake 2>&1 | tee build.log
Compare the output of two commandsdiff <(sort a.txt) <(sort b.txt)

Scripts

TaskHow to write it
First line of a script#!/usr/bin/env bash
Stop on errorsset -euo pipefail
Arguments, their count, shifting$1, "$@", $#, shift
Parse flagswhile getopts 'k:v' opt; do …; done
Clean-up on exittrap 'rm -f -- "$tmp"' EXIT
Temporary filetmp=$(mktemp)
Check syntax, trace executionbash -n deploy.sh, bash -x deploy.sh
Include a file of functionssource ./lib.sh

Danger zones

TaskHow to write it
Empty a directory given by a variablerm -rf -- "${dir:?}"/*
Delete a file whose name is in a variablerm -- "$file"
Branching without the a && b || c trapif a; then b; else c; fi
Stop > overwriting filesset -o noclobber
Overwrite a file with noclobber setmake >| build.log

Section sources

the section is written from these pages

Commands, pipelines and exit statuses

A simple command is a name and arguments separated by spaces: ls -l /etc. Every command finishes with an exit status: 0 means success, any other value means failure. &&, ||, if and while are all built on this status.

bashin the terminal
# test returns 0 (true) or 1 (false)test -d /etcecho "$?"test -d /no/such/direcho "$?"
textexample output
01

The $? parameter holds the exit status of the last command. The statuses lie in the range 0–255, and Bash sets some of the values itself:

CodeWhat it means
0success
1–125the command failed
2for builtins — the command is called wrongly: an invalid option or a missing argument
126the command is found but cannot be executed
127the command is not found
128+Nthe command was terminated by signal N

How Bash finds a command

When the name has no slash, Bash searches in order: a function with that name, then a builtin, then an executable file in the directories from PATH. It remembers the paths it found in a hash table so as not to search again. If the search finds nothing, it prints an error and returns 127. A name with a slash, such as ./deploy.sh, runs by that path with no search.

The type builtin shows what will run under a given name:

bashin a script
greet() { echo "Hello"; }type -t greet cd ls
textexample output
functionbuiltinfile

type -a lists all the variants found under the name. command -v prints one word — the path to the file or the name of the builtin — and returns a non-zero status when nothing is found. This is how a script checks whether a program is installed:

bashin a script
if ! command -v rsync > /dev/null; then  echo "rsync is not installed" >&2  exit 1fi

Pipelines

A pipeline joins commands with |: the stdout of each command goes to the stdin of the next. Every command in a pipeline runs in its own process — a subshell — and Bash waits for all of them to finish. |& passes stderr down the pipe as well: it is a shorthand for 2>&1 |.

bashin the terminal
# the five most frequent response codes in the nginx logcut -d' ' -f9 /var/log/nginx/access.log |  sort | uniq -c | sort -rn | head -n 5

The exit status of a pipeline is the status of its last command, so a failure at the start stays invisible by default. With the pipefail option the status of the pipeline is that of the rightmost command that failed, or 0 if there were no failures. ! before a pipeline inverts the status.

The file missing.txt does not exist, so sort fails while uniq and head succeed.
bashin the terminal
sort missing.txt | uniq -c | head -n 3echo "$?"set -o pipefailsort missing.txt | uniq -c | head -n 3echo "$?"
textexample output
...0...2

The word time before a pipeline prints how long it ran: time make.

Lists: ;, &, && and ||

A list is pipelines separated by the operators ;, &, && or ||. A newline works like ;. && and || bind more tightly than ; and &, and the list runs from left to right.

NotationWhat it does
a; brun a, wait, then b; the status is that of the last command
a &run a in the background and do not wait; the status is 0 straight away, the PID of the background command is in $!
a && brun b only if a returned 0
a || brun b only if a returned a non-zero status
a | ba pipeline: the output of a goes to the input of b
a |& bthe same, with the errors of a as well
! ainvert the exit status of a
bashin a script
# deployment — only after a successful buildmake && ./deploy.sh# the directory is missing — exit with an errorcd /srv/app || exit 1# the long export in the background./export.sh > export.log 2>&1 &echo "PID: $!"

An assignment before a command name, as in LC_ALL=C sort names.txt, applies only to that command — for details, see the section “Variables and parameter expansion”.

Section sources

the section is written from these pages

Variables and parameter expansion

A Bash variable is a named parameter with a value: name=value, with no spaces around the =. The value is substituted by parameter expansion: $name or ${name}. Forms such as ${name:-default} also set a default value, trim and replace text without external programs.

bashin the terminal
name=webport=8080echo "$name listens on port $port"# braces separate the name from the text that followsecho "${name}_backup"unset portecho "port: ${port:-80}"
textexample output
web listens on port 8080web_backupport: 80

An empty string is also a value: name= sets a variable with an empty value, and unset name removes the variable. To the right of the = Bash performs expansions but does not split the result into words and does not expand glob patterns, so copy=$src is safe even without quotes. The += operator appends to a value: PATH+=":$HOME/bin".

The environment and export

Shell variables are visible only to the shell itself. The programs it runs receive an environment — a list of name=value pairs. export marks a variable for passing into the environment; variables that Bash received from the environment at startup are marked already. An assignment before a command name goes only into that command’s environment: LC_ALL=C sort names.txt.

bashin the terminal
mode=debugbash -c 'echo "mode=$mode"'export modebash -c 'echo "mode=$mode"'
textexample output
mode=mode=debug

Special and positional parameters

Special parameters are set by Bash itself; positional parameters are the arguments of a script or function. You cannot assign to them with =; the positional ones are changed by set -- and shift.

ParameterWhat it holds
$?the exit status of the last command
$1…$9, ${10}positional parameters — the arguments of a script or function; beyond 9, in braces
$#the number of positional parameters
"$@"all positional parameters, each as a separate word
"$*"all positional parameters as one word, joined by the first character of IFS
$0the name of the shell or script
$$the PID of the shell; in a subshell, the PID of the shell that started it
$!the PID of the last background command

Parameter expansion forms

The forms with a colon apply when the variable is unset or empty; without the colon, only when it is unset. In the examples file=/var/backups/db.tar.gz.

FormWhat it doesExample → result
${var:-word}word if var is unset or empty${PORT:-8080}
${var:=word}the same, and also assign word to the variable${LOG_DIR:=/var/log/app}
${var:?text}an error with the message text; the script exits${DB_URL:?not set}
${var:+word}word if var is set and not empty${DEBUG:+--verbose}
${#var}the length of the value in characters${#file} → 22
${var:offset:length}a substring; counting starts at 0${file:5:7} → backups
${var#pattern}, ${var##pattern}remove the shortest or longest match at the beginning${file##*/} → db.tar.gz
${var%pattern}, ${var%%pattern}remove a match at the end${file%.gz} → /var/backups/db.tar
${var/pattern/string}replace the first match; // — all of them${file/backups/archive} → /var/archive/db.tar.gz
${var^^}, ${var,,}convert to upper or lower case${name^^} → WEB
${var@Q}the value quoted in a form that can be reused as input${name@Q} → 'web'
bashin the terminal
file=/var/backups/db.tar.gzecho "${file##*/}"echo "${file%/*}"echo "${file#*.}"
textexample output
db.tar.gz/var/backupstar.gz

Command substitution

Command substitution $(command) runs the command in a subshell and substitutes its output without the trailing newlines. The backtick form is obsolete. The contents of a file are substituted faster as $(< file) than as $(cat file). Inside double quotes the result is not split into words.

bashin the terminal
today=$(date +%F)archive="db-$today.sql.gz"host=$(< /etc/hostname)echo "$host: $archive"
textexample output
web1: db-2026-10-31.sql.gz

Since Bash 5.3 there is the form ${ command; }: it runs the command in the current shell, with no subshell, so assignments inside it persist. A space is required after the {, and ; or a newline before the }. ${| command; } substitutes not the output but the value of the REPLY variable.

bashBash 5.3
count=0out=${ count=5; echo "done"; }echo "$out, count=$count"
textexample output
done, count=5

Integer arithmetic $(( a + b )) is covered in the section “Conditionals: if, [[ ]], (( )) and case”.

Section sources

the section is written from these pages

Quoting and escaping

Quoting removes the special meaning of characters. Inside single quotes everything is taken literally; inside double quotes $, the backquote and \ are still expanded. Outside quotes Bash also splits the expansion into words and expands it as a glob pattern, so variables are written in double quotes: "$file".

SyntaxWhat is expandedExample → result
'…'nothing; a single quote cannot be put inside, not even with \echo '$HOME' → $HOME
"…"$, the backquote and \ before $, ", \ or a backquoteecho "$HOME" → /home/ali
\xnothing: the character x is taken literallyecho \$HOME → $HOME
$'…'C-style escape sequences: \n, \t, \\, \'printf '%s' $'a\tb' → a, a tab, b

In an interactive shell ! also keeps a special meaning inside double quotes — history expansion starts with it. Inside "…", a double quote is escaped with a backslash: "he said \"yes\"".

Why variables are quoted

After parameter expansion, command substitution and arithmetic outside double quotes, Bash splits the result into words. The separators are the characters of IFS — a space, a tab and a newline by default. Each word containing *, ? or [ is then, unquoted, treated as a glob pattern and replaced with the names of matching files.

bashdon’t do this
file='my report.txt'rm $file

Here rm receives two arguments, my and report.txt, and deletes the wrong file if one exists. With quotes there is a single argument. The -- tells rm that only file names follow, even if a name begins with a dash:

bashthe right way
file='my report.txt'rm -- "$file"

A variable is left unquoted only when the splitting is intended. A list of names is safer stored in an array — see the “Arrays” section.

All the arguments: "$@" and "$*"

"$@" expands to one separate word per positional parameter, so arguments with spaces are passed on unchanged. "$*" joins all parameters into a single word with the first character of IFS. Unquoted, both forms are split into words again.

bashin the terminal
set -- 'a b' cprintf '[%s]\n' "$@"printf '[%s]\n' "$*"printf '[%s]\n' $@
textexample output
[a b][c][a b c][a][b][c]

IFS and empty values

The separators are set by the IFS variable. An empty value, IFS=, disables splitting, and read with it does not strip leading and trailing whitespace: IFS= read -r line. An explicit empty string "" stays an argument, while an empty unquoted variable disappears: cmd $empty calls cmd with no arguments, cmd "$empty" — with a single empty one.

Section sources

the section is written from these pages

Arrays

An array is a variable holding a list of values. An indexed array is numbered from 0, an associative one (declare -A) stores key–value pairs. An array is a good fit for a list of files or arguments: in "${arr[@]}" each element stays a separate word, even one with spaces.

bashin the terminal
hosts=(web1 web2 'db main')echo "${hosts[0]}"echo "${#hosts[@]}"for h in "${hosts[@]}"; do  echo "→ $h"done
textexample output
web13→ web1→ web2→ db main
SyntaxWhat it does
arr=(a b c)create an indexed array
arr[5]=xset an element; indices need not be consecutive
arr+=(d e)append elements to the end
"${arr[@]}"all elements, each a separate word
"${arr[*]}"all elements as one word, joined by the first character of IFS
${#arr[@]}the number of elements
${arr[-1]}the last element
${!arr[@]}indices or keys
unset 'arr[1]'delete an element; the quotes are needed, otherwise Bash mistakes arr[1] for a glob pattern
unset arrdelete the whole array

Without braces, $arr is the first element, ${arr[0]}. The braces around an element are required: Bash reads $arr[1] as ${arr} followed by the text [1].

A list of files for a command

When an array is created, its elements go through all the expansions, so a glob pattern immediately turns into a list of names. Such a list can be counted and passed to a command whole, without fear of spaces in the names. declare -p prints the array in a form suitable for reuse as input.

bashin the terminal
logs=(logs/*.log)echo "files: ${#logs[@]}"tar -czf logs.tar.gz -- "${logs[@]}"declare -p logs
textexample output
files: 2declare -a logs=([0]="logs/access.log" [1]="logs/error.log")

If there are no files, the array ends up holding the glob pattern logs/*.log itself, and the count will be 1. Enable shopt -s nullglob before the assignment: the array will then be empty.

Associative arrays

An associative array is declared explicitly, with declare -A. A key is any non-empty string. ${!port[@]} lists the keys, ${port[$name]} the value for a key.

bashin a script
declare -A port=([web]=80 [db]=5432)port[cache]=6379for name in "${!port[@]}"; do  echo "$name: ${port[$name]}"done

Read lines into an array

mapfile (readarray is a synonym) reads input lines into an indexed array; -t removes the trailing newline from each line. read -a splits one line into words and puts them into an array.

bashin the terminal
mapfile -t lines < /etc/hostsecho "lines: ${#lines[@]}, first: ${lines[0]}"line='alpha beta gamma'read -ra words <<< "$line"echo "${words[1]}"

Section sources

the section is written from these pages

Conditionals: if, [[ ]], (( )) and case

if in Bash tests not an expression but the exit status of a command: 0 — true, anything else — false. Any command can therefore serve as the condition: grep -q, [[ ]] for strings and files or (( )) for numbers.

bashin a script
if grep -q '^ali:' /etc/passwd; then  echo "user exists"elif [[ -f /etc/ali.disabled ]]; then  echo "user is disabled"else  echo "no such user"fi

elif and else are optional. The exit status of the whole construct is that of the last command it ran, or 0 if no condition turned out to be true.

[[ ]] or [ ]

[ is the test builtin, while [[ ]] is part of the Bash syntax. Inside [[ ]] there is no word splitting or glob expansion, so [[ -n $name ]] works even with an empty variable. To the right of == in [[ ]] stands a pattern, =~ matches against a regular expression, and && and || are written right inside the brackets. [ ] is only needed when the script has to run in sh.

bashdon’t do this
name=''[ $name = admin ] && echo "admin"

With an empty name the test command receives two arguments instead of three and the check breaks. In [[ ]] quotes are not needed, in [ ] they are mandatory:

bashthe right way
[[ $name == admin ]] && echo "admin"[ "$name" = admin ] && echo "admin"

Do not combine checks in [ ] with -a and -o: POSIX has deprecated them. Write [ -f a ] && [ -f b ] or a single expression [[ -f a && -f b ]].

File, string and number tests

ExpressionTrue if
-e filethe file exists
-f fileit is a regular file
-d fileit is a directory
-L fileit is a symbolic link
-s filethe file is larger than zero
-r file, -w file, -x filethe file can be read, written, executed
a -nt bfile a is newer than b, or a exists while b does not
-z str, -n strthe string is empty; the string is not empty
a == b, a != bthe strings are equal or not; in [[ ]] the right side is a pattern
a =~ regexthe string matches a regular expression; only in [[ ]]
-v namethe variable name is set
a -eq b, -ne, -lt, -le, -gt, -gecomparison of integers

A quoted part of a pattern is matched literally: [[ $file == "$pattern" ]] is an exact match, [[ $file == *.log ]] is a pattern match. After =~ comes a POSIX extended regular expression; Bash stores the match and the parenthesised groups in the BASH_REMATCH array.

bashin the terminal
version='v5.3.20're='^v([0-9]+)\.([0-9]+)'if [[ $version =~ $re ]]; then  echo "major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]}"fi
textexample output
major=5 minor=3

Arithmetic: (( )) and $(( ))

Bash calculates only in integers. $(( expression )) expands to the result, while (( expression )) is a command: its exit status is 0 when the result is non-zero and 1 when it is zero. Inside, variable names are written without $, and the operators and their precedence are those of C.

bashin the terminal
files=12pages=$(( (files + 4) / 5 ))echo "$pages"(( files > 10 )) && echo "more than ten"(( ++files ))echo "$files"
textexample output
3more than ten13

case: choosing by pattern

case compares the word against the patterns in order and runs the branch of the first match. The patterns are the same as glob patterns, | separates alternatives, *) catches everything else. A branch ends with ;;, and ;& continues execution with the next branch without a check.

bashin a script
case $1 in  start | up)    echo "starting" ;;  stop)    echo "stopping" ;;  *)    echo "usage: $0 start|stop" >&2    exit 2 ;;esac

Section sources

the section is written from these pages

Loops: for, while, until

for runs the loop body once for each word of the list: file names, arguments, numbers. while repeats the body as long as the condition returns 0, until — until the condition returns 0. Lines of a file are read not with for, but with while read.

bashin a script
for f in *.log; do  echo "compressing $f"  gzip -- "$f"done

The list after in undergoes all expansions. Without in, the loop iterates over the positional parameters, as with in "$@". A glob pattern expands to a sorted list of names; since Bash 5.3 the sort order is set by the GLOBSORT variable.

Numbers and the arithmetic for

A sequence of numbers comes from brace expansion: {1..5}, with a step — {0..20..5}, with leading zeros — {01..10}. Braces expand before variables, so {1..$n} does not work. If a bound is stored in a variable, use the arithmetic for:

bashin the terminal
for i in {1..3}; do echo "step $i"; donen=3for (( i = 1; i <= n; i++ )); do  echo "attempt $i of $n"done
textexample output
step 1step 2step 3attempt 1 of 3attempt 2 of 3attempt 3 of 3

Lines of a file: while read

read reads one line and returns non-zero at the end of the input — that exit status is what stops while. The -r flag leaves backslashes as they are, and an empty IFS= keeps read from stripping leading and trailing whitespace.

bashin a script
while IFS= read -r host; do  echo "checking $host"done < hosts.txt

for line in $(cat hosts.txt) is the wrong tool: for iterates over words, not over lines. A line with a space splits into two iterations, and a word containing * expands into file names.

bashin the terminal
count=0printf 'a\nb\n' | while read -r line; do  (( ++count ))doneecho "$count"count=0while read -r line; do  (( ++count ))done < <(printf 'a\nb\n')echo "$count"
textexample output
02

A glob pattern with no matches

If a glob pattern matches no files, Bash leaves it as it is: the loop runs once with the word *.tmp. After shopt -s nullglob such a pattern disappears, and the loop does not run at all.

bashin a script
shopt -s nullglobfor f in *.tmp; do  rm -- "$f"done

break and continue

break exits the loop, continue jumps to the next iteration:

bashin a script
for f in /etc/nginx/sites-enabled/*; do  [[ -s $f ]] || continue  if grep -q 'listen 80;' -- "$f"; then    echo "found: $f"    break  fidone

Section sources

the section is written from these pages

Functions

A function is a named group of commands that you call like an ordinary command: log INFO done. It runs in the current shell, with no new process, receives arguments as $1, $2 and "$@", and returns an exit status, not a value.

bashin a script
log() {  local level=$1  shift  printf '%s [%s] %s\n' "$(date +%T)" "$level" "$*"}log INFO "backup finished"log ERROR "disk is full"
textexample output
14:02:11 [INFO] backup finished14:02:11 [ERROR] disk is full

A function is declared as name() { …; } or function name { …; }. Separate the curly braces from the commands with a space or a newline, and put ; or a newline before the closing }. A completed function returns the exit status of its last command.

Function arguments

For the duration of the call, the function’s arguments become the positional parameters $1, $2…, and $# is their count; $0 does not change. When the function finishes, the previous values are restored. A parameter with a number above 9 is written in braces: ${10}.

Local variables

By default, variables are shared between a function and the code that calls it. local creates a variable visible only inside the function and in the functions it calls. Without local, the function changes the script’s variable of the same name.

bashin the terminal
name=globalchange() {  local name=local  echo "inside: $name"}changeecho "after: $name"
textexample output
inside: localafter: global

Exit status and result

return n finishes the function with exit status n; without a number — with the exit status of the last command. A function returns a string or a number through its output, and the calling code picks it up through command substitution.

bashin a script
is_running() {  pgrep -x "$1" > /dev/null}dir_size() {  du -sh -- "$1" | cut -f1}if is_running nginx; then  echo "nginx is up, logs: $(dir_size /var/log/nginx)"fi

Listing, exporting and recursion

declare -F prints the names of functions, and declare -f with a name prints the function’s body. export -f passes a function to Bash child processes, unset -f removes it. A function may call itself; the FUNCNEST variable limits the nesting depth — by default there is no limit.

Functions for working in the terminal go into ~/.bashrc — that file is covered in the section “Scripts: shebang, arguments, set -euo pipefail”.

Section sources

the section is written from these pages

Redirections and here documents

Redirection changes where a command reads from and where it writes. The standard file descriptors: 0 — input (stdin), 1 — output (stdout), 2 — errors (stderr). > sends output to a file, 2> — errors, < takes input from a file.

bashin the terminal
# output to a file: the file is created or truncatedmake > build.log# append to the enddate >> build.log# errors — to a separate filemake 2> errors.log# output and errors — to a single filemake > build.log 2>&1# discard everythingmake > /dev/null 2>&1
NotationWhat it does
< fileinput from a file
> fileoutput to a file; the file is created or truncated
>> fileoutput to the end of the file
2> fileerrors to a file
2>&1errors to wherever output is going at the moment
&> fileoutput and errors to a file, like > file 2>&1
&>> filethe same, appending to the end
>&2output — to the error stream; this is how a script prints its own error messages

Order of redirections

Bash performs redirections from left to right, and 2>&1 copies where output points at that moment. In make > build.log 2>&1 both streams end up in the file. In make 2>&1 > build.log errors go where output pointed before > — the terminal — and only output ends up in the file.

Redirections are performed from left to right.

Here documents and here strings

A here document feeds a command lines written directly in the script, up to the delimiter line. If the delimiter is unquoted, variables, $( ) and $(( )) are expanded in the text; if it is quoted, as in <<'EOF', the text is passed as is. <<- strips leading tabs so that the text can be indented together with the code.

bashin the terminal
name=webcat > site.conf <<EOFserver_name $name.example.com;root /srv/$name;EOFcat <<'EOF'$HOME is not expanded hereEOF

A here string <<< passes a single line to the command and adds a newline at the end: grep -c error <<< "$log".

Process substitution

Process substitution <(list) substitutes the name of a file from which the output of the commands list is read. >(list) substitutes the name of a file, and what is written to it goes to the commands as input. This is how the output of other commands is passed to a program that expects files. There is no space between < and (.

bashin the terminal
diff <(sort old.txt) <(sort new.txt)

Output to a file and the screen: tee

The external program tee copies its input both to the output and to files; -a appends to the end. With sudo, a file is written through tee: the > redirection is performed by your shell with your permissions, not by sudo.

bashin the terminal
make 2>&1 | tee build.logecho '192.0.2.10 web1' | sudo tee -a /etc/hosts > /dev/null

Output of a group of commands

To direct the output of several commands into a single file, group them. { …; } runs the commands in the current shell, ( … ) — in a subshell, from which variable changes and cd do not escape. In { } spaces are needed after { and ;, or a newline before }.

bashin the terminal
{  echo "report for $(date +%F)"  df -h /  free -m} > report.txt

With the exec command, the redirection applies to the entire rest of the script: exec >> /var/log/backup.log 2>&1.

Protection against overwriting

set -o noclobber stops > from overwriting an existing regular file. Overwriting is still possible if done explicitly, with >|.

Section sources

the section is written from these pages

Scripts: shebang, arguments, set -euo pipefail

A script is a text file with Bash commands. The first line, #!/usr/bin/env bash, chooses the interpreter, and chmod +x makes the file executable. set -euo pipefail at the top of a script stops it on an error instead of carrying on.

The reference example is a directory backup script with a retention flag:

bashbackup.sh
#!/usr/bin/env bashset -euo pipefail usage() {  echo "usage: $0 [-k days] dir" >&2  exit 2} keep=7while getopts 'k:' opt; do  case $opt in    k) keep=$OPTARG ;;    *) usage ;;  esacdoneshift $(( OPTIND - 1 ))(( $# == 1 )) || usage src=$1dest=/srv/backup[[ -d $src ]] || { echo "no such dir: $src" >&2; exit 1; }mkdir -p -- "$dest" base=$(basename -- "$src")tmp=$(mktemp)trap 'rm -f -- "$tmp"' EXIT tar -czf "$tmp" -C "$src" .mv -- "$tmp" "$dest/$base-$(date +%F).tar.gz"find "$dest" -name "$base-*.tar.gz" -mtime +"$keep" -deleteecho "done: $dest"
bashin a terminal
chmod +x backup.shsudo ./backup.sh -k 14 /etc

Shebang and running a script

The #! line at the top of the file names the program that will run it. #!/usr/bin/env bash finds the first bash in PATH, while #!/bin/bash uses Bash at that specific path. An executable file is run by path, ./backup.sh; without the execute permission — explicitly, as bash backup.sh. A script runs in a new Bash process, so its cd commands and variables do not affect your shell.

When invoked as sh, Bash switches to POSIX mode after reading the startup files and behaves differently. Run a Bash script as bash backup.sh or via a shebang pointing to bash, but not as sh backup.sh.

set -euo pipefail

OptionWhat it does
-e (errexit)exit the script if a command returns a non-zero status
-u (nounset)treat a reference to an unset variable as an error
-o pipefailthe pipeline’s status is that of the last command to fail
-x (xtrace)print every command before running it

With set -u, read an optional variable with a fallback, ${VAR:-}: an unset variable will then not stop the script.

Arguments: shift and getopts

A script’s arguments are the positional parameters $1, $2…; their number is $#, and all of them together are "$@". shift moves them left: $2 becomes $1. Flags are parsed by the getopts builtin: a letter followed by a colon in the option string expects a value, which lands in OPTARG, while OPTIND holds the number of the next argument. That is why shift $(( OPTIND - 1 )) is written after the loop, leaving the first argument after the flags in $1.

Clean-up: trap and mktemp

trap '…' EXIT runs commands when the shell exits — at the end of the script, on exit, or when set -e aborts it. Signals are caught the same way, by name: INT, TERM.

mktemp creates a temporary file with an unpredictable name and owner-only permissions and prints its name; mktemp -d creates a directory. A name like /tmp/app.$$ is predictable, and another user could swap such a file.

bashin a script
tmpdir=$(mktemp -d)trap 'rm -rf -- "$tmpdir"' EXITtrap 'echo "interrupted" >&2; exit 1' INT TERMtar -xzf release.tar.gz -C "$tmpdir"

source and startup files

source file (or . file) runs the file in the current shell: the variables and functions it sets remain in place. This is how shared functions and settings are loaded. To also put the variables from the file into the environment, turn set -a on for a while:

bashin a script
set -asource ./.envset +a

An interactive non-login shell reads ~/.bashrc. A login shell reads /etc/profile and then the first of ~/.bash_profile, ~/.bash_login, ~/.profile. A script reads none of these files; a non-interactive shell runs only the file named in BASH_ENV, if that variable is set.

Running on a schedule — in the Linux reference, the section “Cron scheduler”, and in the systemd reference, the section “Timers and how they compare with cron”.

Section sources

the section is written from these pages

Common errors and troubleshooting

Start diagnosing with three commands. bash -n script.sh checks the syntax without running any commands, bash -x script.sh prints every command after the expansions, and echo "$?" shows the exit status of the last command.

Checking order

  1. Syntax: bash -n script.sh stays silent when there are no errors.
  2. Tracing: bash -x script.sh, or set -x before the suspicious spot and set +x after it.
  3. Line numbers in the trace: PS4='+ ${LINENO}: ' before set -x.
  4. Exit statuses: echo "$?" after a command, echo "${PIPESTATUS[@]}" after a pipeline.
bashin a script
# temporarily, while debuggingPS4='+ ${LINENO}: 'set -xcp -- "$src" "$dest"set +x
textexample output
+ 12: cp -- /etc/app.conf /srv/backup+ 13: set +x

Command not found: exit status 127

The cause: the name is neither among the functions and builtins nor in the PATH directories. Usually it is a typo, a program that is not installed, or a script from the current directory run without ./.

bashcheck
type -a deploy.shecho "$PATH"
  • Run a script from the current directory by path: ./deploy.sh.
  • Install the program or add its directory to PATH: PATH="$PATH:/opt/tool/bin".

File found but not runnable: exit status 126

The cause: the file has no execute permission, or the path points at a directory.

bashcheck
ls -l deploy.sh
bashfix
chmod +x deploy.sh# or run it through bash, without the x permissionbash deploy.sh

The script stops on an unset variable

The cause: with set -u, referring to an unset variable is an error. Bash writes a message to the error stream and the script exits. Most often it is an optional argument $1 or an environment variable someone forgot to set.

bashcheck
if [[ -v DB_URL ]]; then  echo "set"else  echo "not set"fi
bashfix
# a fallback value for an optional argumenttarget=${1:-prod}# a clear error instead of the script stopping: "${DB_URL:?set DB_URL first}"

Syntax error at the end of the file

The cause: a quote or a construct left open — if without fi, do without done, { without }. Bash only notices this when it reaches the end of the file; since version 5.3 it names the line where the unterminated construct started.

bashcheck
bash -n deploy.sh

The fix: open the line named in the message and close the construct that starts on it.

A variable is empty after a loop with |

The cause: the commands of a pipeline run in subshells, and assignments inside … | while read never reach the script. BASHPID shows the number of the process a command runs in.

bashcheck
echo "$BASHPID"echo x | while read -r _; do echo "$BASHPID"; done
  • Feed the loop its input with a redirection: while …; done < file or done < <(command).
  • Or enable shopt -s lastpipe in the script: the last command of the pipeline then runs in the current shell.

set -e did not stop the script

The cause: -e does not act in the conditions of if and while, on the left of && and ||, after ! — and, without pipefail, on pipeline failures other than the last command. The full list is in the section “Scripts: shebang, arguments, set -euo pipefail”. In command substitution $( ), Bash also drops -e outside POSIX mode.

bashcheck
bash -x deploy.sh
  • Check important commands explicitly: cp -- "$src" "$dest" || exit 1.
  • For -e to act inside $( ) as well, enable shopt -s inherit_errexit.

Minor problems

SymptomCauseWhat to do
A file name with a space turns into two argumentsunquoted expansion is subject to word splittingwrite "$file", "$@", "${files[@]}"
[ $a = b ] fails when a is emptytest receives the wrong number of arguments[[ $a == b ]] or [ "$a" = b ]
The loop over *.log ran once with the word *.loga pattern with no matches stays as it isshopt -s nullglob
A script with set -e exited silently at (( count++ ))(( )) returns 1 when the value of the expression is 0(( ++count )) or count=$(( count + 1 ))
$(( 08 + 1 )) — an errora number with a leading zero — octal$(( 10#08 + 1 ))
cd in a script does not change the terminal’s directorythe script runs in a separate processsource script.sh or a function in ~/.bashrc
A program does not see a script’s variablethe variable is not in the environmentexport NAME or NAME=value command

Section sources

the section is written from these pages

Versions and what’s new

This reference covers GNU Bash 5.3. The latest release is 5.3.20 of 14 September 2026: version 5.3 with the official patches up to bash53-020. Fixes are released as patches for the current version, and the patch number is the third number in the version number.

BranchStatusFirst releaseLatest release
5.3current, receives patches30 July 20255.3.20 — 14 September 2026
5.2previous, no new patches26 September 20225.2.37 — 23 September 2024
5.1old, still ships in some Linux distributions6 December 20205.1.16 — 4 January 2022
3.2old, /bin/bash on macOS11 October 20063.2.57 — 5 October 2014

The project does not publish support timelines: the Bash page names a single current version, and patches are released for it. Most Linux distributions, according to this page, ship 5.1 or 5.2.

How to check your version

bashin the terminal
echo "$BASH_VERSION"echo "${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}"
textexample output
5.3.20(1)-release5.3

A script that needs the new syntax checks the version at the start:

bashin a script
if (( BASH_VERSINFO[0] < 5 )); then  echo "Bash 5 or newer is required" >&2  exit 1fi

What changed in 5.3

  • Variables and parameter expansion: command substitution ${ command; } runs in the current shell, without a subshell, and ${| command; } substitutes the value of REPLY.
  • Loops: the GLOBSORT variable sets the order of names when expanding glob patterns — by name, size, modification time and other attributes, ascending or descending.
  • Conditionals: Bash reports an error if the regular expression in [[ =~ ]] fails to compile.
  • Scripts: trap -P shows the action for the given signal, and BASH_TRAPSIG holds the signal number while the trap runs. source -p path looks for the file in the directories from path instead of PATH.
  • Commands, pipelines and exit statuses: type -a -P shows both the remembered path and the result of the search along PATH.
  • Common mistakes and diagnostics: the message about an unterminated compound command, such as if without fi, names the line where it started.

Deprecated and removed

  • The assoc_expand_once option of shopt is deprecated as of 5.3: it has become a synonym of the new array_expand_once.
  • Command substitution with backquotes is marked as deprecated in the manual: write $( ).
  • In test and [, POSIX has deprecated -a, -o and the parentheses for grouping. Write [ … ] && [ … ] or [[ ]].

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

9 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Bash” topic
13 sections
Another reference · DevOps & cloud

Docker

Verified 31 Oct
All references · 61