There are many debugging methods for Linux shell scripts. Last time we discussed and tested some debugging options provided by the shell's built-in command set. In fact, the shell itself also provides some debugging options. Let's take bash as an example.
1 bash command line help information (bash --help)
purleEndurer @ csdn ~ $ bash --help
GNU bash, version 4.2.46(2)-release-(x86_64-redhat-linux-gnu)
Usage: bash [GNU long option] [option] ...
bash [GNU long option] [option] script-file ...
GNU long options:
--debug
--debugger
--dump-po-strings
--dump-strings
--help
--init-file
--login
--noediting
--noprofile
--norc
--posix
--protected
--rcfile
--rpm-requires
--restricted
--verbose
--version
Shell options:
-irsD or -c command or -O shopt_option (invocation only)
-abefhkmnptuvxBCHP or -o option
Type `bash -c "help set"' for more information about shell options.
Type `bash -c help' for more information about shell builtin commands.
purleEndurer @ csdn ~ $
As you can see, the bash command has many parameters and options.
Use the bash
command with specific options to change the behavior of the shell script when running it, helping us diagnose the problem.
2 Options provided by bash’s built-in command set (bash -c "help set" )
We can use the command bash -c "help set" to view the options provided by the bash built-in command set.
purpleEndurer @ cdu ~ $ bash -c "help set"
set: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
Set or unset values of shell options and positional parameters.
Change the value of shell attributes and positional parameters, or
display the names and values of shell variables.
Options:
-a Mark variables which are modified or created for export.
-b Notify of job termination immediately.
-e Exit immediately if a command exits with a non-zero status.
-f Disable file name generation (globbing).
-h Remember the location of commands as they are looked up.
-k All assignment arguments are placed in the environment for a
command, not just those that precede the command name.
-m Job control is enabled.
-n Read commands but do not execute them.
-o option-name
Set the variable corresponding to option-name:
allexport same as -a
braceexpand same as -B
emacs use an emacs-style line editing interface
errexit same as -e
errtrace same as -E
functrace same as -T
hashall same as -h
histexpand same as -H
history enable command history
ignoreeof the shell will not exit upon reading EOF
interactive-comments
allow comments to appear in interactive commands
keyword same as -k
monitor same as -m
noclobber same as -C
noexec same as -n
noglob same as -f
nolog currently accepted but ignored
notify same as -b
nounset same as -u
onecmd same as -t
physical same as -P
pipefail the return value of a pipeline is the status of
the last command to exit with a non-zero status,
or zero if no command exited with a non-zero status
posix change the behavior of bash where the default
operation differs from the Posix standard to
match the standard
privileged same as -p
verbose same as -v
vi use a vi-style line editing interface
xtrace same as -x
-p Turned on whenever the real and effective user ids do not match.
Disables processing of the $ENV file and importing of shell
functions. Turning this option off causes the effective uid and
gid to be set to the real uid and gid.
-t Exit after reading and executing one command.
-u Treat unset variables as an error when substituting.
-v Print shell input lines as they are read.
-x Print commands and their arguments as they are executed.
-B the shell will perform brace expansion
-C If set, disallow existing regular files to be overwritten
by redirection of output.
-E If set, the ERR trap is inherited by shell functions.
-H Enable ! style history substitution. This flag is on
by default when the shell is interactive.
-P If set, do not follow symbolic links when executing commands
such as cd which change the current directory.
-T If set, the DEBUG trap is inherited by shell functions.
-- Assign any remaining arguments to the positional parameters.
If there are no remaining arguments, the positional parameters
are unset.
- Assign any remaining arguments to the positional parameters.
The -x and -v options are turned off.
Using + rather than - causes these flags to be turned off. The
flags can also be used upon invocation of the shell. The current
set of flags may be found in $-. The remaining n ARGs are positional
parameters and are assigned, in order, to $1, $2, .. $n. If no
ARGs are given, all shell variables are printed.
Exit Status:
Returns success unless an invalid option is given.
purpleEndurer @ cdu ~ $
This information is related to
Linux shell programming study notes 28: Script debugging set commandhttps://blog.csdn.net/Purpleendurer/article/details/134506337?spm=1001.2014.3001.5501 The help information displayed by the set --help command in a> is consistent.
3 View bash built-in commands: bash -c help
purpleEndurer @ csdn ~ $ bash -c help
GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)
These shell commands are defined internally. Type `help' to see this list.
Type `help name' to find out more about the function `name'.
Use `info bash' to find out more about the shell in general.
Use `man -k' or `info' to find out more about commands not in this list.A star (*) next to a name means that the command is disabled.
job_spec [&] history [-c] [-d offset] [n] or hist>
(( expression )) if COMMANDS; then COMMANDS; [ elif C>
. filename [arguments] jobs [-lnprs] [jobspec ...] or jobs >
: kill [-s sigspec | -n signum | -sigs>
[ arg... ] let arg [arg ...]
[[ expression ]] local [option] name[=value] ...
alias [-p] [name[=value] ... ] logout [n]
bg [job_spec ...] mapfile [-n count] [-O origin] [-s c>
bind [-lpvsPVS] [-m keymap] [-f filen> popd [-n] [+N | -N]
break [n] printf [-v var] format [arguments]
builtin [shell-builtin [arg ...]] pushd [-n] [+N | -N | dir]
caller [expr] pwd [-LP]
case WORD in [PATTERN [| PATTERN]...)> read [-ers] [-a array] [-d delim] [->
cd [-L|[-P [-e]]] [dir] readarray [-n count] [-O origin] [-s>
command [-pVv] command [arg ...] readonly [-aAf] [name[=value] ...] o>
compgen [-abcdefgjksuv] [-o option] > return [n]
complete [-abcdefgjksuv] [-pr] [-DE] > select NAME [in WORDS ... ;] do COMM>
compopt [-o|+o option] [-DE] [name ..> set [-abefhkmnptuvxBCHP] [-o option->
continue [n] shift [n]
coproc [NAME] command [redirections] shopt [-pqsu] [-o] [optname ...]
declare [-aAfFgilrtux] [-p] [name[=va> source filename [arguments]
dirs [-clpv] [+N] [-N] suspend [-f]
disown [-h] [-ar] [jobspec ...] test [expr]
echo [-neE] [arg ...] time [-p] pipeline
enable [-a] [-dnps] [-f filename] [na> times
eval [arg ...] trap [-lp] [[arg] signal_spec ...]
exec [-cl] [-a name] [command [argume> true
exit [n] type [-afptP] name [name ...]
export [-fn] [name[=value] ...] or ex> typeset [-aAfFgilrtux] [-p] name[=va>
false ulimit [-SHacdefilmnpqrstuvx] [limit>
fc [-e ename] [-lnr] [first] [last] o> umask [-p] [-S] [mode]
fg [job_spec] unalias [-a] name [name ...]
for NAME [in WORDS ... ] ; do COMMAND> unset [-f] [-v] [name ...]
for (( exp1; exp2; exp3 )); do COMMAN> until COMMANDS; do COMMANDS; done
function name { COMMANDS ; } or name > variables - Names and meanings of so>
getopts optstring name [arg] wait [id]
hash [-lr] [-p pathname] [-dt] [name > while COMMANDS; do COMMANDS; done
help [-dms] [pattern ...] { COMMANDS ; }
purpleEndurer @ csdn ~ $
2 Description and demonstration of common debugging options in bash command line
Below we will explain and demonstrate some common debugging options in the bash command line one by one.
2.1 echo $-: Display currently started options
purpleEndurer @ cdu ~ $ echo $-
himBHpurpleEndurer @ cdu ~ $
You can see that the currently enabled options are h, i, m, B and H. These options are in the enabled state.
2.2 bash -n script file name specifier: do not execute the script, only check for errors
The function of the -n option is to read the commands in the script without executing them, and to check for syntax and other errors in the script.
2.2.1 Create test script file a.sh
We use the cp command to create. The file content is: echo 'Hello world
For testing purposes, we intentionally left out the matching single quotes at the end of the command line.
purleEndurer @ csdn ~ $ cp /dev/stdin a.sh
echo 'Hello world
2.2.2 View the contents of the test script file a.sh
purleEndurer @ csdn ~ $ cat a.sh
echo 'Hello world
2.2.3 Check script syntax errors
purleEndurer @ csdn ~ $ bash -n a.sh
a.sh: line 1: unexpected EOF while looking for matching `''
a.sh: line 2: syntax error: unexpected end of file
As you can see, bash detects two errors in a.sh.
The first error is on line 1: Unexpected EOF while looking for matching ''' , i.e. unpaired single quotes.
Error 2 appears on line 2: Syntax error: unexpected end of file.
2.3 bash -x script file specifier: first display the command and parameters (no comments), and then display the execution results
The -x option of the bash command has the same function as the -x option of the set command. They both turn on the echo mode. After executing the command, the command and its parameters will be displayed first, and then the result of the command execution will be displayed:
2.3.1 Create test script file a.sh
We use the cp command to create a.sh. The file content is as follows:
purleEndurer @ csdn ~ $ cp /dev/stdin a.sh
echo -n Enter your name please: # 提示用户输入名字
read n # 将用户输入的名字保存到变量n
echo Your name is $n # 显示用户输入的名字
The content after the # sign is a description of the command function.
2.3.2 Execute script file a.sh
purleEndurer @ csdn ~ $ bash -x a.sh
+ echo -n Enter your name please:
Enter your name please:+ read n
purpleEndurer
+ echo Your name is purpleEndurer
Your name is purpleEndurer
purleEndurer @ csdn ~ $
Bash will start with +, display the executed command, and then display the result of the command execution.
2.3.3 Use environment variables to customize the display format of PS4
In fact, when we use the -x option of bash to display commands and parameters, the + added in front is saved by the environment variable PS4.
purpleEndurer @csdn ~ $ set | grep PS4
PS4='+ '
Therefore, we can set the format of bash's -x option when displaying commands and parameters by modifying the value of the environment variable PS4.
For example: we start the displayed commands and parameters with >, and then introduce ${BASH_SOURCE} to display the script file name, ${LINENO} to display the line number, and ${FUNCNAME[0]} to display the name of the function being executed:
purpleEndurer @csdn ~ $ PS1="\e[35mpurpleEndurer\e[0m @csdn \w $ "
purpleEndurer @csdn ~ $ export PS4='>${BASH_SOURCE} [${LINENO}] ${FUNCNAME[0]}: '
purpleEndurer @csdn ~ $ bash -x a.sh
>a.sh [1] : echo -n Enter your name please:
Enter your name please:>a.sh [2] : read n
abc
>a.sh [3] : echo Your name is abc
Your name is abc
purpleEndurer @csdn ~ $
If you feel that there are too many characters and it is difficult to distinguish them, we can also add colors to them respectively:
purpleEndurer @csdn ~ $ export PS4='\e[35m>${BASH_SOURCE} \e[0m \e[33m [${LINENO}]\e[0m \e[31m ${FUNCNAME[0]}: \e[0m'
purpleEndurer @csdn ~ $ bash -x a.sh
>a.sh [1] : echo -n Enter your name please:
Enter your name please:>a.sh [2] : read n
abc
>a.sh [3] : echo Your name is abc
Your name is abc
Here we use
Linux shell programming study notes 4: Modify the command line prompt format (content and color)https://blog.csdn.net/Purpleendurer/article/details/133416124? The knowledge introduced in spm=1001.2014.3001.5501 causes the script file name to be displayed in purple, the line number to be displayed in yellow, and the name of the function being executed to be displayed in red.
2.4 bash -v script file specifier: while executing the script, print the executed script commands to the standard output (including comments)
purpleEndurer @csdn ~ $ export PS4='\e[35m>${BASH_SOURCE} \e[0m \e[33m [${LINENO}]\e[0m \e[31m ${FUNCNAME[0]}: \e[0m'
purpleEndurer @csdn ~ $ bash -v a.sh
echo -n Enter your name please: # Prompt the user to enter a name purpleEndurer @csdn ~ $ Your name is abc echo Your name is $n # display The name entered by the user abc
Enter your name please:read n # Save the name entered by the user to variable n
As you can see, the -v option shows that the executed command is not affected by the PS4 environment variable, and the comments in the script file will also be displayed.