Advanced Bash-Scripting Guide(一)
Chapter 3. Special Characters
command comment
[#] Comments. Lines beginning with a # (with the exception of #!) are comments and will not be executed.
echo "The # here does not begin a comment."
echo 'The # here does not begin a comment.'
echo The \# here does not begin a comment.
echo The # here begins a comment.
echo ${PATH#*:} # Parameter substitution, not a comment.
echo $(( 2#101011 )) # Base conversion, not a comment.
# Thanks, S.C.
[;] Command separator [semicolon]. Permits putting two or more commands on the same line.
[;;] Terminator in a case option [double semicolon].
[;;&, ;&] Terminators in a case option (version 4+ of Bash).
[.] 1)"dot" command [period]. Equivalent to source (see Example 15-22). This is a bash builtin.
2)"dot", as a component of a filename. When working with filenames, a leading dot is the prefix of a
"hidden" file, a file that an ls will not normally show.
3)When considering directory names, a single dot represents the current working directory, and two dots denote the parent directory.
4) The dot often appears as the destination (directory) of a file movement command, in this context meaning current directory.
[.] "dot" character match. When matching characters, as part of a regular expression, a "dot" matches a single character.
["] partial quoting [double quote]. "STRING" preserves (from interpretation) most of the special characters within STRING. See Chapter 5.
['] full quoting [single quote]. 'STRING' preserves all special characters within STRING. This is a stronger form of quoting than "STRING". See Chapter 5.
[,] comma operator. The comma operator [16] links together a series of arithmetic operations. All are evaluated, but only the last one is returned.
[,, ,] Lowercase conversion in parameter substitution (added in version 4 of Bash).
[\] escape [backslash]. A quoting mechanism for single characters. \X escapes the character X. This has the effect of "quoting" X, equivalent to 'X'. The \ may be used to quote " and ', so they are expressed literally. See Chapter 5 for an in-depth explanation of escaped characters.
[/] Filename path separator [forward slash]. Separates the components of a filename (as in /home/bozo/projects/Makefile). This is also the division arithmetic operator.
[`] command substitution. The `command` construct makes available the output of command for assignment to a variable. This is also known as backquotes or backticks.
[:] 1)null command [colon]. This is the shell equivalent of a "NOP" (no op, a do-nothing operation). It may be considered a synonym for the shell builtin true. The ":" command is itself a Bash builtin, and its exit status is true (0).
:
echo $? # 0
2)Endless loop:
while :
do
operation-1
operation-2
...
operation-n
done
# Same as:
# while true
# do
# ...
# done
4)Placeholder in if/then test:
if condition
then : # Do nothing and branch ahead
else # Or else ...
take-some-action
fi
5)Provide a placeholder where a binary operation is expected, see Example 8-2 and default parameters.
Or Provide a placeholder where a command is expected in a here document. See Example 19-10.
: ${username=`whoami`}
# ${username=`whoami`} Gives an error without the leading :
# unless "username" is a command or builtin...
: ${1?"Usage: $0 ARGUMENT"} # From "usage-message.sh example script.
6)Evaluate string of variables using parameter substitution (as in Example 10-7).
: ${HOSTNAME?} ${USER?} ${MAIL?}
# Prints error message
#+ if one or more of essential environmental variables not set.
7)In combination with the > redirection operator, truncates a file to zero length, without changing its permissions.
If the file did not previously exist, creates it.
: > data.xxx # File "data.xxx" now empty.
# Same effect as cat /dev/null >data.xxx
# However, this does not fork a new process, since ":" is a builtin.
8)In combination with the >> redirection operator, has no effect on a pre-existing target file (: >> target_file).
If the file did not previously exist, creates it.(This applies to regular files, not pipes, symlinks, and certain special files.)
9)The ":" serves as a field separator, in /etc/passwd, and in the $PATH variable.
bash$ echo $PATH
/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/sbin:/usr/sbin:/usr/games
[!] 1)reverse (or negate) the sense of a test or exit status [bang]. The ! operator inverts the exit status of
the command to which it is applied (see Example 6-2). It also inverts the meaning of a test operator.
This can, for example, change the sense of equal ( = ) to not-equal ( != ). The ! operator is a Bash keyword.
2)In yet another context, from the command line, the ! invokes the Bash history mechanism (see Appendix K).
Note that within a script, the history mechanism is disabled.
[*] 1)wild card [asterisk]. The * character serves as a "wild card" for filename expansion in globbing. By
itself, it matches every filename in a given directory.
2)The * also represents any number (or zero) characters in a regular expression.
arithmetic operator. In the context of arithmetic operations, the * denotes multiplication.
[?] 1)test operator. Within certain expressions, the ? indicates a test for a condition.
2)In a double-parentheses construct, the ? can serve as an element of a C-style trinary operator.
condition?result-if-true:result-if-false
(( var0 = var1<98?9:21 ))
# ^ ^
# if [ "$var1" -lt 98 ]
# then
# var0=9
# else
# var0=21
# fi
3)In a parameter substitution expression, the ? tests whether a variable has been set.
4)wild card. The ? character serves as a single-character "wild card" for filename expansion in
globbing, as well as representing one character in an extended regular expression.
[$] 1)Variable substitution (contents of a variable).
A $ prefixing a variable name indicates the value the variable holds.
2)end-of-line. In a regular expression, a "$" addresses the end of a line of text
[${}] Parameter substitution.
[$' ... '] Quoted string expansion. This construct expands single or multiple escaped octal or hex values into ASCII [17] or Unicode characters.
[$*, $@] positional parameters.
# If $IFS set, but empty,
#+ then "$*" and "$@" do not echo positional params as expected.
mecho () # Echo positional parameters.
{
echo "$1,$2,$3";
}
IFS="" # Set, but empty.
set a b c # Positional parameters.
mecho "$*" # abc,,
# ^^
mecho $* # a,b,c
mecho $@ # a,b,c
mecho "$@" # a,b,c
# The behavior of $* and $@ when $IFS is empty depends
#+ on which Bash or sh version being run.
# It is therefore inadvisable to depend on this "feature" in a script.
[$?] exit status variable. The $? variable holds the exit status of a command, a function, or of the script itself.
[$_] Special variable set to final argument of previous command executed.
#!/bin/bash
echo $_ # /bin/bash
# Just called /bin/bash to run the script.
# Note that this will vary according to
#+ how the script is invoked.
du >/dev/null # So no output from command.
echo $_ # du
ls -al >/dev/null # So no output from command.
echo $_ # -al (last argument)
:
echo $_ # :
[$-] 保存了shell使用set命令时设置的shell属性
[$!] PID (process ID) of last job run in background
[$$] process ID variable. The $$ variable holds the process ID [18] of the script in which it appears.
[()] 1) command group. (a=hello; echo $a) A listing of commands within parentheses starts a subshell.
Variables inside parentheses, within the subshell, are not visible to the rest of the script.
The parent process, the script, cannot read variables created in the child process, the subshell.
a=123
( a=321; )
echo "a = $a" # a = 123
# "a" within parentheses acts like a local variable.
2)array initialization.
Array=(element1 element2 element3)
[{xxx,yyy,zzz,...}] Brace expansion.
echo \"{These,words,are,quoted}\" # " prefix and suffix
# "These" "words" "are" "quoted"
cat {file1,file2,file3} > combined_file
# Concatenates the files file1, file2, and file3 into combined_file.
cp file22.{txt,backup}
# Copies "file22.txt" to "file22.backup"
#A command may act upon a comma-separated list of file specs within braces. [19] Filename expansion (globbing) applies to the file specs between the braces.
#No spaces allowed within the braces unless the spaces are quoted or escaped.
echo {file1,file2}\ :{\ A," B",' C'}
#file1 : A file1 : B file1 : C file2 : A file2 : B file2 : C
[{a..z}] Extended Brace expansion.
echo {a..z} # a b c d e f g h i j k l m n o p q r s t u v w x y z
# Echoes characters between a and z.
echo {0..3} # 0 1 2 3
# Echoes characters between 0 and 3.
base64_charset=( {A..Z} {a..z} {0..9} + / = )
# Initializing an array, using extended brace expansion.
# From vladz's "base64.sh" example script.
[{}] 1) Block of code [curly brackets]. Also referred to as an inline group, this construct, in effect, creates
an anonymous function (a function without a name). However, unlike in a "standard" function, the
variables inside a code block remain visible to the remainder of the script.
bash$ { local a;
a=123; }
bash: local: can only be used in a function
-------------------------------------------
a=123
{ a=321; }
echo "a = $a" # a = 321 (value inside code block)
-----------------------------------------------------
2)placeholder for text. Used after xargs -i (replace strings option). The {} double curly brackets are a placeholder for output text.
ls . | xargs -i -t cp ./{} $1
# ^^ ^^
[{} \;] pathname. Mostly used in find constructs. This is not a shell builtin
The ";" ends the -exec option of a find command sequence. It needs to be escaped to
protect it from interpretation by the shell.
[ [ ] ] 1)test. Test expression between [ ]. Note that [ is part of the shell builtin test (and a synonym for it), not a link to the external command /usr/bin/test.
2)array element. In the context of an array, brackets set off the numbering of each element of that array.
Array[1]=slot_1
echo ${Array[1]}
3)range of characters. As part of a regular expression, brackets delineate a range of characters to match.
[ [[ ]] ] test. Test expression between [[ ]]. More flexible than the single-bracket [ ] test, this is a shell keyword.
[$[ ... ]] integer expansion. Evaluate integer expression between $[ ].
a=3
b=7
echo $[$a+$b] # 10
echo $[$a*$b] # 21
Note that this usage is deprecated, and has been replaced by the (( ... )) construct.
[(( ))] integer expansion. Expand and evaluate integer expression between (( )).
[> &> >& >> < <>] redirection.
scriptname >filename redirects the output of scriptname to file filename. Overwrite filename if it already exists.
command &>filename redirects both the stdout and the stderr of command to filename.
command >&2 redirects stdout of command to stderr.
scriptname >>filename appends the output of scriptname to file filename. If filename does not already exist, it is created.
[i]<>filename opens file filename for reading and writing, and assigns file descriptor i to it. If filename does not exist, it is created.
In a different context, the "<" and ">" characters act as string comparison operators.
In yet another context, the "<" and ">" characters act as integer comparison operators.
[<<] redirection used in a here document.
[<<<] redirection used in a here string.
[<, >] ASCII comparison.
veg1=carrots
veg2=tomatoes
if [[ "$veg1" < "$veg2" ]]
then
echo "Although $veg1 precede $veg2 in the dictionary,"
echo -n "this does not necessarily imply anything "
echo "about my culinary preferences."
else
echo "What kind of dictionary are you using, anyhow?"
fi
[\<, \>] word boundary in a regular expression.
bash$ grep '\<the\>' textfile
[|] pipe.
Passes the output (stdout of a previous command to the input (stdin) of the next one, or to the shell.
This is a method of chaining commands together.
The stdout of each process in a pipe must be read as the stdin of the next.
If this is not the case, the data stream will block, and the pipe will not behave as expected.
cat file1 file2 | ls -l | sort
# The output from "cat file1 file2" disappears.
A pipe runs as a child process, and therefore cannot alter script variables.
variable="initial_value"
echo "new_value" | read variable
echo "variable = $variable" # variable = initial_value
[>|] force redirection (even if the noclobber option is set). This will forcibly overwrite an existing file.
[||] OR logical operator. In a test construct, the || operator causes a return of 0 (success) if either of the linked test conditions is true.
[&] Run job in background. A command followed by an & will run in the background.
[&&] AND logical operator. In a test construct, the && operator causes a return of 0 (success) only if both the linked test conditions are true.
[-] option, prefix. Option flag for a command or filter. Prefix for an operator. Prefix for a default parameter in parameter substitution.
COMMAND -[Option1][Option2][...]
[--] The double-dash -- prefixes long (verbatim) options to commands.
sort --ignore-leading-blanks
[-] 1) previous working directory. A cd - command changes to the previous working directory. This uses the $OLDPWD environmental variable.
2)Minus. Minus sign in an arithmetic operation.
[=] 1)Equals. Assignment operator
2)In a different context, the "=" is a string comparison operator.
[+] 1)Plus. Addition arithmetic operator.
2)In a different context, the + is a Regular Expression operator.
3)Option. Option flag for a command or filter.
Certain commands and builtins use the + to enable certain options and the - to disable them.
In parameter substitution, the + prefixes an alternate value that a variable expands to.
[%] 1) modulo. Modulo (remainder of a division) arithmetic operation.
2)In a different context, the % is a pattern matching operator.
[~] home directory [tilde].
[~+] current working directory. This corresponds to the $PWD internal variable.
[~-] previous working directory. This corresponds to the $OLDPWD internal variable.
[=~] regular expression match. This operator was introduced with version 3 of Bash.
[^] beginning-of-line. In a regular expression, a "^" addresses the beginning of a line of text.
[^, ^^] Uppercase conversion in parameter substitution (added in version 4 of Bash).
Control Characters:change the behavior of the terminal or text display. A control character is a CONTROL + key
combination (pressed simultaneously). A control character may also be written in octal or
hexadecimal notation, following an escape.
Control characters are not normally useful inside a script.
[Ctl-A][^A] Moves cursor to beginning of line of text (on the command-line).
[Ctl-B][^B] Backspace (nondestructive).
[Ctl-C][^C] Break. Terminate a foreground job.
[Ctl-D][^D] Log out from a shell (similar to exit).
EOF (end-of-file). This also terminates input from stdin.
When typing text on the console or in an xterm window, Ctl-D erases the character under
the cursor. When there are no characters present, Ctl-D logs out of the session, as expected.
In an xterm window, this has the effect of closing the window.
[Ctl-E][^E] Moves cursor to end of line of text (on the command-line).
[Ctl-F][^F] Moves cursor forward one character position (on the command-line).
[Ctl-G][^G] BEL. On some old-time teletype terminals, this would actually ring a bell. In an xterm it might beep.
[Ctl-H][^H] Rubout (destructive backspace). Erases characters the cursor backs over while backspacing.
[Ctl-I][^I] Horizontal tab.
[Ctl-J][^J] Newline (line feed). In a script, may also be expressed in octal notation -- '\012' or in hexadecimal -- '\x0a'.
[Ctl-K][^K] Vertical tab.
When typing text on the console or in an xterm window, Ctl-K erases from the character
under the cursor to end of line. Within a script, Ctl-K may behave differently, as in Lee Lee
Maschmeyer's example, below.
[Ctl-L][^L] Formfeed (clear the terminal screen). In a terminal, this has the same effect as the clear
command. When sent to a printer, a Ctl-L causes an advance to end of the paper sheet.
[Ctl-M][^M] Carriage return.
[Ctl-N][^N] Erases a line of text recalled from history buffer [22] (on the command-line).
[Ctl-O][^O] Issues a newline (on the command-line).
[Ctl-P][^P] Recalls last command from history buffer (on the command-line).
[Ctl-Q][^Q] Resume (XON). This resumes stdin in a terminal.
[Ctl-R][^R] Backwards search for text in history buffer (on the command-line).
[Ctl-S][^S] Suspend (XOFF). This freezes stdin in a terminal. (Use Ctl-Q to restore input.)
[Ctl-T][^T] Reverses the position of the character the cursor is on with the previous character (on the command-line).
[Ctl-U][^U] Erase a line of input, from the cursor backward to beginning of line. In some settings, Ctl-U
erases the entire line of input, regardless of cursor position.
[Ctl-V][^V] When inputting text, Ctl-V permits inserting control characters. For example, the following
two are equivalent:
echo -e '\x0a'
echo <Ctl-V><Ctl-J>
Ctl-V is primarily useful from within a text editor.
[Ctl-W][^W] When typing text on the console or in an xterm window, Ctl-W erases from the character
under the cursor backwards to the first instance of whitespace. In some settings, Ctl-W
erases backwards to first non-alphanumeric character.
[Ctl-X][^X] In certain word processing programs, Cuts highlighted text and copies to clipboard.
[Ctl-Y][^Y] Pastes back text previously erased (with Ctl-U or Ctl-W).
[Ctl-Z][^Z] Pauses a foreground job.
Substitute operation in certain word processing applications.
EOF (end-of-file) character in the MSDOS filesystem.
Chapter 4. Introduction to Variables and Parameters
#-------------------------------------------------------------------------
# No space permitted on either side of = sign when initializing variables.
# What happens if there is a space?
# "VARIABLE =value"
# ^
#% Script tries to run "VARIABLE" command with one argument, "=value".
# "VARIABLE= value"
# ^
#% Script tries to run "value" command with
#+ the environmental variable "VARIABLE" set to "".
#-------------------------------------------------------------------------
hello="A B C D"
echo $hello # A B C D
echo "$hello" # A B C D
# As you see, echo $hello and echo "$hello" give different results.
# Why?
# =======================================
# Quoting a variable preserves whitespace.
# =======================================
# Escaping the whitespace also works.
mixed_bag=2\ ---\ Whatever
# ^ ^ Space after escape (\).
echo "$mixed_bag" # 2 --- Whatever
echo "uninitialized_variable = $uninitialized_variable"
# Uninitialized variable has null value (no value at all!).
uninitialized_variable= # Declaring, but not initializing it --
#+ same as setting it to a null value, as above.
echo "uninitialized_variable = $uninitialized_variable"
# It still has a null value.
An uninitialized variable has a "null" value -- no assigned value at all (not zero!).
if [ -z "$unassigned" ]
then
echo "\$unassigned is NULL."
fi # $unassigned is NULL.
Using a variable before assigning a value to it may cause problems. It is nevertheless
possible to perform arithmetic operations on an uninitialized variable.
echo "$uninitialized" # (blank line)
let "uninitialized += 5" # Add 5 to it.
echo "$uninitialized" # 5
# Conclusion:
# An uninitialized variable has no value,
#+ however it evaluates as 0 in an arithmetic operation.
# Now, getting a little bit fancier (command substitution).
a=`echo Hello!` # Assigns result of 'echo' command to 'a' ...
echo $a
# Note that including an exclamation mark (!) within a
#+ command substitution construct will not work from the command-line,
#+ since this triggers the Bash "history mechanism."
# Inside a script, however, the history functions are disabled.
Variable assignment using the $(...) mechanism (a newer method than backquotes). This is likewise a
form of command substitution.
# From /etc/rc.d/rc.local
R=$(cat /etc/redhat-release)
arch=$(uname -m)
Bash Variables Are Untyped: Bash permits arithmetic operations and comparisons on variables.
The determining factor is whether the value of a variable contains only digits.
a=2334 # Integer.
let "a += 1"
echo "a = $a " # a = 2335
echo # Integer, still.
b=${a/23/BB} # Substitute "BB" for "23".
# This transforms $b into a string.
echo "b = $b" # b = BB35
declare -i b # Declaring it an integer doesn't help.
echo "b = $b" # b = BB35
let "b += 1" # BB35 + 1
echo "b = $b" # b = 1
echo # Bash sets the "integer value" of a string to 0.
c=BB34
echo "c = $c" # c = BB34
d=${c/BB/23} # Substitute "23" for "BB".
# This makes $d an integer.
echo "d = $d" # d = 2334
let "d += 1" # 2334 + 1
echo "d = $d" # d = 2335
echo
# What about null variables?
e='' # ... Or e="" ... Or e=
echo "e = $e" # e =
let "e += 1" # Arithmetic operations allowed on a null variable?
echo "e = $e" # e = 1
echo # Null variable transformed into an integer.
# What about undeclared variables?
echo "f = $f" # f =
let "f += 1" # Arithmetic operations allowed?
echo "f = $f" # f = 1
echo # Undeclared variable transformed into an integer.
#
# However ...
let "f /= $undecl_var" # Divide by zero?
# let: f /= : syntax error: operand expected (error token is " ")
# Syntax error! Variable $undecl_var is not set to zero here!
#
# But still ...
let "f /= 0"
# let: f /= 0: division by 0 (error token is "0")
# Expected behavior.
# Bash (usually) sets the "integer value" of null to zero
#+ when performing an arithmetic operation.
# But, don't try this at home, folks!
# It's undocumented and probably non-portable behavior.
# Conclusion: Variables in Bash are untyped,
#+ with all attendant consequences.
Special Variable Types:
If a script sets environmental variables, they need to be "exported," that is, reported to the
environment local to the script. This is the function of the export command.
A script can export variables only to child processes, that is, only to commands or
processes which that particular script initiates. A script invoked from the
command-line cannot export variables back to the command-line environment.
Child processes cannot export variables back to the parent processes that spawned
them.
Positional parameters:
Arguments passed to the script from the command line [25] : $0, $1, $2, $3 . . .
$0 is the name of the script itself(`basename $0`), $1 is the first argument, $2 the second, $3 the third, and so forth.
After $9, the arguments must be enclosed in brackets, for example, ${10}, ${11}, ${12}.
The special variables $* and $@ denote all the positional parameters.$# is Number of args passed.
Bracket notation for positional parameters leads to a fairly simple way of referencing the last
argument passed to a script on the command-line: args=$#; lastarg=${!args} or lastarg=${!#}
If a script expects a command-line parameter but is invoked without one, this may
cause a null variable assignment, generally an undesirable result:
# A better method is parameter substitution:
# ${1:-$DefaultVal}
Chapter 5. Quoting
Use double quotes to prevent word splitting. An argument enclosed in double quotes presents itself as a
single word, even if it contains whitespace separators:
List="one two three"
for a in $List # Splits the variable in parts at whitespace.
do
echo "$a"
done
# one
# two
# three
echo "---"
for a in "$List" # Preserves whitespace in a single variable.
do # ^ ^
echo "$a"
done
# one two three
variable1="a variable containing five words"
COMMAND This is $variable1 # Executes COMMAND with 7 arguments:
# "This" "is" "a" "variable" "containing" "five" "words"
COMMAND "This is $variable1" # Executes COMMAND with 1 argument:
# "This is a variable containing five words"
variable2="" # Empty.
COMMAND $variable2 $variable2 $variable2
# Executes COMMAND with no arguments.
COMMAND "$variable2" "$variable2" "$variable2"
# Executes COMMAND with 3 empty arguments.
COMMAND "$variable2 $variable2 $variable2"
# Executes COMMAND with 1 argument (2 spaces).
Escaping:
used with echo and sed:
\n means newline
\r means return
\t means tab
\v means vertical tab
\b means backspace
\a means alert (beep or flash)
\0hh translates to the octal ASCII equivalent of 0nn, where hh is a string of digits
\xhhh translates to the hexa ASCII equivalent of xhhh, where hhh is a string of digits
The $' ... ' quoted string-expansion construct is a mechanism that uses escaped
octal or hex values to assign ASCII characters to variables, e.g., quote=$'\042'.
echo "This will print
as two lines."
# This will print
# as two lines.
echo "This will print \
as one line."
# This will print as one line.
echo "\v\v\v\v" # Prints \v\v\v\v literally.
# Use the -e option with 'echo' to print escaped characters.
echo "============="
echo "VERTICAL TABS"
echo -e "\v\v\v\v" # Prints 4 vertical tabs.
echo "=============="
echo "QUOTATION MARK"
echo -e "\042" # Prints " (quote, octal ASCII character 42).
echo "=============="
# The $'\X' construct makes the -e option unnecessary.
echo; echo "NEWLINE and (maybe) BEEP"
echo $'\n' # Newline.
echo $'\a' # Alert (beep).
# May only flash, not beep, depending on terminal.
Chapter 6. Exit and Exit Status
• Every command returns an exit status (sometimes referred to as a return status or exit code). A successful
command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an
error code. Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful
completion, though there are some exceptions.
• Likewise, functions within a script and the script itself return an exit status. The last command executed in the
function or script determines the exit status. Within a script, an exit nnn command may be used to deliver
an nnn exit status to the shell (nnn must be an integer in the 0 - 255 range).
• When a script ends with an exit that has no parameter, the exit status of the script is the exit status of the
last command executed in the script (previous to the exit).
EX1:#!/bin/bash
COMMAND_1
. . .
COMMAND_LAST
# Will exit with status of last command.
exit
• The equivalent of a bare exit is exit $? or even just omitting the exit.
EX2:#!/bin/bash
COMMAND_1
. . .
COMMAND_LAST
# Will exit with status of last command.
exit $?
EX3:#!/bin/bash
COMMAND1
. . .
COMMAND_LAST
• Example 6-2. Negating a condition using !
true # The "true" builtin.
echo "exit status of \"true\" = $?" # 0
! true
echo "exit status of \"! true\" = $?" # 1
# Note that the "!" needs a space between it and the command.
# !true leads to a "command not found" error
#
# The '!' operator prefixing a command invokes the Bash history mechanism.
true
!true
# No error this time, but no negation either.
# It just repeats the previous command (true).
# =========================================================== #
# Preceding a _pipe_ with ! inverts the exit status returned.
ls | bogus_command # bash: bogus_command: command not found
echo $? # 127
! ls | bogus_command # bash: bogus_command: command not found
echo $? # 0
# Note that the ! does not change the execution of the pipe.
# Only the exit status changes.
# =========================================================== #