Bash (Unix shell)

Original author(s)Brian Fox
Developer(s)Chet Ramey
Initial release8 June 1989; 36 years ago (8 June 1989)
Stable release
5.3[1] Edit this on Wikidata / 3 July 2025
Repository
Written inC
Operating system
PlatformGNU
Available inMultilingual (gettext)
TypeShell (computing), Unix shell, command language
License
Websitewww.gnu.org/software/bash/

In computing, Bash is an interactive command interpreter and programming language developed for Unix-like operating systems.[6][7] It is designed as a 100% free alternative for the Bourne shell, `sh`, and other proprietary Unix shells.[8] Bash has gained widespread adoption and is commonly used as the default login shell for numerous Linux distributions.[9]

Created in 1989 by Brian Fox for the GNU Project, it is supported by the Free Software Foundation.[10] Bash (short for "Bourne Again SHell") can operate within a terminal emulator, or text window, where users input commands to execute various tasks.[11][12] It also supports the execution of commands from files, known as shell scripts, facilitating automation.

The Bash command syntax is a superset of the Bourne shell, `sh`, command syntax, from which all basic features of the (Bash) syntax were copied. As a result, Bash can execute the vast majority of Bourne shell scripts without modification. Some other ideas were borrowed from the C shell, `csh`, and its successor `tcsh`, and the Korn Shell, `ksh`. It is available on nearly all modern operating systems, making it a versatile tool in various computing environments.

Definitions

[edit]

ASCII, strings and numbers

[edit]

All input and output at the command line is communicated using printable, human-language characters, such as the letter a or the number 1.[13] One of the earliest devised and most widespread ways of encoding these characters in a consistent manner which computers could understand was a standard called ASCII.[14] ASCII systematically encodes human readable text into and out of binary code which can be read by computers.[15] Today, all modern terminal emulators are capable of understanding all 95 English language printable characters and numerous control characters from the 128 code-point ASCII standard for character encoding.[16] Control characters most commonly seen during a shell session are newline, tab, space and "null."

$ printf 'newline: <%b>\n' $'\n'
newline: <
>
$ printf 'tab: <%b>\n' $'\t'
tab: <    >
$ printf 'space: <%s>\n' " "
space: < >
$ printf 'null: <%b>\n' $'\0'
null: <>

Any series of characters is called a "string." In Unix-like operating systems, all characters, printable and non-printing, except for a few such as the null character and forward slash /, can be used in naming files. In Unix-like operating systems, all strings are case-sensitive.[17]

In everyday life, people usually begin counting some group of items from the number one: 1, 2, 3 apples. In computer science it is customary to do as the computers do and begin counting the first item from the number zero: 0, 1, 2 oranges, for a total of 3 oranges.

CLI and GUI

[edit]

Long after the first Analytical Engine, in the mid-1960's one of the primary ways for humans and computers to interact in real time was at a keyboard with a teleprinter: only display of textual characters was possible.[18] In the 1970s, after computer monitors were developed yet before display of graphics was available, these interfaces were integrated and were known as hardware video terminals. Their interaction paradigm is the basis of what we consider the command-line interface (CLI).

