encyclopegia.org

Bash (Unix shell)

Bash (short for "Bourne Again SHell") is an interactive command interpreter and command language developed for Unix-like operating systems. Supported by the Free Software Foundation and created in 1989 by Brian Fox for the GNU Project, it is designed as a completely free software alternative for the Bourne shell, , and other proprietary Unix shells. Having gained widespread adoption, Bash is commonly used as the default login shell for numerous Linux distributions. 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's 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, its successor tcsh, and the Korn Shell. It is available on nearly all modern operating systems, making it a versatile tool in various computing environments.

Bash (short for "Bourne Again SHell") is an interactive command interpreter and command language developed for Unix-like operating systems. Supported by the Free Software Foundation and created in 1989 by Brian Fox for the GNU Project, it is designed as a completely free software alternative for the Bourne shell, , and other proprietary Unix shells. Having gained widespread adoption, Bash is commonly used as the default login shell for numerous Linux distributions. 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's 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, its successor tcsh, and the Korn Shell. It is available on nearly all modern operating systems, making it a versatile tool in various computing environments. $ printf ' : \n' $'\n' : $ printf ' : \n' $'\t' : $ printf ' : \n' " " : $ printf ' : \n' $'\0' : <> Any series of characters is called a "string", or sometimes a "string literal". 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 filenames. In addition, all strings are case-sensitive. Bash, like many other programming languages, uses zero-based numbering. '!' '{' '}' case in esac for do done if then elif else fi ... Names may only contain the characters ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_ . In the following example of a full command string, metacharacters have a comma placed above them, , reserved words have a caret placed beneath them, , and other tokens have a backtick placed also beneath them, . $ #, , , ,, , ,, , $ if echo foo; then bar=abc; fi $ # ^^ ```` ``` ^^^^ ``````` ^^ $ echo foo; ( echo foo ) foo foo For this simple case, the preceding two commands are equivalent, however, use of subshells can have certain unexpected side effects. There are numerous different forms of syntax which can cause the initialization of a subshell. A non-comprehensive list of operators that cause the initialization of a subshell is as follows: Subshells syntax, () , for example, would initialize a subshell: $ ( program arga argb ) Piping syntax, A | B , would initialize multiple subshells, one for each separate command in the pipeline: $ program1 abc def | program2 -abc A variable is assigned to using the syntax name = value . To use a variable, the syntax $ name is used, or ${ name } , which expands to the value assigned to the variable. The latter syntax must be used for certain names to prevent unwanted side effects. For example, $10 will be parsed as ${1}0 , so using ${10} means it will be parsed as intended. Positional parameters, usually passed to a bash script, are denoted by the variables numbered starting from $1. Special parameters are signified by punctuation characters. For example, expands to a list of the first through last positional parameters, individually requoted, separated by spaces. Environment variables are signified by all capital letters. Environment variables include UNIX variables like , and Bourne shell variables such as . Scripting variables are signified by all lower case letters or CamelCase. This is only convention; any variable can be passed to the command to be made into an environment variable. An array is assigned using the syntax name =( value1 value2 ... ) . It is expanded using or or , depending on the use case. Each kind of parameter is distinguished by a specific naming convention. Since Bash 4.0, Bash also supports associative arrays. In this article, examples of variables from this section include , and . $ foo=aa bar=bb quux=cc zork=dd; set -o xtrace $ : "${foo}"; : "${bar}" + : aa + : bb $ : "${quux}" \ > : "${zork}" + : cc : dd The first word of a command line is known as the "command position". Under UNIX coventionality, the first word of the command line is always some kind of command, and the rest of the words in the command line 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 variable and the current working directory. $ # [COMMAND POSITION] [OPTION] [ARGUMENTS] $ # ,--^ ,------------^ ,----^ $ declare -p USER BASH_VERSION declare -x USER="liveuser" declare -- BASH_VERSION="5.2.37(1)-release" $ sudo --login --user root [sudo] password for liveuser: umask 077 echo bob > /home/liveuser/names.txt exit $ grep -e bob ./names.txt grep: ./names.txt: Permission denied $ cat ./example.sh ! /bin/env bash echo foo 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 . The "execute" bit can be enabled on a shell script with the utility : $ 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 $ 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 command or, by default in Bash, pressing . $ declare -p POSIXLY_CORRECT SHLVL bash: declare: POSIXLY_CORRECT: not found declare -x SHLVL="1" $ bash -o posix $ declare -p POSIXLY_CORRECT SHLVL declare -- POSIXLY_CORRECT="y" declare -x SHLVL="2" The full list of features available in Bash which are not specified by POSIX is considerable. 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 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 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 prints the list of Bourne special builtins, which are POSIX $ enable -s | wc --lines 16 $ enable | wc --lines 61 The builtin itself is not POSIX In Bash, in non-POSIX mode, the and builtins are synonymous The (i.e., 'dot') builtin is POSIX, however The builtin is not POSIX The and shell variables are not POSIX 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. Most (such as ) are standalone programs in the , , or directories (in Linux, typically provided by GNU coreutils or BusyBox) rather than Bash builtins. 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. Code that is valid syntax in Bash but not specified by POSIX is called a "bashism". The program can be used to make sure that a script can be executed in Debian Linux without any portability errors. Vidar Holen's 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. 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), while a script intending to support pre-POSIX Bourne shells, like autoconf's , are even more limited in the features they can use. $ bash -x $ echo $(( 2 + 2 )) + echo 4 4 $ set -- 1 2 3 + set -- 1 2 3 $ printf ' \n' "$@" + printf ' \n' 1 2 3 The shell setting is specified by POSIX. See also . $ # Define foo $ foo=bar # An inline hash comment occurs on the same line as a command $ set -x $ # A regular comment (no output) $ : "${foo}" + : bar $ true; echo $? # Exit code means "true" 0 $ false; echo $?; echo # Exit code means "false" 1 $ $ bash -c 'exit 99'; printf 'exit-code: %d\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 $ command1; command2 $ command3 In this example, when is finished, is executed, and when has completed, will execute. A background execution of 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 and , they must be executed in the Bash shell in the following way: $ command1 & command2 In this case is executed in the background, symbol, returning immediate control to the shell that executes in the foreground. A process can be stopped and control returned to bash by typing while the process is running in the foreground. A list of all processes, both in the background and stopped, can be achieved by running : $ jobs [1]- Running command1 & In the output, the number in brackets refers to the job id. The plus sign signifies the default process for and . 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 command brings a process to the foreground, while sets a stopped process running in the background. and 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 . The 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 . $ 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 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 by shutting down and exiting cleanly. (TERM and are the same, the SIG- prefix to all signal names can be omitted.) The sequence in Bash sends a , interrupt signal, to the foreground process. The sequence sends the , stop signal. When a process receives a , the process terminates immediately and messily. It is recommended to use only as a last resort. The 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 respond 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 : for example, the command. By default Bash shell scripts receive and respond to any and all IPC signals sent to them, however, Bash scripts can utilize the builtin to catch and handle signals. $ 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: , , and . These signals can be useful in debugging, and can only be sent and handled by shell builtins. See also . $ foo=abc bar=123 $ printf ' \n' "${foo}" "${bar}" For digits only, the format specifier is . $ printf ' \n' "${foo}" "${bar}" bash: printf: abc: invalid number 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 ' ' "${foo}" "${bar}" $ Another very consistent method is to use . The output of can be reused as input. However, not all variables and parameters can be printed using , for example, the values of the Special Parameters. The Special Parameter hash, , reports how many Positional Parameters are currently defined. $ declare -p foo bar declare -- foo="abc" declare -- bar="123" $ set -- $ declare -p "$#" bash: declare: 0: not found For a full string of input at an interactive shell... $ declare -p # ...the hash 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 . This command would, according to , "display the values and attributes of each NAME ," i.e., each variable, and, "if no NAME s are given, display the values and attributes and values of all variables," which can be over 100 lines of output. On the other hand, cannot display variables' attributes. See also . $ readonly fo $ declare -p foo declare -r foo="abc" $ printf ' ' "${foo}" $ [ -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 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 or file to read the — which provides the environment variables that Bash shell windows spawned from the window manager need, such as xterm or Gnome Terminal. $ # 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 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. $ cd "$SOMEWHERE" && ./do_something || echo "An error occurred" >&2 Where is only executed if the (change directory) command was "successful" (returned an exit status of zero) and the command would only be executed if either the or the command return an "error" (non-zero exit status). Regexp matching is limited to strings on the right side of the =~ operator in the extended test construct. ${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. $ 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. 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 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 $ cat ex.sh ! /bin/env bash bar="foo is not defined" echo "${foo:?$bar}" echo this message does not print $ chmod 0700 ./ex.sh $ ./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 builtin. $ bash -o posix $ set -- "a" " b" " > c " $ printf ',%s,\n' "$@" | sed 's/.*/|&|/ |,a,| |, b,| |, | | c ,| Note that in Bash, the number of spaces before the newline is made clear. $ 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 ! ls -l /dev | grep sdz then echo Error, line "${LINENO}" fi $ chmod 0700 ./error.sh $ ./error.sh Error, line 4 Using xtrace. If errexit had been enabled, then would not have been executed. $ cat ./test.sh ! /bin/env bash echo foo false echo quux $ chmod 0700 ./test.sh $ bash -o xtrace -o errexit ./test.sh + echo foo foo + false $ bash -o xtrace ./test.sh + echo foo foo + false + echo quux quux Note: 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

