Linux shell编程学习笔记29:shell自带的 脚本调试 选项

这篇具有很好参考价值的文章主要介绍了Linux shell编程学习笔记29:shell自带的 脚本调试 选项。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Linux shell脚本的调试方法比较多,上次我们探讨和测试了shell内建命令set所提供的一些调试选项,其实 shell 本身也提供了一些调试选项。我们以bash为例来看看。

1 bash 的命令行帮助信息(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 ~ $ 

Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

 可以看到,bash命令有很多参数和选项。

使用 bash 命令加上特定的选项可以在运行Shell脚本时改变其行为,帮助我们诊断问题。

2  bash 的内置命令set提供的选项(bash -c "help set" )

我们可以使用命令 bash -c "help set" 查看 bash 内置命令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 ~ $ 

这个信息与

Linux shell编程学习笔记28:脚本调试 set命令https://blog.csdn.net/Purpleendurer/article/details/134506337?spm=1001.2014.3001.5501中set --help命令显示的帮助信息是一致的。

3 查看bash内置的命令: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 bash 命令行常用调试选项说明和演示

下面我们就bash命令行中的一些常用的调试选项逐一进行说明和演示。

2.1 echo $-:显示当前已启动的选项

purpleEndurer @ cdu ~ $ echo $-
himBH

purpleEndurer @ cdu ~ $

Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

 可以看到,当前启用的选项有h、i、m、B和H这几个选项处于启动状态。

2.2 bash -n 脚本文件名说明符:不执行脚本,仅检查错误

-n 选项的功能是:读一遍脚本中的命令但不执行,用于检查脚本中的语法等错误。

2.2.1 创建测试脚本文件a.sh

我们用 cp 命令来创建 ,文件内容是: echo 'Hello world

为了测试,我们故意漏了命令行末尾配对的单引号。

purleEndurer @ csdn ~ $ cp /dev/stdin a.sh
echo 'Hello world   

 Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

2.2.2 查看测试脚本文件a.sh内容

purleEndurer @ csdn ~ $ cat a.sh
echo 'Hello world

Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

2.2.3 检查脚本语法错误

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

 Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

可以看到,bash检查出a.sh存在两个错误。

第1个错误出现在第1行:寻找匹配的 ''' 时出现意外的 EOF,即单引号未配对。

第2个错误出现在第2行:语法错误:意外的文件结尾。

2.3 bash -x 脚本文件说明符:先显示命令及参数(不显示注释),再显示执行结果

bash命令的-x选项与set 命令中的-x选项功能相同,都是打开echo模式,执行命令后,会先显示该命令及所带的参数,再显示命令执行的结果:

2.3.1 创建测试脚本文件a.sh

我们用 cp 命令来创建 a.sh,文件内容如下:

purleEndurer @ csdn ~ $ cp /dev/stdin a.sh
echo -n Enter your name please:    # 提示用户输入名字
read n                             # 将用户输入的名字保存到变量n                                                                            
echo Your name is $n               # 显示用户输入的名字      

Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

#号后的内容是对命令功能的说明。

2.3.2 执行脚本文件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 ~ $ 

Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

bash会将以+开头,将执行的命令显示出来,然后再显示命令执行的结果。

2.3.3 使用环境变量PS4定制显示格式

其实我们在使用bash的 -x选项来显示命令和参数时前面加的 + 是环境变量PS4 保存的。

purpleEndurer @csdn ~ $ set | grep PS4
PS4='+ '

Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

因此,我们可以通过修改环境变量PS4的值来设置 bash的 -x选项显示命令和参数时的格式。

例如:我们对显示的命令和参数以 > 开头,然后引入${BASH_SOURCE} 显示脚本文件名,${LINENO}显示行号,${FUNCNAME[0]}显示正在执行的函数的名字:

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 ~ $ 

Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

如果觉得字符太多,不容易辨别的话,我们还可以分别给它们加上颜色:

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

Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

这里我们使用了

Linux shell编程学习笔记4:修改命令行提示符格式(内容和颜色)https://blog.csdn.net/Purpleendurer/article/details/133416124?spm=1001.2014.3001.5501中介绍的知识,让脚本文件名以紫色显示,行号以黄色显示,正在执行的函数的名字以红色显示。

2.4 bash -v 脚本文件说明符:一边执行脚本,一边将执行过的脚本命令打印到标准输出(包括注释)

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:    # 提示用户输入名字
Enter your name please:read n                             # 将用户输入的名字保存到变量n                                                                            
abc
echo Your name is $n               # 显示用户输入的名字 
Your name is abc
purpleEndurer @csdn ~ $ 

Linux shell编程学习笔记29:shell自带的 脚本调试 选项,Linux世界,麒麟操作系统,编程资料,linux,学习笔记,Linux shell,shell脚本,bash -x,bash -n,bash -v

 可以看到,-v选项显示所执行的命令不受环境变量PS4的影响,而且会连脚本文件中的注释一并显示。文章来源地址https://www.toymoban.com/news/detail-757762.html

到了这里,关于Linux shell编程学习笔记29:shell自带的 脚本调试 选项的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Linux shell编程学习笔记35:seq

    在使用 for 循环语句时,我们经常使用到序列。比如: for i in 1 2 3 4 5 6 7 8 9 10; do echo \\\"$i * 2 = $(expr $i * 2)\\\";  done 其中的 1 2 3 4 5 6 7 8 9 10; 就是一个整数序列 。 为了方便我们使用数字序列,Linux提供了seq命令,这个命令是取自单词 sequence 的前3个字母。比如: for i in $(seq 1 10) ;

    2024年02月04日
    浏览(36)
  • Linux shell编程学习笔记27:tput

    除了stty命令,我们还可以使用tput命令来更改终端的参数和功能。 tput 命令的主要功能有:移动更改光标、更改文本显示属性(如颜色、下划线、粗体),清除屏幕特定区域等。  tput [选项] [参数] 命令格式:   tput setab n : 设置背景色,set text attributes background color   tput

    2024年02月05日
    浏览(39)
  • linux shell 脚本调试技巧

    本文分享自天翼云开发者社区《linux shell 脚本调试技巧》,作者:g****n 1.bash -x 加脚本 这是最常用的调试手段,终端会打印出,脚本执行过程中的每一个命令。 a. 查看脚本流程有无错误 b.查看变量值有无错误 c.查看退出位置是否符合预期 例如脚本 small_test.sh  #!/bin/bash echo 

    2024年04月24日
    浏览(43)
  • Linux shell编程学习笔记41:lsblk命令

    边缘计算面临着数据安全与隐私保护、网络稳定性等挑战,但同时也带来了更强的实时性和本地处理能力,为企业降低了成本和压力,提高了数据处理效率。因此,边缘计算既带来了挑战也带来了机遇,需要我们不断地研究 前几节学习我们均涉及到磁盘和文件存储,今天我们

    2024年01月24日
    浏览(39)
  • Linux shell编程学习笔记39:df命令

    0 前言 1  df命令的功能、格式和选项说明 1.1 df命令的功能 1.2 df命令的格式 1.3 df命令选项说明  2 df命令使用实例  2.1  df:显示主要文件系统信息 2.2 df -a:显示所有文件系统信息 2.3 df -t[=]TYPE或--type[=]TYPE:显示TYPE指定类型的文件系统信息 2.4 df --total:追加显示统计信息 2

    2024年01月16日
    浏览(44)
  • Linux shell编程学习笔记47:lsof命令

    今天国产电脑提示磁盘空间已耗尽,使用用df命令检查文件系统情况,发现/dev/sda2已使用100%。 Linux shell编程学习笔记39:df命令 https://blog.csdn.net/Purpleendurer/article/details/135577571 于是开始清理磁盘空间。 第一步是查看已删除、但空间却没有释放的进程。 这里要用到 lsof命令。

    2024年04月27日
    浏览(36)
  • Linux shell编程学习笔记33:type 命令

     目录 0 引言 1 type 命令的功能和格式 1.1 type命令的功能 1.2 type 命令的格式 2 type命令用法实例 2.1用type命令查看shell内置命令(以echo命令为例) 2.2 用type命令查看别名(以ls命令为例) 2.3 用type命令同时查看shell内置命令和别名(以echo和ls命令为例) 2.4 用type命令查看外部

    2024年02月03日
    浏览(44)
  • Linux shell编程学习笔记36:read命令

     *更新日志  *2023-12-18 1.根据[美] 威廉·肖特斯 (Willian shotts)所著《Linux命令行大全(第2版)》                         更新了-e、-i、-r选项的说明                       2.更新了 2.8 的实例,增加了gif动图                       3.补充了-i的应用实例 2.12 目录 目录

    2024年02月04日
    浏览(35)
  • Linux shell编程学习笔记40:stat命令

    “程序员必备的面试技巧,就像是编写一段完美的代码一样重要。在面试战场上,我们需要像忍者一样灵活,像侦探一样聪明,还要像无敌铁金刚一样坚定。只有掌握了这些技巧,我们才能在面试的舞台上闪耀光芒,成为那个令HR们心动的程序猿!” 目录 0 前言 1 DOS、Wind

    2024年01月19日
    浏览(43)
  • Linux shell编程学习笔记17:for循环语句

    Linux Shell 脚本编程和其他编程语言一样,支持算数、关系、布尔、字符串、文件测试等多种运算,同样也需要进行根据条件进行流程控制,提供了if、for、while、until等语句。  之前我们探讨了if语句,现在我们来探讨for循环语句。 Linux Shell中的for语句十分灵活,格式多样,我

    2024年02月06日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包