When computers gained the ability to draw graphics on a monitor, graphical user interfaces (GUI's) were designed.[19] Terminal emulators are GUI software programs which create a visual representation of these earlier hardware computer terminals. Today, when a human user initiates a login session, that procedure usually occurs via some graphical user interface.

GNU Readline

[edit]

In Bash, certain keypress combinations allow a user to operate the terminal emulator in order to move the cursor within the terminal window, search the command history and use tab completion. By default, the keypress combinations in Bash mirror those of the Emacs text editing software.[20] This functionality is provided by a program called GNU Readline and is available in interactive mode only. Default keybindings for control codes include:

  • Ctrl+c - Cancels the current command and presents a new prompt
  • Ctrl+d - Closes the current Bash instance, possibly also closing the terminal-emulator
  • Ctrl+z - Stop a foregrounded process
  • Ctrl+s - Put the terminal to sleep
  • Ctrl+w - Wake the terminal
  • Ctrl+a - Move the cursor to the beginning of the current commandline
  • Ctrl+e - Move the cursor to the end of the current commandline
  • Ctrl+w - Remove one word to the left of the cursor
  • Ctrl+ - Move the cursor one word to the right
  • Ctrl+ - Move the cursor one word to the left

Vi (text editor) keybindings are also available and can be enabled by running set -o vi.[21][22]

Comments

[edit]

Comments can be a valuable way of clarifying information or explaining a script or source file to someone else who might not be familiar with the scripter's intentions or context.

Standard comments in Bash are denoted with a hashtag character: #. Any text to the right of the hashtag to the end of the line will be ignored. Inline comments are allowed, but hashtag comments will not print during debugging. See also: § xtrace.

$ # Define foo
$ foo=bar # An inline hashtag comment occurs on the same line as a command
$ set -x
$ # A regular comment (no output)
$ : "${foo}"
+ : bar
$

Comments denoted with a colon character, :, originated with the Thompson shell.[23] Any arguments to the right of colon : builtin are ignored. Inline comments are not possible, but colon comments will print during debugging and any parameters will have been expanded. [24]

Data structures

[edit]

Bash offers variables and arrays, and though there are numerous kinds of each of these available, the data structures are relatively simple compared to other languages like C or Java. All data is stored in memory as a string.

Some data structures are useful for simple general problems, such as retrieving data that has been stored with a specific identifier. ... The simplest data structure is the one-dimensional (linear) array, in which stored elements are numbered with consecutive integers and contents are accessed by these numbers.[25]

— Encyclopædia Britannica, data structure


Each kind of parameter is distinguished by a specific naming convention.[26]

  • Variables: Data structures which hold just one value
    • Positional parameters: signified by integers.[27]
      • "$1" "$2" "${11}"
    • Special parameters: signified by punctuation characters[28]
      • "$@" "$$" "$?" "$-"
    • Environment variables: signified by all capital letters
      • UNIX variables
        • LESS_SIGUSR1
      • Shell variables
        • Bourne shell variables[29]
          • "$HOME"
        • Bash variables[30]
    • Scripting variables: signified by all lower case letters or by CamelCase
  • Arrays: Data structures which hold multiple values[31][32]
    • Indexed arrays[33]
    • Associative arrays

In this article, examples of variables from this section include "${foo}", PID, PWD, EUID, $$, "${quux}" and "${zork}".[34]

Processes

[edit]

Each operating system (OS) has at its core a program called the kernel which runs commands.[35] The kernel, or "control unit," manages a machine's central processing unit (CPU).[36] Any program running on a computer including the kernel can be described as something called a "process."[37] Processes can be identified and described as having a certain list of "attributes" such as PID, PWD and EUID.

A process identifier attribute, denoted in Bash by the variable dollar $$, is a unique integer between 300 and approximately , depending on the OS. Most processes also have a current working directory (CWD) attribute which is denoted in Bash by the variable $PWD and discoverable with the shell builtin pwd (short for "print working directory"). All processes have attributes which identify their user and group ID's, $UID and $GID, and their "effective" user and group ID's, $EUID and $EGID. Processes can have "effective" owner and group identifiers, but files may not.

$ ps -o pid,uid,euid,gid,egid,cmd=Command | grep -e [b]ash -e [P]ID 
    PID USER       UID  EUID   GID  EGID Command
   3237 liveuser  1000  1000  1000  1000 bash
$ declare -p PWD
declare -x PWD="/home/liveuser"
$

Files and permissions

[edit]

In Unix-like operating systems, all objects locatable on the file system are considered to be "files."[38][a] This term, "files," is an umbrella jargon which includes text files, binary files, directories, device files which are used to represent computer hardware, symbolic links and hard links between files: most anything locatable on a file-system.

All "files" have a set of file-system permission attributes, such as owner and group memberships, which control how processes may interact with the file. These permissions are user configurable so they're considered a kind of discretionary access control (DAC). File permissions describe whether each of "owner," "group" or "other," may have "read," "write" or "execute" access. When a user, via some process, requests access to a file, the kernel looks at the process's and files's identifying attributes, and at the file's permissions. From there, the kernel determines whether and how any particular user process may interact with any particular file.

$ ls -l ~/.bashrc
-rw--r--r--. 1 liveuser liveuser 7597 Aug 11 20:01 /home/liveuser/.bashrc
$

In Unix-like OS's, a written representation of a file's discretionary access control (DAC) permissions is called a "mode."[39] Shell builtin umask allows the user to define a default set of DAC permissions for all files created thereafter.[40]

The standard file permission is determined by the mask for new file creation. The value of this mask can be displayed using the umask command. Instead of adding the symbolic values to each other, as with chmod, for calculating the permission on a new file they need to be subtracted from the total possible access rights.

Paths

[edit]

In Unix-like OS's, files, hardlinks, device nodes, etc., (i.e., "files") are sorted into directories that form a hierarchical file structure which is nested in a "parent" and "child" manner. The base of the hierarchy is called the "root directory" which is denoted by one forward slash: /.

On the command line, a file can be identified using its full filename or an abbreviated filename.[41] When the kernel searches for a directory, the starting point is the leftmost character of directory name. For full filenames, or "absolute paths," the leftmost directory is known positively: it's the filesystem root directory, /. For abbreviated filenames, or "relative paths," as shorthand on the commandline the current working directory (CWD) can be referred to as ., and its parent directory as ...[b] If a shell process attempts to locate any filename that begins with the string ./, it will only search in the current working directory of that process.

$ realpath -e . ..
/home/liveuser
/home
$

The $PATH variable will be discussed in detail in the section, § PATH and system commands.

Execution

[edit]

"Execution" of a given program occurs when a user (or some other program) asks the operating system to act upon the instructions contained in the given program.

By default, Bash reads user code one line at a time, interprets any newline or semi-colon character ; as the end of the current command, and executes commands in sequence. If an interactive command extends beyond the width of the terminal emulator, it's usually possible to keep typing and the command will wrap around. To extend a command beyond a newline onto an additional line, it's necessary that the final character of the first line be an unescaped backslash, \, which signals "line continuation." Bash always finishes parsing and executing one full commandline before moving on to and beginning with the parsing of the next commandline.

$ foo=aa bar=bb quux=cc zork=dd; set -o xtrace
$ : "${foo}"; : "${bar}"
+ : aa
+ : bb
$ : "${quux}" \
> : "${zork}"
+ : cc : dd
$

The first word of a commandline is known as the "command position." Under UNIX coventionality, the first word of the commandline is always some kind of a command, and the rest of the words in the commandline string are either options for the command, arguments for the options, or some kind of input upon which the command will operate. "Options" are also called "flags," "switches," or, more formally, "operators." When Bash attempts to locate a command for execution, the directories it searches are those listed in the $PATH variable and the current working directory.[42]

$ # [COMMAND POSITION] [OPTION] [ARGUMENTS] 
$ # ,--^   ,------------^   ,----^
$ declare -p USER BASH_VERSION
declare -x USER="liveuser"
declare -- BASH_VERSION="5.2.37(1)-release"
$

Users and PS1

[edit]

A user account can be created for either a human or a programmatic user. In Unix-like OS's, there are two kinds of users: "privileged" and "regular." A privileged user, such as "root" or the operating system kernel, is allowed to do anything whatsoever on the machine. Unprivileged users are limited in various ways.

When an interactive shell session waits for user input, often within a terminal emulator connected to a peripheral keyboard, by default it prints a particular string of characters to the screen.[43] In Bash, the value of this waiting-string is held in the shell variable $PS1. For regular users a common default value for $PS1 is the dollar character, $.[c] For the superuser a common default value is hashtag (#)

$ sudo --login --user root
[sudo] password for liveuser:
# vim /home/liveuser/names.txt
# exit
$ grep -e bob ./names.txt
grep: ./names.txt: Permission denied

Modes

[edit]

Programming paradigm

[edit]

Although most users think of the shell as an interactive command interpreter, it is really a programming language in which each statement runs a command. Because it must satisfy both the interactive and programming aspects of command execution, it is a strange language, shaped as much by history as by design.[44]


Bash was written in C.[45] A modular style can be approximated through good style and careful design.[46] It is often used in an imperative or procedural style.[47]

Interactive and non-interactive modes

[edit]

As a command processor, Bash can operate in two modes: interactive or non-interactive. In interactive mode, commands are usually read from a terminal emulator. In non-interactive mode, which facilitates automation, commands are usually read from named files known today as shell scripts. When executed as a standalone command at the command-line interface (CLI), by default Bash opens a new shell in interactive mode.

Scripts

[edit]

Shell scripts are text files that contain code, often commands, intended to be read and acted upon by some particular interpreter in a batch process in a non-interactive mode and without any further user interaction. Interpreted scripts are programs that do not require their source code to be compiled: all of the relevant source code is contained within the script. There are many programs which can serve as an script interpreter: Perl,[48] Ruby, Python,[49] AWK, etc. Interpreted scripts are most often written for Unix shells.

The first two characters of the first line of any (executable) shell script begins with a something called a hash-bang: literally the characters hashtag (#) and bang (!) side by side.

$ cat ./example.sh
#! /bin/env bash
echo foo
exit

$

If a script is intended to be run by a user as a stand-alone program on the commandline, then it is referred to as an "executable." By convention, the filenames of executable unix shell scripts are identified the suffix .sh. The "execute" bit can be enabled on a shell script with the utility chmod:

$ ls -l ./example.sh
-rw-r--r--.1 liveuser liveuser 32 Aug  3 22:33 example.sh
$ ./example.sh
bash: ./example.sh: Permission denied
$ chmod 0744 ./example.sh
$ ls -l ./example.sh
-rwxr--r--.1 liveuser liveuser 32 Aug  3 22:33 example.sh
$ ./example.sh
foo
$

The source builtin

[edit]

With the source, or synonymous ., command, Bash can read and execute shell commands from files which are not marked as executable, which do not have hash-bangs, and which do not have the file extension .sh. Such files are known as "source files" or "dotfiles." In Unix, file names which begin with a "dot," such as ~/.bashrc are considered "hidden files."

Login and non-login shells

[edit]

Bash can be executed as a login shell, or "session leader," in both interactive and non-interactive modes via the --login option. "Logging in" requires user authentication. For this reason, only one login shell exists per user session. In GNU/Linux, a user's login shell is identified in the /etc/passwd file.

$ awk -F ':' '$1 ~ /root/' /etc/passwd
root:x:0:0:Super User:/root:/bin/bash

When a human user initiates a login session, this procedure often occurs in a graphical user interface (GUI). When a user opens a terminal emulator, the emulator executes a non-login instance of the user's login shell.

Logging out of a shell session from within a terminal emulator can be accomplished with the exit command or, by default in Bash, pressing Ctrl+d.

Startup source files

[edit]

When Bash starts, it uses source to execute commands in a variety of dotfiles (see lists below).[50] These dotfiles, unlike shell scripts, typically have neither the execute permission enabled nor an hash-bang. By default Bash will source a somewhat different set of files, and in a different sequence, depending on:[51]

  • How bash is called
    • interactively, non-interactively, invoked with name sh
  • Which options are used
    • --login, --rcfile, --norc, --posix
  • Which environment variables are defined
    • BASH_ENV, ENV , and
  • Which files exist
    • /etc/profile
    • ~/.bash_profile
    • ~/.bash_login
    • ~/.profile
    • ~/.bash_logout, and
    • ~/.bashrc among others.

Of course, any startup file can also execute commands from any other file. Startup files can affect shell behavior, terminal emulators, the X window system and the window manager.

POSIX mode

[edit]

The POSIX IEEE 1003.1 standard specifies a common set of definitions that any shell system application (bash, dash, zsh, etc.) may conform to.[52] Any shell user script (./myscript.sh) written in conformance with POSIX guidelines should be executable by any shell system application that has implemented the POSIX specification. As a result, there can be a reasonable expectation that POSIX-compliant scripts can be executed with success on any Unix or Unix-like operating systems which implements the POSIX standard (Linux, OpenBSD, Oracle Linux, HP-UX, etc.). These scripts are considered "portable" as they are and without any further modifications. The portion of POSIX that applies to shells and command line utilities is a subset of a larger group of POSIX standards that further specify how terminals and terminal emulators aught to function in order to also be considered portable.

When Bash is operating in POSIX mode, fewer features are available but the resulting code can be executed on a greater variety of operating systems.

To enable POSIX mode at the initialization of an interactive shell, Bash can be executed as either sh, bash --posix or bash -o posix.[53] To cause a script to be initialized in POSIX mode, one would use the either the hashbang #! /bin/env sh or the less portable #!/bin/sh. When an instance of Bash is operating in POSIX mode, the environment variable $POSIXLY_CORRECT is defined, and the value of the environment variable $SHELLOPTS includes the string posix.

$ declare -p POSIXLY_CORRECT
bash: declare: POSIXLY_CORRECT: not found
$ sh
$ declare -p POSIXLY_CORRECT
declare -- POSIXLY_CORRECT="y"
$

The full list of features available in Bash which are not specified by POSIX is considerable.[54] Here is a partial list:

  • Any arrays other than the array of positional parameters, $@, are not POSIX
  • The double bracket extended test construct, [[...]], is not POSIX
    • [...] and test are POSIX
  • One of the double-parentheses arithmetic-evaluation syntaxes, ((...)), is not POSIX
    • $((...)) is POSIX
  • Brace expansion, kernel{,-headers}, is not POSIX
  • Dynamic scoping of parameters and the local builtin are not POSIX
  • Process substitution, <(...), is not POSIX
  • Certain string-manipulation operations in Parameter Expansions are not POSIX
  • Most Bash builtin commands are not POSIX
    • The command enable -s prints the list of Bourne Special Builtins, which are POSIX
      $ enable -s | wc --lines
      16
      $ enable | wc --lines
      61
      
    • The enable builtin itself is not POSIX
    • In Bash, in non-POSIX mode, the . and source builtins are synonymous
      • The . (i.e., 'dot') builtin is POSIX, however
      • The source builtin is not POSIX
  • The $EPOCHSECONDS and $EPOCHREALTIME shell variables are not POSIX[55]

System commands which are available in modern Unix-like operating systems, and which are also specified by POSIX may have fewer option flags or fewer relevant environment variables available under POSIX.

Because of these and other differences, modern (version 5) Bash shell scripts are rarely runnable "as-is" under the Bourne or legacy Korn shell interpreters. Scripting with portability in mind is becoming less common as GNU/Linux becomes more widespread.[53][56]

Code that is valid syntax in Bash and yet is not specified by POSIX is called a "bashism." The program checkbashisms can be used to make sure that a script can be executed in Debian Linux without any portability errors.[57] Vidar Holen's shellcheck is another static linter written in Haskell which can parse script syntax for compatibility with any or all of bash, dash, ksh, and Bourne sh.[58] The syntax requirements for each shell are each a little different. For example, Debian's policy allows some extensions in their scripts (as they are in the dash shell),[56] while a script intending to support pre-POSIX Bourne shells, like autoconf's configure, are even more limited in the features they can use.[59]

Other modes

[edit]
  • Privileged mode
In Bash, "privileged mode" is a rarely used option inherited (perhaps?) from the SVR4.2 UNIX System V shell (circa 1992).[60] It can be enabled with set -p and disabled with set +p.[61] When privileged mode is enabled, the $SHELLOPTS shell variables includes the string, "privileged."
  • Extended debugging mode
Enabled via bash --debugger at invocation or via shopt -s extdebug during either interactive or non-interactive modes. It uses a separate program called bashdb. extdebug is not available in POSIX mode. See documentation for more information. See also § Debugging.
  • Compatibility modes

Bash-4.0 introduced the concept of a shell compatibility level, specified as a set of options to the shopt builtin (compat31, compat32, compat40, compat41, and so on). There is only one current compatibility level – each option is mutually exclusive. The compatibility level is intended to allow users to select behavior from previous versions that is incompatible with newer versions while they migrate scripts to use current features and behavior. It's intended to be a temporary solution.[62]

— Bash Reference Manual, 6.12 Shell Compatability Mode

Observability

[edit]

The xtrace option

[edit]

When xtrace is enabled, simple debugging content is printed to the terminal. It can be enabled with set -o xtrace or set -x, and disabled with set +o xtrace, set +x or set -. These options are also accepted at the commandline and at hash-bangs: #!/bin/bash -x, etc.

$ bash -x
$ echo $((  2 + 2  ))
+ echo 4
4
$ set -- 1 2 3
$ printf '<%s>\n' "$@"
+ printf '<%s>\n' 1 2 3
<1>
<2>
<3>
$

The xtrace is specified by POSIX. See also § Debugging.

The verbose option

[edit]

The verbose option prints strings to the terminal as they are read, and before any expansions are performed. Rarely used.[63]

Exit codes

[edit]

When bash executes commands, exit status codes, also called "return codes," are produced which can offer some insight into the manner in which a program ceased running. The value of the most recently captured exit code is held within the shell parameter, 'question mark:' $?. In non-arithmetic contexts, (i.e., most of the time) the numerical or "Boolean" value of "true" is zero (0), and the value of "false" is one (1).

When a system command has executed, the intended meaning of its exit status can most often be found in its man page; usually a zero indicates success and a nonzero exit status indicates some kind of failure condition or partial success. ping is a well known command with three meaningful exit codes: 0, 1, and 2.

In Bash, within arithmetic contexts, the numerical truth values are reversed: "true" is one and "false" is zero. An arithmetic context can usually be identified by the syntax ((...)) or $((...)). If an arithmetic statement evaluates to the integer zero, then the statement is considered "true," and the exit code is one. If the statement evaluates to any number other than zero the arithmetic statement is "false" and the exit code is zero.

Not all Linux/UNIX commands provide meaningful exit codes beyond zero and one, and there is no standard system for definitions of exit codes in Linux.

$ true; echo "$?" # Exit code means "true"
0
$ false; echo "$?"; echo # Exit code means "false"
1
$
$ bash -c 'exit 99'; printf 'exit-code: %d\n\n' "$?"
exit-code: 99
$
$ ((  1 - 1  )); printf '%d\n' "$?" # This exit code means "true"
1
$ ((  1 + 1  )); printf '%d\n' "$?" # ...and this exit code means "false"
0

Job control

[edit]

The Bash shell has two modes of execution for commands: batch (asynchronous), and concurrent (synchronous). To execute commands in batch mode (i.e., in sequence) they must be separated by the character ;, or on separate lines:

$ command1; command2
$ command3
$

In this example, when command1 is finished, command2 is executed, and when command2 has completed, command3 will execute. A background execution of command1 can occur using symbol & at the end of an execution command, and process will be executed in background while immediately returning control to the shell and allowing continued execution of commands.

$ command1 &
$

Or to have a concurrent execution of command1 and command2, they must be executed in the Bash shell in the following way:

$ command1 & command2
$

In this case command1 is executed in the background, & symbol, returning immediate control to the shell that executes command2 in the foreground. A process can be stopped and control returned to bash by typing Ctrl+z while the process is running in the foreground.[64] A list of all processes, both in the background and stopped, can be achieved by running jobs:

$ jobs
[1]-  Running                  command1 &
$

In the output, the number in brackets refers to the job id. The plus sign signifies the default process for bg and fg. The text "Running" and "Stopped" refer to the process state. The last string is the command that started the process.

The state of a process can be changed using various commands. The fg command brings a process to the foreground, while bg sets a stopped process running in the background. bg and fg can take a job id as their first argument, to specify the process to act on. Without one, they use the default process, identified by a plus sign in the output of jobs. The kill command can be used to end a process prematurely, by sending it a signal. The job id must be specified after a percent sign:

$ sleep 100 &
[1] 4904
$ kill %1
$ jobs
[1]+  Terminated                    sleep 100
$

Job control, also known as "Monitor mode," is enabled by default in interactive shells, and can be disabled with set +m.

Signals

[edit]

Signaling is a means of inter-process communication (IPC). Sometimes a commandline process may seem to freeze in the middle of execution. In these instances it may become necessary to identify which process may be blocked and to manually end the offending process.

At an interactive terminal, it is usually sufficient to press Ctrl-c to end the current foreground process and return control back to the user prompt, or to press Ctrl-z to suspend it. Occasionally attempting to suspend a process will succeed when attempts to cancel a process appear unresponsive. In other cases it may be necessary to use the kill program to send an IPC signal. In this example, we use the kill command from a second terminal screen to terminate the process with PID 4331.

$ tty # Terminal one
/dev/pts/0
$ whoami
liveuser
$ sleep 1000 # Command hangs
$ tty # Terminal two
/dev/pts/1
$ whoami
liveuser
$ ps aux | grep -e sleep -e PID
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START    TIME COMMAND       
liveuser    4331  0.0  0.0 230336  2312 pts/1    S+   11:19    0:00 sleep 1000
liveuser    4333  0.0  0.0 231248  2516 pts/0    S+   11:19    0:00 grep --color=auto -e sleep -e PID
$ kill 4331
$ ps aux | grep -e sleep -e PID # The sleep process has ended
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START    TIME COMMAND       
liveuser    4333  0.0  0.0 231248  2516 pts/0    S+   11:19    0:00 grep --color=auto -e sleep -e PID
$
$ tty # Terminal one again
/dev/pts/0
$ whoami
liveuser
$ sleep 1000
Terminated
$

In Unix-like operating systems, a user is allowed to instruct the kernel to send a signal to a process that is owned by the user. A regular user may not send a signal to a privileged process. Signals can be sent to a process using the kill builtin or using the system binary of the same name.

$ whoami
liveuser
$ ps aux | awk '$2 ~ /\<1\>/' # Let\s view some info on the kernel process, process 1.
root           1  0.0  0.2  37140 20440 ?        Ss   04:44    0:18 /usr/lib/systemd/systemd --switched-root --system --deserialize=53 rhgb
$ kill -s SIGKILL 1
bash: kill: (1) - Operation not permitted
$ type -a kill
kill is a shell builtin
kill is /usr/bin/kill
$ /usr/bin/kill -s SIGKILL 1
kill: sending signal to 1 failed: Operation not permitted
$

The most commonly used signals can be viewed with kill -L | head -n 4. Each IPC signal is associated with a signal number, but exit codes and signal codes are two different things. While sending a process an IPC signal of 9 (a "KILL" signal) will almost certainly terminate the process immediately, it will most likely not result in the process returning an exit code of 9.

By default in Bash, builtin kill sends a TERM ("terminate") signal. It's common for commandline utilities to respond to a SIGTERM by shutting down and exiting cleanly. The Ctrl-c keypress sequence in Bash sends a SIGINT, interrupt signal, to the foreground process. The Ctrl-z keypress sequence sends the SIGSTOP, stop signal.[65] When a process receives a SIGKILL, the process terminates immediately and messily. It is recommended to use SIGKILL only as a last resort.[66] The SIGKILL signal cannot be blocked or handled.

Processes can "catch" and "handle" IPC signals they receive. A user can use the kill builtin to "send" an IPC signal to another process. That target process can set up a mechanism, some plan beforehand, for how to repsond whenever any particular signal might be received, or "caught." The way a target program responds is referred to as how the program "handles" receiving the signal. In the man pages one can see how some system commands will print out certain information to the terminal when they receive a SIGHUP: for example, the dd command.

When bash is interactive, in the absence of any traps, it ignores SIGTERM (so that kill 0 does not kill an interactive shell), and catches and handles SIGINT (so that the wait builtin is interruptible). When bash receives SIGINT, it breaks out of any executing loops. In all cases, bash ignores SIGQUIT. If job control is in effect, bash ignores SIGTTIN, SIGTTOU, and SIGTSTP.[67]

—  bash(1)

By default Bash shell scripts receive and respond to any and all IPC signals sent to them, however, Bash scripts can utilize the trap builtin to catch and handle signals.[68]

$ cat ./trap-example.sh 
#! /usr/bin/env bash
trap umask EXIT
echo bar
exit 0
$ chmod 0700 trap-example.sh
$ ./trap-example.sh 
bar
0077
$

There are a few signals which are only available from within Bash as GNU extensions: ERR, EXIT, RETURN and DEBUG. These signals can be useful in debugging, and can only be sent and handled by shell builtins. See also § Debugging.

Values of parameters

[edit]

There are many different implementations of echo. Some have the -e option, and some don't.[69] The list of options is not uniform across implementations, though echo and printf are both specified by POSIX. If a scripter wishes to know the precise value of a string contained by a variable, then the most consistent way of doing so is to use printf.

For any string containing any character (besides null?) including digits, the format specifier is %s.

$ foo=abc bar=123
$ printf '<%s>\n' "${foo}" "${bar}"
<abc>
<123>
$

For digits only, the format specifier is %d.

$ printf '<%d>\n' "${foo}" "${bar}"
bash: printf: abc: invalid number
<0>
<123>
$

With printf, a newline is never included in the output unless the scripter includes a newline in the format string. In the example below, where a newline has been omitted from the format string, the value of PS1 is printed on the same line as the output of the previous command.

$ printf '<%s>' "${foo}" "${bar}"
<abc><123>$

Another very consistent method is to use declare -p. The output of declare -p can be reused as input. However, not all variables and parameters can be printed using declare -p, for example, the values of the Special Parameters. The Special Parameter hashtag, "$#", reports how many Positional Parameters are currently defined.

$ declare -p foo bar
declare -- foo="abc"
declare -- bar="123"
$ declare -p "$#"
bash: declare: 0: not found
$

For a full string of input at an interactive shell...

$ declare -p #

...the hashtag would be interpreted by Bash as an inline comment. With the comment and all text to the right of it removed, the command that Bash would execute would be declare -p. This command would, according to help declare, "display the values and attributes of each NAME," i.e., each variable, and, "if no NAMEs are given, display the values and attributes and values of all variables," which can be over 100 lines of output.

On the other hand, printf cannot display variables' attributes. See also § Debugging.

$ readonly foo
$ declare -p foo
declare -r foo="abc"
$ printf '<%s>' "${foo}"
<abc>
$


Environment

[edit]

Configurable execution environment(s):[70]

  • Shell and session startup files such as ~/.bashrc and ~/.profile (i.e., dotfiles);
  • Settings (set built-in) and shell options (shopt built-in) which alter shell behavior;

Shell and session startup Files (a.k.a., "dot files")

When Bash starts, it executes the commands in a variety of dot files.[50] Unlike Bash shell scripts, dot files do typically have neither the execute permission enabled nor an interpreter directive like #!/bin/bash.

  • Legacy-compatible Bash startup example

The example ~/.bash_profile below is compatible with the Bourne shell and gives semantics similar to csh for the ~/.bashrc and ~/.bash_login. The [ -r filename ] && cmd is a short-circuit evaluation that tests if filename exists and is readable, skipping the part after the && if it is not.

[ -r ~/.profile ] && ~/.profile             # set up environment, once, Bourne-sh syntax only
if [ -n "$PS1" ]; then                      # are we interactive?
   [ -r ~/.bashrc     ] && ~/.bashrc        # tty/prompt/function setup for interactive shells
   [ -r ~/.bash_login ] && ~/.bash_login    # any at-login tasks for login shell only
fi                                          # End of "if" block
  • Operating system issues in Bash startup

Some versions of Unix and Linux contain Bash system startup scripts, generally under the /etc directory. Bash executes these files as part of its standard initialization, but other startup files can read them in a different order than the documented Bash startup sequence. The default content of the root user's files may also have issues, as well as the skeleton files the system provides to new user accounts upon setup. The startup scripts that launch the X window system may also do surprising things with the user's Bash startup scripts in an attempt to set up user-environment variables before launching the window manager. These issues can often be addressed using a ~/.xsession or ~/.xprofile file to read the ~/.profile — which provides the environment variables that Bash shell windows spawned from the window manager need, such as xterm or Gnome Terminal.

Commands

[edit]

Aliases

[edit]

Aliases allow a string to be substituted for a word that is in a position in the input where it can be the first word of a simple command. Aliases have names and corresponding values that are set and unset using the alias and unalias builtin commands.

— GNU Bash Reference Manual, Ch 6.6 Aliases[71][72][73][74][75]

Keywords / Reserved words

[edit]
  • function
    • Bash function declarations which include this particular keyword are not compatible with Bourne/Korn/POSIX scripts, however, Bash does accepts the function declaration syntax used by Bourne, Korn and POSIX-compliant shells.

Functions

[edit]

Shell functions are a way to group commands for later execution using a single name for the group. They are executed just like a "regular" simple command. When the name of a shell function is used as a simple command name, the shell executes the list of commands associated with that function name. Shell functions are executed in the current shell context; there is no new process created to interpret them.

—  GNU Bash Reference Manual, Ch 3.3 Shell Functions[76][77][78][79][80][81]

Builtin commands

[edit]
  • Various Built-In Commands:
    • POSIX Special builtins:[82]
      • cd, pwd, etc.
    • set[83]
      • Xtrace: [ set -x | set -o xtrace ]. The shell's primary means of debugging. Both xtrace and verbose can be turned off at the same time with the command set -.
      • Verbose: [ set -v | set -o verbose ]. Prints a command to the terminal as Bash reads it. Bash reads constructs all at once, such as compound commands which include if-fi and case-esac blocks. If a set -v is included within a compound command, then "verbose" will be enabled the next time Bash reads code as input, i.e., after the end of the currently executing construct.[84]
      • Both xtrace and verbose can be turned off at the same time with the command set -.
    • shopt[85]
      • expand-aliases: On by default in interactive shells. Some developers discourage its use in scripts.

PATH and system commands

[edit]

When the shell looks for external commands, it relies on the Bourne shell variable $PATH. $PATH contains a list of directories separated by colons, :. Beginning with the leftmost directory and selecting directories in a left to right pattern, each directory is searched until a match is found. In Linux, so that a user can locate additional commands, it's common practice for distribution administrators and package developers to alter the value of an end user's $PATH by including source files in /etc/profile.d and other locations.

When looking for the command, chmod, for instance, after considering internal commands and finding nothing, Bash will search the directories in $PATH and will select the absolute path of the first executable found that has a basename which matches the search string. [42]

If there is more than one command echo available in the directories listed in $PATH, during the process of parsing and executing a commandline, by default only the first command found will be selected. $PATH lookups are slow. The shell speeds up the commandline execution process by remembering command locations in a hash table. To perform a full $PATH search without any interference from the hash table, remove the current table with hash -r and search for all kinds of commands with type -a.

$ # Force a full path search
$ PATH=${PATH}:${HOME}
$ printf 'echo script_file: "$@"\n' > ./echo
$ chmod 0700 ./echo
$ hash -r; type -a echo
echo is a shell builtin
echo is /usr/bin/echo
echo is /home/liveuser/echo
$

In order to execute a commandline with a command found later in the $PATH string, you can specify an absolute path or you can anchor path resolution relative to the current working directory.

$ /home/liveuser/echo foo
script_file: foo
$ ./echo bar
script_file: bar
$

For security reasons it is advisable to make sure the directories in PATH are not world-writeable, or are writeable only by root and trusted users.

Command lookup

[edit]
  • Command position: after expansions, the first word of the full text of the command line.
  • Command name lookup is performed, in the following order:
  • The resulting string is executed as a command.

Control structures

[edit]

short-circuit evaluation

Pipelines

[edit]

However, by using a pipeline, they can engage in multiple cycles of computation at the same time, substantially increasing their speed. In a pipelined control unit, different instructions simultaneously go through the process but at different points. While one instruction is being fetched, a second is being decoded, and so forth.[35]

UNIX-style pipelines: |.

Subshells

[edit]

Subshells: (...);

Logical operators

[edit]
  • AND (&&)
  • OR (||)
  • NOT (!)

Bash supplies "conditional execution" command separators that make execution of a command contingent on the exit code set by a precedent command. For example:

$ cd "$SOMEWHERE" && ./do_something || echo "An error occurred" >&2

Where ./do_something is only executed if the cd (change directory) command was "successful" (returned an exit status of zero) and the echo command would only be executed if either the cd or the ./do_something command return an "error" (non-zero exit status).

Iteration

[edit]

ITERATION: Sometimes programs are repeated indefinitely or until a specific outcome is reached. Each execution of the instructions is an “iteration.”[86]

  • while, until, and select loop compound commands;
  • Arithmetic C-style and list-enumerating for loop compound commands; and
  • continue, break, return, and exit flow control commands;

Compound commands

[edit]

compound: something formed by a union of elements or parts.[87]

— Merriam-Webster's Collegiate Dictionary

Bash also supports if ... fi and case ... esac forms of conditional command evaluation.[e]

Testing

[edit]

Built in commands for testing file attributes, comparing string and integer values, etc.:

  • Traditional test command,
  • Traditional single bracket test: [,
  • Modern double bracket test: [[...]], which includes advanced features:
  • ((...)) numeric evaluation and testing; this includes almost all "C" language operators for arithmetic and numeric comparison;

For all commands the exit status is stored in the special variable $?.

Regular Expressions

[edit]

Bash 3.0 supports in-process regular expression matching using a syntax reminiscent of Perl.[89] Regexp matching is limited to strings on the right side of the =~ operator in the [[..]] extended test construct.[90]

[[ $line =~ [[:space:]]*(a)?b ]] means values for line like ‘aab’, ‘ aaaaaab’, ‘xaby’, and ‘ ab’ will all match, as will a line containing a ‘b’ anywhere in its value.

Coprocesses

[edit]

A coprocess is a shell command preceded by the coproc reserved word. A coprocess is executed asynchronously in a subshell, as if the command had been terminated with the ‘&’ control operator, with a two-way pipe established between the executing shell and the coprocess.[91]

— Bash Reference Manual, 3.2.6 Coprocesses

Data manipulation

[edit]

Word Splitting

[edit]

Split into words (i.e., word splitting)

Quoting

[edit]

When in doubt -- Quote![92]

— Mastering Linux Shell Scripting, by Andrew Mallett


Bash has certain quoting rules: uses of

  • single quotes '...'
  • double quotes "..."
  • backslashes \, and
  • ANSI-C quoting $'...'.

See also § Locales, $"..."

See also backticks `...`: § Deprecated syntax.

Unicode

[edit]

Support for Unicode in echo -e and ANSI-C quoting.

Unicode: international character-encoding system designed to support the electronic interchange, processing, and display of the written texts of the diverse languages of the modern and classical world.[93]

Brace Expansion

[edit]
$ echo kernel{,-headers}
kernel kernel-headers

Brace expansion, also called alternation, is a feature copied from the C shell. It generates a set of alternative combinations.[94] Generated results need not exist as files. The results of each expanded string are not sorted and left to right order is preserved:

$ echo a{p,c,d,b}e
ape ace ade abe
$ echo {a,b,c}{d,e,f}
ad ae af bd be bf cd ce cf

Users should not use brace expansions in portable shell scripts, because the Bourne shell does not produce the same output.

$ # bash shell
$/bin/bash -c 'echo a{p,c,d,b}e'
ape ace ade abe
$ # A traditional shell does not produce the same output
$ /bin/sh -c 'echo a{p,c,d,b}e'
a{p,c,d,b}e

When brace expansion is combined with wildcards, the braces are expanded first, and then the resulting wildcards are substituted normally. Hence, a listing of JPEG and PNG images in the current directory could be obtained using:

ls *.{jpg,jpeg,png}    # expands to *.jpg *.jpeg *.png – after which,
                       # the wildcards are processed
echo *.{png,jp{e,}g}   # echo just shows the expansions –
                       # and braces in braces are possible.

In addition to alternation, brace expansion can be used for sequential ranges between two integers or characters separated by double dots. Newer versions of Bash allow a third integer to specify the increment.

$ echo {1..10}
1 2 3 4 5 6 7 8 9 10
$ echo {01..10}
01 02 03 04 05 06 07 08 09 10
$ echo file{1..4}.txt
file1.txt file2.txt file3.txt file4.txt
$ echo {a..e}
a b c d e
$ echo {1..10..3}
1 4 7 10
$ echo {a..j..3}
a d g j

When brace expansion is combined with variable expansion (a.k.a., parameter expansion and parameter substitution) the variable expansion is performed after the brace expansion, which in some cases may necessitate the use of the eval built-in, thus:

$ start=1; end=10
$ echo {$start..$end} # fails to expand due to the evaluation order
{1..10}
$ eval echo {$start..$end} # variable expansion occurs then resulting string is evaluated
1 2 3 4 5 6 7 8 9 10

Tilde Expansion

[edit]

Tilde expansion ~,

Parameter and variable expansion

[edit]
  • Type
  • Shell parameters
  • Environment variables
  • User variables
  • Scope
  • Arrays
  • Parameter Expansion
    Expansion syntaxes which can perform some tasks more quickly than external utilities, including, among others:
    • Pattern Substitution
      • ${foo//x/y} for sed 's/x/y/g',
    • Remove Matching Prefix or Suffix Pattern
      • ${bar##[a-zA-Z0-9]*} for cut -c8-,
    • Enumerate Array Keys
      • ${!array[@]}, and
    • Display Error if Null or Unset
      • ${var:?error message},

Pathname expansion

[edit]

Pathname expansion, i.e., shell-style globbing and pattern matching using *, ?, [...].[h]

Locales

[edit]

Locale-specific translation via $"..." quoting syntax.[98]

Process redirections and parsing

[edit]

Command substitution

[edit]

Command substitution: $(...),

Process substitution

[edit]

Process substitution, <() or >(), when a system supports it:

Bash supports process substitution using the <(command) and >(command) syntax, which substitutes the output of (or input to) a command where a filename is normally used. (This is implemented through /proc/fd/ unnamed pipes on systems that support that, or via temporary named pipes where necessary).

Arithmetic expansion

[edit]

Arithmetic expansion, ((...)) or $((...)), including

Bash can perform integer calculations ("arithmetic evaluation") without spawning external processes. It uses the ((...)) command and the $((...)) variable syntax for this purpose.

Redirection

[edit]

Redirections of Standard Input, Standard Output and Standard Error data streams are performed, including

  • File writing, >, and appending, >,
  • Here documents, <<,
  • Here strings, <<<, which allow parameters to be used as input, and
  • A redirection operator, >, which can force overwriting of a file when a shell's noclobber setting is enabled;

Its syntax simplifies I/O redirection. For example, it can redirect standard output (stdout) and standard error (stderr) at the same time using the &> operator. This is simpler to type than the Bourne shell equivalent 'command > file 2>&1'. Bash supports here documents. Since version 2.05b Bash can redirect standard input (stdin) from a "here string" using the <<< operator.

Command parsing

[edit]
  • Comments are ignored, from an unquoted # (hash) to the end of the same line;[99][100]
  • Commands are parsed one line at a time:
    • Control structures are honored, and
    • Backslash \ escapes are also honored at the ends of lines;
  • Split into words (i.e., word splitting) according to quoting rules,
    • Including ANSI-C quoting $'...';
  • Seven kinds of expansions are performed in the following order on the resulting string:
    1. (Step 1) Brace expansion kernel{-headers},
    2. (Step 2) Tilde expansion ~,
    3. (Step 3) In a left-to-right fashion:
      • Parameter and variable expansion $foo or ${bar}, including
        • Dynamically scoped variables,
        • Indexed arrays of unlimited size,
        • Associative arrays via declare -A, and
        • Expansion syntaxes which can perform some tasks more quickly than external utilities, including, among others:
          • Pattern Substitution
            • ${foo//x/y} for sed 's/x/y/g',
          • Remove Matching Prefix or Suffix Pattern
            • ${bar##[a-zA-Z0-9]*} for cut -c8-,
          • Enumerate Array Keys
            • ${!array[@]}, and
          • Display Error if Null or Unset
            • ${var:?error message},
      • Command substitution: $(...),
      • Process substitution, <() or >(), when a system supports it:
      • Arithmetic expansion, ((...)) or $((...)), including
    4. (Step 4) Word splitting (again),
    5. (Step 5) Pathname expansion, i.e., shell-style globbing and pattern matching using *, ?, [...],[h]

and Quote removal;

  • Redirections of Standard Input, Standard Output and Standard Error data streams are performed, including
    • File writing, >, and appending, >>,
    • Here documents, <<,
    • Here strings, <<<, which allow parameters to be used as input, and
    • A redirection operator, >, which can force overwriting of a file when a shell's noclobber setting is enabled;
  • Command name lookup is performed, in the following order:
    1. Commands internal to the shell:
    2. Commands external to the shell:
    3. The resulting string is executed as a command.

Interactive-only features

[edit]

Command History

[edit]

Unlimited size command history.[101] This feature is available in interactive mode only.

Directory stack

[edit]

A directory stack (pushd and popd built-ins) feature is available in interactive mode only.

Programmable completion

[edit]

Also known as "tab completion" or "command-line completion", when a user presses the Tab, within an interactive command-shell Bash automatically uses any available completion scripts to suggest partly typed program names, filenames and variable names.[102] [4] The Bash command-line completion system is very flexible and customizable, and is often packaged with functions that complete arguments and filenames for specific programs and tasks.

Bash supports programmable completion via built-in complete, compopt, and compgen commands.[103] The feature has been available since the beta version of 2.04 released in 2000.[104] These commands enable complex and intelligent completion specification for commands (i.e., installed programs), functions, variables, and filenames.[105]

The complete and compopt two commands specify how arguments of some available commands or options are going to be listed in the readline input.As of version 5.1 completion of the command or the option is usually activated by the Tab keystroke after typing its name.[105] This feature is available in interactive mode only.

Prompts

[edit]

Configurable prompts. This feature is available in interactive mode only.

Restricted mode

[edit]

Modern systems provide more secure ways to implement a restricted environment, such as jails, zones, or containers.[106]

A restricted shell is used to set up an environment more controlled than the standard shell. A restricted shell behaves identically to bash with the exception that numerous actions are disallowed or not performed, including:

  • Changing directories with the cd builtin.
  • Setting or unsetting the values of the $SHELL, $PATH, $HISTFILE, $ENV, or $BASH_ENV variables.
  • Specifying command names containing slashes on the CLI.
  • Using absolute pathnames as arguments to the ., history, or hash -p commands
  • Specifying a path search with . -p or command -p
  • Importing function definitions and parsing the value of $SHELLOPTS from the shell environment at startup.
  • Redirecting output using the >, >, <>, >&, &>, and >> redirection operators.
  • Using the exec builtin to replace the shell with another command.
  • Altering shell builtins

Once restricted mode is enabled, it cannot be disabled. These restrictions are enforced after any startup files are read, and it does not apply to shell scripts. Restricted mode is rarely used.

Documentation

[edit]

User Manual

[edit]

A user manual for Bash is provided by the GNU Project. It is sometimes considered to be a more user-friendly document than the man page. "You may also find information about Bash ...by looking at /usr/share/doc/bash, /usr/local/share/doc/bash, or similar directories on your system."[107] On GNU/Linux systems, if the info program is available then the GNU Manual version relevant for your installation should also be available at info bash.[108][109]

Man page

[edit]

The most recent technical manual, or 'man page', is intended to be the authoritative explanatory technical document for the understanding of how bash operates. On GNU/Linux systems, the version relevant for your installation is usually available through the man program at man bash.[108][67][110]

help builtin

[edit]

With recent versions of Bash, information on shell built-in commands can be found by executing help, help [name of builtin] or man builtins at a terminal prompt where bash is installed.

The printf command can be invoked via env to ensure that you run the program found via your shell's search path, and not a shell alias or built-in function: env printf --help.[111]

POSIX Specification

[edit]

For the purpose of allowing inter-operability among different shell programs running on different operating systems, the POSIX Specification influences how modern UNIX-like shells are written. Bash "is intended to be a conformant implementation of the IEEE POSIX "Shell and Utilities" portion of the IEEE POSIX specification (IEEE Standard 1003.1)."[112] The most recent publication of the standard (2024) is available online.[113]

As the standard upon which bash is based, the POSIX Standard, or IEEE Std 1003.1,[114] et seq, is especially informative.

Further resources

[edit]

"The project maintainer also has a Bash page which includes Frequently Asked Questions",[107][115][116] this FAQ is current as of bash version 5.1 and is no longer updated.

Informal avenues of support are available via IRC at libera.chat, in the #bash channel, and mailing lists are available at Bash - GNU Project - Free Software Foundation.

Security and vulnerabilities

[edit]

Root scripts

[edit]

Running any shell scripts as the root user has, for years, been widely criticized as poor security practice. One commonly given reason is that, when a script is executed as root, the negative effects of any bugs in a script would be magnified by root's elevated privileges.

One common example: a script contains the command, rm -rf ${dir}/, but the variable $dir is left undefined. In Linux, if the script was executed by a regular user, the shell would attempt to execute the command rm -rf / as a regular user, and the command would fail. However, if the script was executed by the root user, then the command would likely succeed and the filesystem would be erased.

It is recommended to use sudo on a per-command basis instead.

CGI Scripts

[edit]

Do not use Shell for CGI scripts. You have been warned.[117][118][119]

builtin eval

[edit]

"The eval command is extremely powerful and extremely easy to abuse."[120]

Input validation

[edit]

"Input validation is the process of ensuring data has undergone data cleansing to confirm it has data quality, that is, that it is both correct and useful."

Input validation is performed to ensure only properly formed data is entering the workflow in an information system, preventing malformed data from persisting in the database and triggering malfunction of various downstream components. Input validation should happen as early as possible in the data flow, preferably as soon as the data is received from the external party.[121]

— OWASP Input Validation Cheat Sheet

Command injection

[edit]
  • CWE-77: Improper Neutralization of Special Elements used in a Command ('Command Injection')[122]
  • CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')[123]
  • CWE-88: Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')[124]

Clearlisting is more effective than blocklisting.

  • CWE-184: Incomplete List of Disallowed Inputs[125]

Path traversal

[edit]
  • CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')[126]

TOCTOU errors (Race conditions)

[edit]
  • CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition[127]

The mkdir and mktemp commands are known to create directories / files in an atomic fashion.

Untrusted search PATH

[edit]
  • CWE-426: Untrusted Search Path[128]
  • CWE-427: Uncontrolled Search Path Element[129]
  • CWE-428: Unquoted Search Path or Element[130]
[edit]
  • CWE-61: UNIX Symbolic Link (Symlink) Following[131]

Sensitive information in error messages

[edit]
  • CWE-535: Exposure of Information Through Shell Error Message[132]

Shellshock

[edit]

In September 2014, a security bug was discovered[133] in the program. It was dubbed "Shellshock." Public disclosure quickly led to a range of attacks across the Internet.[134][135][136]

Exploitation of the vulnerability could enable arbitrary code execution in CGI scripts executable by certain versions of Bash. The bug involved how Bash passed function definitions to subshells through environment variables.[137] The bug had been present in the source code since August 1989 (version 1.03)[138] and was patched in September 2014 (version 4.3).

Patches to fix the bugs were made available soon after the bugs were identified. Upgrading to a current version is strongly advised.

It was assigned the Common Vulnerability identifiers CVE-2014-6271, CVE-2014-6277 and CVE-2014-7169, among others. Under CVSS Metrics 2.x and 3.x, the bug is regarded as "high" and "critical", respectively.

Deprecated syntax

[edit]
  • Backtick style command substitutions: `...` is deprecated in favor of
    • $(...);
  • Use of -a or -o in test/[/[[ commands,
    • for example, [ -r ./file -a ! -l ./file ] is deprecated in favor of
      • [ -r ./file ] && ! [ -l ./file ];
  • Use of the arithmetic syntax $[...] is deprecated in favor of
    • $((...)) or
    • ((...)), as appropriate;
  • Use of ^ as a pipeline is deprecated in favor of |;
  • Any uses of expr or let.

Debugging

[edit]

Table of Features

[edit]
Bash features which can be useful during debugging.[4][85][139]
Feature POSIX 2024 Description Bash ver.
Grammar type Formal name Syntax
Special Built-In Utility set / xtrace set -x Yes The shell's primary means of debugging.

It "writes to standard error a trace for each command after it expands the command and before it executes it."

?
Special Parameters Exit Status "$?" Yes "Expands to the shortest representation of the decimal exit status." ?
Parameter Expansions Indicate Null or Unset "${parameter:?[word]}" Yes "Where the expansion of [word], perhaps an error message or a line number, is written to standard error and the shell exits with a non-zero exit code." ?
Special Parameters PID of Invoked Shell "$$" Yes "Expands to the shortest representation of the decimal process ID of the invoked shell." ?
Special Built-In Utility set / verbose set -v Yes "Writes its input to standard error as it is read." ?
Special Built-In Utility set / pipefail set -o pipefail Yes "Derive the exit status of a pipeline from the exit statuses of all of the commands in the pipeline, not just the last (rightmost) command." ?
Special Built-In Utility set / nounset set -u Yes When enabled, will cause the shell to exit with an error message when it encounters an unset variable expansion.

Its use has a number of counter-intuitive pitfalls.

?
Special Built-In Utility set / errexit set -e Yes Errexit is a setting that, when enabled, will, under certain very specific conditions, cause the shell to exit without an error message whenever the shell receives a non-zero exit code.

Its use is somewhat controversial, to the extent that any somewhat obscure computer program can be controversial. Adherents claim that Errexit provides an assurance of verifiability in situations where shell scripts "must not fail." However, opponents claim that its use is unreliable, deceptively simple, highly counter-intuitive, rife with gotchas and pitfalls, and in essence "security theater." Numerous developers of Bash have strongly discouraged the use of this particular setting.

?
Special Built-In Utility trap / EXIT trap '[arg]' EXIT Yes "If a signal specifier is 0 or EXIT, [arg] is executed when the shell exits." If [arg] contains expansions, then [arg] should be in single quotes. ?
Utility printf printf '<%s>\n' "${var}" Yes A means of reliably printing the contents of a variable. ?
Bash Variables BASHPID "${BASHPID}" No "Expands to the process ID of the current bash process."[140] ?
Bash Variables BASH_ARGC "${BASH_ARGC[@]}" No "An array variable whose values are the number of parameters in each frame of the current bash execution call stack."[141] ?
Bash Variables BASH_ARGV "${BASH_ARGV[@]}" No "An array variable containing all of the parameters in the current bash execution call stack."[142] ?
Bash Variables BASH_LINENO "${BASH_LINENO[@]}" No "An array variable whose members are the line numbers in source files where each corresponding member of "${FUNCNAME[@]}" was invoked."[143] ?
Bash Variables BASH_REMATCH "${BASH_REMATCH[@]}" No "An array variable whose members are assigned by the =~ binary operator to the [[ conditional command."[144] ?
Bash Variables BASH_SOURCE "${BASH_SOURCE[@]}" No "An array variable whose members are the source filenames where the corresponding shell function names in the "${FUNCNAME[@]}" array variable are defined."[145] ?
Bash Variables BASH_XTRACEFD "${BASH_XTRACEFD}" No "If set to an integer corresponding to a valid file descriptor, Bash will write the trace output generated when set -x is enabled to that file descriptor."[146] ?
Bash Variables EPOCHREALTIME "${EPOCHREALTIME}" No "Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see time(3)) as a floating point value with micro-second granularity."[147] ?
Bash Variables FUNCNAME "${FUNCNAME[@]}" No "An array variable containing the names of all shell functions currently in the execution call stack."[148] ?
Bash Variables LINENO "${LINENO}" No "Each time this parameter is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script or function."[149] ?
Bash Variables PIPESTATUS "${PIPESTATUS[@]}" No "An array variable containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command)."[150] ?
Bash Variables PPID "${PPID}" No "The process ID of the shell's parent."[151] ?
Bash Variables PS4 "${PS4}" No "The value of this parameter is expanded as with PS1 and the value is printed before each command bash displays during an execution trace."[152] ?
Shell Builtin set / restricted set -r No Restricted mode is intended to improve the security of an individual shell instance from a malicious human with physical access to a machine.

As threat models have changed, it has become less commonly used now than it once was.

?
Shell Builtin shopt / extdebug shopt -s extdebug No "Behavior intended for use by debuggers." ?
Shell Builtin trap / DEBUG trap '[arg]' DEBUG No "If a sigspec is DEBUG, the command arg is executed before" certain kinds of commands. ?
Shell Builtin trap / ERR trap '[arg]' ERR No "If a sigspec is ERR, the command arg is executed whenever..." certain kinds of commands "return a non-zero exit status", subject to similar restrictions as with ErrExit. ?
Shell Builtin trap / RETURN trap '[arg]' RETURN No "If a sigspec is RETURN, the command arg is executed each time a shell function or a script executed with the . or source builtins finishes executing." ?
  • Shell features specified by POSIX:
    • Parameter Expansions:[153]
    • Special Parameters:[154][155]
    • Special Built-In Utility set:[156][157]
    • Special Built-In Utility trap:[157][158]
      • POSIX does specify certain uses of the trap builtin: ...
    • Utility printf: a means of reliably printing the contents of a variable:
  • Bash features not specified by POSIX:
    • Bash Variables:[159][160]
    • Shell Builtin set:[156][157]
    • Shell Builtin shopt:[161][157]
    • Shell Builtin trap:[158][157]
      • While POSIX does specify certain uses of the trap builtin, the following signal specs are Bash extensions: ...
  • Third party debugging utilities:
    • ShellCheck: Shell script analysis tool;[162][58]
    • devscripts-checkbashisms: Check whether a /bin/sh script contains any common bash-specific constructs;[163][57]
    • kcov: Code coverage tool without special compilation options;[164]
    • Bashdb: The Bash symbolic debugger.[165][166]

Examples

[edit]

With the "${var:?}" parameter expansion, an unset or null variable can halt a script.

$ cat ex.sh
#!/bin/bash
bar="foo is not defined"
echo "${foo:?$bar}"
echo this message doesn't print

$ ./ex.sh
./ex.sh: line 3: foo: foo is not defined
$

Reliably printing the contents of an array that contains spaces and newlines first in a portable syntax, and then the same thing in Bash. Note that POSIX doesn't have named array, only the list of arguments, "$@", which can be re-set by the set builtin.

$ # In POSIX shell:
$ set -- "a" " b" " 
>  c "
$ printf ',%s,\n' "$@"
,a,
, b,
,
 c,

Note that in Bash, the number of spaces before the newline is made clear.

$ # In Bash:
$ array=( "a" " b" " 
>  c " )
$ declare -p array
declare -a array=([0]="a" [1]=" b" [2]=$' \n c ')

Printing an error message when there's a problem.

$ cat error.sh
#!/bin/env bash
if ! lsblk | grep sdb
then
  echo Error, line "${LINENO}"
fi
$ ./error.sh
Error, line 130

Using xtrace. If errexit had been enabled, then echo quux would not have been executed.

$ cat test.sh
#!/bin/env bash
set -x
foo=bar; echo "${foo}"
false
echo quux
$ ./test.sh
+ foo=bar
+ echo bar
bar
+ false
+ echo quux
quux

Note: $BASHPID differs from $$ in certain circumstances, such as subshells that do not require bash to be reinitialized.

$ echo $(echo $BASHPID $$)   $$    $BASHPID
              25680    16920 16920 16920
#             |        |     |     |
#             |        |     |     \-- $BASHPID outside of the subshell
#             |        |     \-- $$ outside of the subshell
#             |        \-- $$ inside of the subshell
#             \-- $BASHPID inside of the subshell

Bug reporting

[edit]

An external command called bashbug reports Bash shell bugs. When the command is invoked, it brings up the user's default editor with a form to fill in. The form is mailed to the Bash maintainers (or optionally to other email addresses).[167][168]

History

[edit]

Shell script functionality originated with files called "runcoms" in reference to the 1963 macro processor of the same name. The suffix "rc" is short for "runcom."[169] The term "shell" was coined by Louis Pouzin in 1964 or 1965, and appeared in his 1965 paper, "The SHELL, A Global Tool for Calling and Chaining Procedures in the System,"which describes many features later found in many UNIX shells.[170][171][172] The ASCII standard for character encoding was defined in 1969 in a document called Request for Comments (RFC) 20. [173]


Timeline

[edit]
Date Event
1988-01-10

Brian Fox began coding Bash after Richard Stallman became dissatisfied with the lack of progress being made by a prior developer.[174] Stallman and the FSF considered a free shell that could run existing shell scripts so strategic to a completely free system built from BSD and GNU code that this was one of the few projects they funded themselves. Fox undertook the work as an employee of FSF.[174][175]

1989-06-08

Fox released Bash as a beta, version 0.99.[176] The license was GPL-1.0-or-later. "In addition to supporting backward-compatibility for scripting, Bash has incorporated features from the Korn and C shells. You'll find command history, command-line editing, a directory stack (pushd and popd), many useful environment variables, command completion, and more."[177] Eventually it supported "regular expressions (similar to Perl), and associative arrays".

1991

Bash holds historical significance as one of the earliest programs ported to Linux by Linus Torvalds, alongside the GNU Compiler (GCC).[178]

1992 ~ 1994

Brian Fox retired as the primary maintainer sometime between mid-1992 [179] and mid-1994.[180][181] His responsibility was transitioned to another early contributor, Chet Ramey.[115][182][10][9] Since then, Bash has become the most popular default interactive shell among the major GNU/Linux distributions, such as Fedora, Debian, and openSUSE, as well as among their derivatives and competitors.[183][184]

1994-01-26

Debian – initial release. Bash is the default interactive and non-interactive shell.[185]

1996-12-31

Chet Ramey released bash 2.0. The license was GPL-2.0-or-later

1997-06-05

Bash 2.01 released.

1998-04-18

Bash 2.02 released.

1999-02-19

Bash 2.03 released.

2000-03-21

Bash 2.04 released.

2000-09-14

Bug-bash mailing list exists.[186]

2001-04-09

Bash 2.05 released.[187]

2003

Bash became the default shell on Apple's operating systems (i.e., MacOS) starting with OS X 10.3 Panther.[188][189] It was available on OS X 10.2 Jaguar as well where the default shell was tcsh.

2004-07-27

Bash 3.0 released.[190]

2005-12-09

Bash 3.1 released.[191]

2006-10-12

Bash 3.2 released.[192] The license was GPL-2.0-or-later.

2006

Ubuntu replace bash with dash as its default shell.

2009-02-20

Bash 4.0 released[193] Its license is GPL-3.0-or-later.

2010-01-02

Bash 4.1 released.[194]

2011-02-14

Bash 4.2 released.[195]

2012

On Solaris 11, "the default user shell is the Bourne-again (bash) shell."[196]

2014-02-27

Bash 4.3 released.[197]

2014-09-08

Shellshock (software bug).[198][199] Patches to fix the bugs were made available soon after the bugs were identified.[200]

2015

Termux and other terminal emulation applications provide availability of Bash on Android.

2016-09-15

Bash 4.4 released.

2009 ~ 2018

Apple declines to accept version 4 of Bash being licensed under version 3 of the GNU GPL, and ceases to supply upgrades to Bash beyond version 3.2 (as supplied in MacOS Mojave).

2019-06-05

Apple declares zsh its default shell[201] and supplies version 5.7 in its Catalina release of MacOS.[202][203][204]

2019-01-07

Bash 5.0 released.[205]

2020-12-07

Bash 5.1 released.[206]

2022-09-26

Bash 5.2 released.

2025

Bash 5.3 released.

See also

[edit]

Unix shells

[edit]

Graphical interface to scripts

[edit]

There are many programs that allow you to create a graphical interface for bash scripts.

  • dialog - is a utility that allows you to create dialog boxes in the console, using the curses and ncurses libraries .
  • whiptail - is an analogue of the dialog utility, it uses the newt library .
  • zenity - is the most popular application for creating a graphical interface for scripts.
  • kdialog - is a KDE equivalent of zenity .
  • yad - is a fork of zenity, with more features.
  • xdialog - is a replacement for dialog that is designed to give programs launched from the terminal an X Window System interface .
  • gtkdialog - is the most functional utility for creating graphical applications on bash scripts.

Further reading

[edit]

Notes

[edit]
  1. ^ This description does not apply to Windows-based operating systems.
  2. ^ The shell builtin ., synonymous with the source builtin, is something else.
  3. ^ not to be confused with the shell variable $$
  4. ^ a b Shell scripts do not require compilation before execution and, when certain requirements are met, can be invoked as commands by using their filename.
  5. ^ concept drawn from ALGOL 68;[88]
  6. ^ Bash 4 also switches its license to GPL-3.0-or-later.
  7. ^ In February 2009,[95] Bash 4.0[f][96] introduced support for associative arrays.[4] Associative array indices are strings, in a manner similar to AWK or Tcl.[97] They can be used to emulate multidimensional arrays.
  8. ^ a b Although they can be used in conjunction, the use of brackets in pattern matching, [...], and the use of brackets in the testing commands, [ and [[ ... ]], are each one different things.
  9. ^ for this functionality, see current versions of bc and awk, among others.

References

[edit]
  1. ^ Chet Ramey (5 July 2025). "Bash-5.3-release available". Retrieved 5 July 2025.
  2. ^ "GNU Bash". gnu.org. GNU Project. Archived from the original on 26 April 2019. Retrieved 8 August 2025. Bash is free software, distributed under the terms of the [GNU] General Public License as published by the Free Software Foundation, version 3 of the License (or any later version).
  3. ^ "bash-1.11". oldlinux.org. Archived from the original on 15 October 2021. Retrieved 8 August 2025. See test.c for GPL-2.0-or-later
  4. ^ a b c d "BashFAQ/061: Is there a list of which features were added to specific releases (versions) of Bash?". wooledge.org. Archived from the original on 2 March 2021. Retrieved 8 August 2025.
  5. ^
  6. ^ "operating system". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  7. ^ "Bourne shell". ibm.com. IBM. Retrieved 8 August 2025. The Bourne shell is an interactive command interpreter and command programming language.
  8. ^
  9. ^ a b Morris, Richard (14 December 2015). "Chet Ramey: Geek of the Week". Simple Talk. Archived from the original on 31 July 2020. Retrieved 8 August 2025.
  10. ^ a b
  11. ^ "GNU's Bulletin, vol 1 no 7, June, 1989 :: GNU Project Status Report". gnu.org. GNU Project. Retrieved 8 August 2025. Brian Fox has now completed GNU's version of sh, called BASH, the `Bourne Again SHell'.
  12. ^
    • Stallman, Richard (12 November 2010). "About the GNU Project (Footnote 5)". gnu.org. GNU Project. Archived from the original on 24 April 2011. Retrieved 8 August 2025. "Bourne Again Shell" is a play on the name Bourne Shell, which was the usual shell on Unix.
    • Gattol, Markus (10 January 2015). "Bourne-again Shell". markus-gattol.name. Archived from the original on 9 March 2011. Retrieved 8 August 2025. The name is a pun on the name of the Bourne shell (sh), an early and important Unix shell written by Stephen Bourne and distributed with Version 7 Unix circa 1978, and the concept of being 'born again'.
  13. ^ "MDN Glossary of web terms: character". mozilla.org. Mozilla Corporation. Retrieved 15 August 2025.
  14. ^ "ASCII". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  15. ^ "binary code". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  16. ^ "code". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  17. ^ Michael, Randal (2008). Mastering Unix Shell Scripting, 2e. Wiley Publishing, Inc., Indianapolis, Indiana. p. 3. ISBN 978-0-470-18301-4. Retrieved 16 August 2025. UNIX is case sensitive. Because UNIX is case sensitive, our shell scripts are also case sensitive.
  18. ^ "Analytical Engine". britainnica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  19. ^ "graphical user interface". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  20. ^ "GNU Bash Manual: 8.2.1 Readline Bare Essentials". gnu.org. GNU Project. Retrieved 8 August 2025.
  21. ^ "GNU Bash Manual: 8.5 Readline vi mode". gnu.org. GNU Project. Retrieved 8 August 2025.
  22. ^ Rippee, Scott (5 October 2012). "Getting started with BASH: A Bash Tutorial". hypexr.org. Archived from the original on 2 March 2021. Retrieved 8 August 2025.
  23. ^ "Ken Thompson". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  24. ^ The Open Group. "2.15 Special Builtins: colon - null utility". opengroup.org. Base Specifications Issue 8: IEEE Std 1003.1-2024. Retrieved 8 August 2025.
  25. ^ "data structure". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  26. ^ "Bash Reference Manual, 3.4 Shell Parameters". gnu.org. GNU Project. Retrieved 14 August 2025. A parameter is an entity that stores values. It can be a name, a number, or one of the special characters listed below. ... A variable has a value and zero or more attributes.
  27. ^ "Bash reference manual, 3.4.1 Positional Parameters". gnu.org. GNU Project. Retrieved 15 August 2025.
  28. ^ "Bash reference manual, 3.4.2 Special Parameters". gnu.org. GNU Project. Retrieved 15 August 2025.
  29. ^ "Bash reference manual, 5.1 Bourne Shell Variables". gnu.org. GNU Project. Retrieved 15 August 2025.
  30. ^ "Bash reference manual, 5.2 Bash Variables". gnu.org. GNU Project. Retrieved 15 August 2025.
  31. ^ "Bash reference manual, 6.7 Arrays". gnu.org. GNU Project. Retrieved 15 August 2025.
  32. ^ "Thirteen Incorrect Ways and Two Awkward Ways to Use Arrays". oilshell.org. 6 November 2016. Retrieved 15 August 2025.
  33. ^ "integer". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  34. ^ "parameter (noun)". merriam-webster.com. Merriam-Webster's Collegiate Dictionary. Retrieved 15 August 2025.
  35. ^ a b "control unit". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  36. ^ "central processing unit". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  37. ^ "computer program". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  38. ^ "Introduction to Linux, Ch. 3 About files and the filesystem, 3.1. General overview of the Linux file system, 3.1.1 Files". tldp.org. Retrieved 13 August 2025. A simple description of the UNIX system, also applicable to Linux, is this: "On a UNIX system, everything is a file; if something is not a file, it is a process."
  39. ^ chmod(1) – Linux General Commands Manual
  40. ^ "Introduction to Linux, Ch. 3 About files and the filesystem, 3.4 File security, 3.4.2.3. The file mask". tldp.org. Retrieved 13 August 2025.
  41. ^ "Introduction to Linux, Ch. 3 About files and the filesystem, 3.2 Orientation in the filesystem, 3.2.2 Absolute and relative paths". tldp.org. Retrieved 13 August 2025.
  42. ^ a b "Introduction to Linux, Ch. 3 About files and the filesystem, 3.2 Orientation in the filesystem, 3.2.1 The path". tldp.org. Retrieved 13 August 2025. The PATH environment variable ... lists those directories in the system where executable files can be found, and thus saves the user a lot of typing and memorizing locations of commands.
  43. ^ "peripheral device". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  44. ^ Kernighan, Brian W.; Pike, Rob (1984). The UNIX Programming Environment. Englewood Cliffs: Prentice-Hall. ISBN 0-13-937699-2.
  45. ^ "C". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  46. ^ "Modular data structures in C". dartmouth.edu. Dartmouth University. Retrieved 15 August 2025.
  47. ^ "computer programming language". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  48. ^ "Perl". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  49. ^ "Python". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  50. ^ a b Stevens, Al (1 July 2021). "I Almost Get a Linux Editor and Compiler". drdobbs.com. Archived from the original on 2 March 2021. Retrieved 8 August 2025. But virtually all the configure and install scripts that come with open-source programs are written for bash, and if you want to understand those scripts, you have to know bash.
  51. ^ "Bash reference manual, 6.2 Bash startup files". gnu.org. GNU Project. Retrieved 12 August 2025.
  52. ^ "Institute of Electrical and Electronics Engineers". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  53. ^ a b Cooper, Mendel. "Advanced Bash Scripting Guide: 36.9: Portability Issues". tldp.org. ibiblio.org. Archived from the original on 27 January 2012. Retrieved 8 August 2025.
  54. ^ "6.11 Bash and POSIX". case.edu. Case Western Reserve University. Retrieved 8 August 2025.
  55. ^ Brousse, Nicolas (2 October 2020). "How To Format Date And Time In Linux, MacOS, And Bash?". shell-tips.com. Archived from the original on 3 June 2020. Retrieved 8 August 2025.
  56. ^ a b "Debian Policy Manual v4.5.0.2: 10 - Files". debian.org. Archived from the original on 12 May 2020. Retrieved 11 May 2020.
  57. ^ a b checkbashisms(1) – Linux General Commands Manual
  58. ^ a b shellcheck(1) – Linux General Commands Manual
  59. ^ "Autoconf: 11: Portable Shell". gnu.org. GNU Project. Archived from the original on 2 March 2021. Retrieved 20 January 2020.
  60. ^ "Bash Reference Manual, B.1 Implementation Differences from the SVR4.2 Shell". gnu.org. GNU Project. Retrieved 13 August 2025. In a questionable attempt at security, the SVR4.2 shell, when invoked without the -p option, will alter its real and effective UID and GID....
  61. ^ "Bash Reference Manual, 4.3.1 The Set Builtin". gnu.org. GNU Project. Retrieved 13 August 2025. In this mode, the $BASH_ENV and $ENV files are not processed, shell functions are not inherited from the environment, and the SHELLOPTS, BASHOPTS, CDPATH and GLOBIGNORE variables, if they appear in the environment, are ignored....
  62. ^ Free Software Foundation. "Bash Reference Manual, 6.12 Shell Compatability Mode". gnu.org. GNU Project. Retrieved 5 August 2025.
  63. ^ See set -v in the documentation.
  64. ^ "Bash Reference Manual: 7.1 Job Control Basics". gnu.org. GNU Project. Archived from the original on 15 March 2018. Retrieved 8 August 2025.
  65. ^ Michael, Randal (2008). Mastering Unix Shell Scripting, 2e. Wiley Publishing, Inc., Indianapolis, Indiana. p. 25. ISBN 978-0-470-18301-4. Retrieved 16 August 2025. 19 :: SIGSTOP :: Stop, usually Ctrl + z
  66. ^ Newham, Cameron (29 March 2005). Learning the bash Shell: Unix Shell Programming. O'Reilly Media, Inc. p. 205. Retrieved 16 August 2025. Use KILL only as a last resort!
  67. ^ a b "Bash(1)". case.edu. Case Western Reserve University. Retrieved 8 August 2025.
  68. ^ "Sending and Trapping Signals". wooledge.org. Retrieved 5 August 2025.
  69. ^ Michael, Randal (2008). Mastering Unix Shell Scripting, 2e. Wiley Publishing, Inc., Indianapolis, Indiana. p. 20. ISBN 978-0-470-18301-4. Retrieved 16 August 2025. In Korn shell the echo command recognizes these command options by default. In Bash shell we must add the -e switch to the echo command, echo -e "\n" for one new line.
  70. ^ "Bash Reference Manual: 3.7.3: Command Execution Environment". gnu.org. GNU Project. Retrieved 8 August 2025.
  71. ^ "Bash Reference Manual, 6.6 Aliases". gnu.org. GNU Project. Retrieved 14 August 2025. Aliases allow a string to be substituted for a word that is in a position in the input where it can be the first word of a simple command. Aliases have names and corresponding values that are set and unset using the alias and unalias builtin commands.
  72. ^ "alias - define or display aliases". opengroup.org. The Open Group. Retrieved 14 August 2025.
  73. ^ Cooper, Mendel. "Advanced Bash Scripting Guide, Ch 25. Aliases". tldp.org. Retrieved 14 August 2025.
  74. ^ "Commands and Arguments: Aliases". wooledge.org. Retrieved 14 August 2025.
  75. ^ "Compound Commands: Aliases". wooledge.org. Retrieved 14 August 2025.
  76. ^ "Bash Reference Manual, 3.3 Shell Functions". gnu.org. GNU Project. Retrieved 14 August 2025. Shell functions are a way to group commands for later execution using a single name for the group. They are executed just like a "regular" simple command. When the name of a shell function is used as a simple command name, the shell executes the list of commands associated with that function name. Shell functions are executed in the current shell context; there is no new process created to interpret them.
  77. ^ "2.9.5 Function Definition Command". opengroup.org. The Open Group. Retrieved 14 August 2025.
  78. ^ Cooper, Mendel. "Advanced Bash Scripting Guide, Ch 24. Functions". tldp.org. Retrieved 14 August 2025.
  79. ^ "Compound Commands, 4. Functions". wooledge.org. Retrieved 14 August 2025.
  80. ^ "Bash Programming, 2. Basic Concepts, 7. Functions". wooledge.org. Retrieved 14 August 2025.
  81. ^ "Bash Weaknesses, 13. Functions". wooledge.org. Retrieved 14 August 2025.
  82. ^ "Bash Reference Manual: 4.1: Bourne Shell Builtins". gnu.org. GNU Project. Retrieved 8 August 2025.
  83. ^ "Bash Reference Manual: 4.3.1: The Set Builtin". gnu.org. GNU Project. Retrieved 8 August 2025.
  84. ^ "bug-bash archives, Re: Document that set -v inside case statements is special". bug-bash (Mailing list). GNU Project. 20 April 2021. Retrieved 8 August 2025.
  85. ^ a b "Bash changes". bash-hackers.org. Archived from the original on 23 September 2019. Retrieved 8 August 2025.
  86. ^ "Glossary of Coding Terms for Beginners: iteration". syracuse.edu. Syracuse University. Retrieved 15 August 2025.
  87. ^ "compound - noun (1)". merriam-webster.com. Merriam-Webster's Collegiate Dictionary. Retrieved 15 August 2025.
  88. ^ Stephen R Bourne (12 June 2015). "Early days of Unix and design of sh" (PDF). bsdcan.org. BSDcan 2015: The Technical BSD Conference. Retrieved 8 August 2025.
  89. ^ "Advanced Bash Scripting Guide: 37.2: Bash, version 3". tldp.org. Section 37.2 (Bash, version 3). Archived from the original on 5 May 2017. Retrieved 5 March 2017.
  90. ^ "GNU Bash Manual: 3.2.5.2: Conditional Constructs". gnu.org. GNU Project. Retrieved 8 August 2025.
  91. ^ "Bash Reference Manual, 3.2.6 Coprocesses". gnu.org. GNU Project. Retrieved 15 August 2025.
  92. ^ Mallett, Andrew (24 December 2015). Mastering Linux Shell Scripting. Packt Publishing, Ltd. p. 56. Retrieved 16 August 2025. Learning this now can save us a lot of pain and heartache later, especially....
  93. ^ "Unicode". britannica.com. Retrieved 15 August 2025. Unicode, international character-encoding system designed to support the electronic interchange, processing, and display of the written texts of the diverse languages of the modern and classical world.
  94. ^ "Bash Reference Manual: 5.3.1 Brace Expansion". gnu.org. GNU Project. Archived from the original on 15 March 2018. Retrieved 8 August 2025.
  95. ^ "Advanced Bash Scripting Guide: 37.3: Bash, version 4". tldp.org. Archived from the original on 1 July 2018. Retrieved 8 August 2025.
  96. ^ "Update bash to version 4.0 on OSX". apple.stackexchange.com. Archived from the original on 25 June 2018. Retrieved 8 August 2025.
  97. ^ "Bash Reference Manual: 6.7: Arrays". gnu.org. GNU Project. Archived from the original on 11 July 2018. Retrieved 8 August 2025.
  98. ^ "Bash Reference Manual, 3.1.2.5 Locale-Specific Translation". gnu.org. Free Software Foundation. Retrieved 16 August 2025. Prefixing a double-quoted string with a dollar sign $, such as $"hello, world", causes the string to be translated according to the current locale. The gettext infrastructure performs the lookup and translation, using the $LC_MESSAGES, $TEXTDOMAINDIR, and $TEXTDOMAIN shell variables.
  99. ^ "The Bash Parser". wooledge.org. Retrieved 15 August 2025.
  100. ^ Ramey, Chet. "The Architecture of Open Source Applications (Volume 1): The Bourne-Again Shell". aosabook.org. Retrieved 15 August 2025.
  101. ^ "Bash Reference Manual: 9.2: Bash History Builtins". gnu.org. GNU Project. Archived from the original on 15 September 2019. Retrieved 8 August 2025.
  102. ^ "Bash Reference Manual: 8.6: Programmable Completion". gnu.org. GNU Project. Retrieved 8 August 2025.
  103. ^ "Bash Reference Manual: 8.6 Programmable completion". case.edu. Case Western Reserve University. Retrieved 8 August 2025.
  104. ^ "Index of /gnu/bash". swin.edu.au. Swinburne University of Technology. Archived from the original on 8 March 2020. Retrieved 8 August 2025.
  105. ^ a b "Advanced Bash Scripting Guide: Appendix J: An Introduction to Programmable Completion". tldp.org. Retrieved 21 January 2022.
  106. ^ "Bash Reference Manual, 6.10 The Restricted Shell". gnu.org. GNU Project. Retrieved 13 August 2025. Modern systems provide more secure ways to implement a restricted environment, such as jails, zones, or containers.
  107. ^ a b "Bash". gnu.org. GNU Project. Retrieved 8 August 2025.
  108. ^ a b Free Software Foundation. "GNU Bash manual". gnu.org. GNU Project. Retrieved 8 August 2025.
  109. ^ "Bash Reference Manual". case.edu. Case Western Reserve University. Retrieved 8 August 2025.
  110. ^ "git: index : bash.git". gnu.org. GNU Project. Retrieved 8 August 2025.
  111. ^ "GNU Coreutils manual v.9.7, 15.2 printf: Format and print data". gnu.org. GNU Project. Retrieved 11 August 2025.
  112. ^ "GNU Bash Manual: 1.1: What is Bash?". gnu.org. GNU Project. Retrieved 8 August 2025.
  113. ^ Open Group. "POSIX 2024". gnu.org. Retrieved 30 July 2025.
  114. ^ "The Open Group Base Specifications Issue 7, 2018 edition". opengroup.org.
  115. ^ a b "The GNU Bourne-Again Shell, Top Page". case.edu. Case Western Reserve University. Retrieved 8 August 2025.
  116. ^ "Frequently Asked Questions". case.edu. Case Western Reserve University. Retrieved 8 August 2025.
  117. ^ "CVE-2024-2448: Authenticated Command Injection In Progress Kemp LoadMaster". rhinosecuritylabs.com. Rhino Security Labs, Inc. 23 April 2024. Retrieved 17 August 2025.
  118. ^ "CGI-BIN Specific Vulnerabilities". ucdavis.edu. University of California, Davis. January 1999. Retrieved 17 August 2025.
  119. ^ "CGI Security". BITS: computing and communications news. Los Alamos National Laboratory. March 1996. Archived from the original on 16 April 2000. Retrieved 17 August 2025.
  120. ^ "Eval command and security issues". wooledge.org. Archived from the original on 21 July 2025. Retrieved 17 August 2025.
  121. ^ "Input Validation Cheat Sheet". owasp.org. OWASP. Retrieved 17 August 2025.
  122. ^ "CWE-77: Improper Neutralization of Special Elements used in a Command ('Command Injection')". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  123. ^ "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  124. ^ "CWE-88: Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  125. ^ "CWE-184: Incomplete List of Disallowed Inputs". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  126. ^ "CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  127. ^ "CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  128. ^ "CWE-426: Untrusted Search Path". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  129. ^ "CWE-427: Uncontrolled Search Path Element". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  130. ^ "CWE-428: Unquoted Search Path or Element". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  131. ^ "CWE-61: UNIX Symbolic Link (Symlink) Following". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  132. ^ "CWE-535: Exposure of Information Through Shell Error Message". mitre.org. The MITRE Corporation. Retrieved 17 August 2025.
  133. ^ Juliana, Cino (10 June 2017). "Linux bash exit status and how to set exit status in bash - Techolac". techolac.com. Archived from the original on 21 June 2019. Retrieved 21 June 2019.
  134. ^ Leyden, John (24 September 2014). "Patch Bash NOW: 'Shell Shock' bug blasts OS X, Linux systems wide open". theregister.co.uk. The Register. Archived from the original on 16 October 2014. Retrieved 25 September 2014.
  135. ^ Perlroth, Nicole (25 September 2014). "Security Experts Expect 'Shellshock' Software Bug in Bash to Be Significant". The New York Times. Archived from the original on 5 April 2019. Retrieved 25 September 2014.
  136. ^ Seltzer, Larry (29 September 2014). "Shellshock makes Heartbleed look insignificant". zdnet.com. ZDNet. Archived from the original on 14 May 2016.
  137. ^ Sidhpurwala, Huzaifa (24 September 2014). "Bash specially-crafted environment variables code injection attack". redhat.com. Red Hat. Archived from the original on 25 September 2014. Retrieved 25 September 2014.
  138. ^ Chazelas, Stephane (4 October 2014). "oss-sec mailing list archives". seclists.org. Archived from the original on 6 October 2014. Retrieved 4 October 2014.
  139. ^ "Advanced Bash Scripting Guide: 2.3: Debugging Bash scripts". tldp.org. Archived from the original on 4 November 2018. Retrieved 8 August 2025.
  140. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. BASHPID. Retrieved 8 August 2025.
  141. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. BASH_ARGC. Retrieved 8 August 2025.
  142. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. BASH_ARGV. Retrieved 8 August 2025.
  143. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. BASH_LINENO. Retrieved 8 August 2025.
  144. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. BASH_REMATCH. Retrieved 8 August 2025.
  145. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. BASH_SOURCE. Retrieved 8 August 2025.
  146. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. BASH_XTRACEFD. Retrieved 8 August 2025.
  147. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. EPOCHREALTIME. Retrieved 8 August 2025.
  148. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. FUNCNAME. Retrieved 8 August 2025.
  149. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. LINENO. Retrieved 8 August 2025.
  150. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. PIPESTATUS. Retrieved 8 August 2025.
  151. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. PPID. Retrieved 8 August 2025.
  152. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. PS4. Retrieved 8 August 2025.
  153. ^
  154. ^ "Bash Reference Manual: 3.4.2: Special Parameters". gnu.org. GNU Project. Retrieved 8 August 2025.
  155. ^ "Shell Command Language". opengroup.org.
  156. ^ a b
  157. ^ a b c d e "Bash(1), Shell builtin commands". case.edu. Case Western Reserve University. Retrieved 8 August 2025.
  158. ^ a b "Bourne Shell Builtins (Bash Reference Manual)". gnu.org. GNU Project. Retrieved 8 August 2025.
  159. ^ "Bash Reference Manual: 5.2: Bash Variables". gnu.org. GNU Project. Retrieved 8 August 2025.
  160. ^ "Bash(1), Special parameters". case.edu. Case Western Reserve University. Retrieved 8 August 2025.
  161. ^ "The Shopt Builtin (Bash Reference Manual)". gnu.org. GNU Project. Retrieved 8 August 2025.
  162. ^
  163. ^ "Debian -- Details of package devscripts in sid". debian.org.
  164. ^ "Kcov - code coverage". github.io.
  165. ^ "BASH Debugger". sourceforge.net.
  166. ^ "[Bashdb-devel] Re: [PATCH] fix bashdb script handling of tmp directory". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  167. ^ "bashbug(1)". die.net. 21 October 2017. Archived from the original on 2 October 2018.
  168. ^ "bashbug(1) Mac OS X Manual Page". apple.com. 4 June 2014. Archived from the original on 6 October 2014.
  169. ^ "In Unix, what do some obscurely named commands stand for?". iu.edu. Indiana University. 5 February 2009. Archived from the original on 10 June 2010. Retrieved 8 August 2025.
  170. ^ Louis Pouzin (25 November 2000). "The Origin of the Shell". multicians.org.
  171. ^ "The SHELL, A Global Tool for Calling and Chaining Procedures in the System" (PDF). mit.edu.
  172. ^ "Multics". britannica.com. Encyclopædia Britannica. Retrieved 15 August 2025.
  173. ^ Cerf, Vint (16 October 1969). "ASCII Format for Network Interchange". ietf.org. UCLA, Network Working Group. Retrieved 8 August 2025.
  174. ^ a b Stallman, Richard; Ramey, Chet (10 February 1988). "GNU + BSD = ?". google.com. Newsgroupcomp.unix.questions. Usenet: 2362@mandrill.CWRU.Edu. Archived from the original on 28 December 2021. Retrieved 28 December 2021. For a year and a half, the GNU shell was "just about done". The author made repeated promises to deliver what he had done, and never kept them. Finally I could no longer believe he would ever deliver anything. So Foundation staff member Brian Fox is now implementing an imitation of the Bourne shell.
  175. ^ Stallman, Richard (3 October 2010). "About the GNU Project". gnu.org. GNU Project. Archived from the original on 24 April 2011. Retrieved 8 August 2025. Free Software Foundation employees have written and maintained a number of GNU software packages. Two notable ones are the C library and the shell. ... We funded development of these programs because the GNU Project was not just about tools or a development environment. Our goal was a complete operating system, and these programs were needed for that goal.
  176. ^ Fox, Brian; Tower Jr., Leonard H. (8 June 1989). "Bash is in beta release!". google.com. Newsgroupgnu.announce. Archived from the original on 4 May 2013. Retrieved 28 October 2010.
  177. ^ "Evolution of shells in Linux". ibm.com. IBM. 9 December 2011.
  178. ^ Torvalds, Linus (26 August 1991). "What would you like to see most in Minix?". google.com. Newsgroupcomp.os.minix. Retrieved 8 August 2025. To make things really clear - yes I can run gcc on it, and bash, and most of the gnu [bin/file]utilities
  179. ^ "January 1993 GNU's Bulletin". google.com. Newsgroupgnu.announce. 20 April 1993. Usenet: gnusenet930421bulletin@prep.ai.mit.edu. Archived from the original on 2 March 2021. Retrieved 28 October 2010.
  180. ^ Ramey, Chet (1 August 1994). "Bash – the GNU shell (Reflections and Lessons Learned)". linuxjournal.com. Linux Journal. Archived from the original on 5 December 2008. Retrieved 13 November 2008.
  181. ^ Ramey, Chet (31 October 2010), "Dates in your Computerworld interview", scribd.com, archived from the original on 20 July 2012, retrieved 31 October 2010
  182. ^
  183. ^ Bresnahan, Christine; Blum, Richard (April 2015). CompTIA Linux+ Powered by Linux Professional Institute Study Guide: Exam LX0-103 and Exam LX0-104 (3rd ed.). John Wiley & Sons, Inc. p. 5. ISBN 978-1-119-02122-3. Archived from the original on 2 March 2021. Retrieved 6 June 2016. In Linux, most users run bash because it is the most popular shell.
  184. ^ Danesh, Arman; Jang, Michael (February 2006). Mastering Linux. John Wiley & Sons, Inc. p. 363. ISBN 978-0-7821-5277-7. Archived from the original on 2 March 2021. Retrieved 6 June 2016. The Bourne Again Shell (bash) is the most common shell installed with Linux distributions.
  185. ^ a b "Debian Wiki: Shell". debian.org.
  186. ^ Ramey, Chet (14 September 2000). "Re: Line-Edit mode is lost if "set -o vi" is in any files sourced on login". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  187. ^ Ramey, Chet (9 April 2001). "Bash-2.05 available for FTP". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  188. ^ Essential Mac OS S Panther Server Administration, pg 189
  189. ^ Foster-Johnson, Eric; Welch, John C.; Anderson, Micah (April 2005). "Beginning Shell Scripting". google.com. John Wiley & Sons, Inc. p. 6. ISBN 978-0-7645-9791-6. Archived from the original on 2 March 2021. Retrieved 8 August 2025. Bash is by far the most popular shell and forms the default shell on Linux and Mac OSX systems.
  190. ^ "Bash-3.0 available for FTP". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  191. ^ "Bash-3.1 released". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  192. ^ "Bash-3.2 available for FTP". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  193. ^ "Bash-4.0 available for FTP". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  194. ^ "Bash-4.1 available for FTP". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  195. ^ "Bash-4.2 available for FTP". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  196. ^ "User Environment Feature Changes". oracle.com. Oracle Corporation. Archived from the original on 12 June 2018. Retrieved 8 August 2025.
  197. ^ "Bash-4.3 available for FTP". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  198. ^ "CVE-2014-6271". cve.org. Retrieved 8 August 2025. GNU Bash through 4.3 processes trailing strings after function definitions in the values of environment variables, which allows remote attackers to execute arbitrary code via a crafted environment, as demonstrated by vectors involving the ForceCommand feature in OpenSSH sshd, the mod_cgi and mod_cgid modules in the Apache HTTP Server, scripts executed by unspecified DHCP clients, and other situations in which setting the environment occurs across a privilege boundary from Bash execution, aka "ShellShock."
  199. ^ "CVE-2014-7169". cve.org. Retrieved 8 August 2025.
  200. ^ "Bash 3.0 Official Patch 1". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  201. ^ Briegel, Armin (5 June 2019). "Moving to zsh". scriptingosx.com. Retrieved 8 August 2025.
  202. ^ "Apple Support – Use zsh as the default shell on your Mac". apple.com. Archived from the original on 2 December 2019. Retrieved 8 August 2025.
  203. ^ Warren, Tom (4 June 2019). "Apple replaces bash with zsh as the default shell in macOS Catalina". theverge.com. The Verge. Archived from the original on 10 June 2019. Retrieved 8 August 2025. The bash binary bundled with macOS has been stuck on version 3.2 for a long time now. Bash v4 was released in 2009 and bash v5 in January 2019. The reason Apple has not switched to these newer versions is that they are licensed with GPL v3. Bash v3 is still GPL v2.
  204. ^ Hughes, Matthew (4 June 2019). "Why does macOS Catalina use Zsh instead of Bash? Licensing". The Next Web. Archived from the original on 31 December 2020. Retrieved 8 August 2025.
  205. ^ "Bash-5.0 release available". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  206. ^ "Bash-5.1 release available". bug-bash (Mailing list). GNU Project. Retrieved 8 August 2025.
  207. ^ "exec_com, ec". mit.edu. Massachusetts Institute of Technology. 23 March 1984. Retrieved 8 August 2025. Function: executes programs written in the exec_com language, used to pass command lines to the Multics command processor and pass input lines to commands reading input.
  208. ^ "shell.c", gnu.org, GNU Project, 29 August 1996, archived from the original on 28 September 2018, retrieved 8 August 2025
  209. ^ "Command-line shell". archlinux.org. 5 February 2025. Retrieved 8 August 2025.