References

No reference rows published for this article.

Cite this article

MLA

"Bash (Unix shell)." encyclopegia.org, 2026, https://encyclopegia.org/wiki/bash-unix-shell. Accessed 25 November 2026.

Chicago

"Bash (Unix shell)." encyclopegia.org. Accessed November 25, 2026. https://encyclopegia.org/wiki/bash-unix-shell.

APA

encyclopegia.org. (2026). Bash (Unix shell). Retrieved November 25, 2026, from https://encyclopegia.org/wiki/bash-unix-shell

Accessed November 25, 2026 · CC BY-SA 4.0 · citation page · JSON

Related articles

Shell Haven

stub · references available

Ghost in the Shell

stub · references available

Northern & Shell

stub · references available

Shell Rock Township

stub · references available

Unix file permissions

stub · references available

Baby Bash

stub · references available

Bourne shell

stub · references available

shell-shaped noodle

stub · references available
CC BY-SA 4.0 · share-alike · https://en.wikipedia.org/w/index.php?oldid=1378502367 · 0.5 · snapshot enwiki-001378502367

Cite · JSON · Search

Related services and records

Services

  • Estate — measured countries, lanes and facts
  • Intel — live corroborated events
  • Legal — statutes, cases and citations
  • Encyclopedia — articles with inline sources
  • Space — launches, satellites and orbits
  • Search — federated search and reports
  • Pass — passport account and SSO
  • Corpora — read-only corpus origins
  • e01 — self-hosted corpora and tools

Text and metadata only; each target carries its own sources. Missing data is published as no-data, never estimated.