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

 可以看到,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命令icon-default.png?t=N7T8https://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 ~ $

 可以看到,当前启用的选项有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   

 

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

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

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

 

可以看到,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               # 显示用户输入的名字      

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

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

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

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

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

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

因此,我们可以通过修改环境变量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 ~ $ 

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

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编程学习笔记4:修改命令行提示符格式(内容和颜色)icon-default.png?t=N7T8https://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 ~ $ 

 可以看到,-v选项显示所执行的命令不受环境变量PS4的影响,而且会连脚本文件中的注释一并显示。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/189976.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

YOLOv5轻量化改进之mobilenetv3,更换mobilenetv3中的注意力机制。

目录 一、原理 二、代码 三、YOLOv5改进 一、原理 我们提出了基于互补搜索技术和新颖架构设计相结合的下一代mobilenet。MobileNetV3通过硬件网络架构搜索(NAS)和NetAdapt算法的结合来调整到移动电话cpu,然后通过新的架构进步进行改进。本文开始探索自动搜索算法和网络设计如…

Java王者荣耀小游戏

Background类 package LX;import java.awt.*; //背景类 public class Background extends GameObject{public Background(GameFrame gameFrame) {super(gameFrame);}Image bg Toolkit.getDefaultToolkit().getImage("C:\\Users\\ASUS\\Desktop\\王者荣耀图片\\Map.jpg&…

【Spring整合MyBatis】Spring整合MyBatis的具体方法

在前面写的博客中,介绍了MyBatis通过配置方式和通过注解方式写的方法: 【Spring集成MyBatis】MyBatis诞生及代码快速入门(非注解开发)【Spring集成MyBatis】MyBatis的Dao层实现(基于配置,非注解开发&#…

前端学习网站推荐

1.菜鸟教程(程序员必备)菜鸟教程 - 学的不仅是技术,更是梦想! 2.npm库 npm | Home 3.uniapp学习官网 uni-app官网 4.vue官网 快速上手 | Vue.js 5.ECharts图表 Apache ECharts 6.ES6学习 ES6 入门教程 7.Three.js学习 Three.js…

17. Python 数据库操作之MySQL和SQLite实例

目录 1. 简介2. 使用PyMySQL2. 使用SQLite 1. 简介 数据库种类繁多,每种数据库的对外接口实现各不相同,为了方便对数据库进行统一的操作,大部分编程语言都提供了标准化的数据库接口,用户不需要了解每种数据的接口实现细节&#x…

Python教程:DataFrame数据中使用resample计算月线平均值

在pandas库中,DataFrame可以使用resample()方法来对时间序列数据进行重采样。重采样是将原始数据按照指定的频率进行重新组织,以便进行更细粒度的分析或转换。下面是一个示例,演示如何使用resample()方法: # Author : 小红牛 # 微…

uiautomator2 无法连接 ATX-Agent

最近需要写个安卓自动项目,本身不想用appium 。主要是appium需要安装的依赖太多,一单换个环境又要配置新的环境。但是ATX-Agent装好之后怎么都连接不是。 报错信息如下: .........省略............ uiautomator2.exceptions.GatewayError: (…

解密 sqli靶场第一关:一步一步学习 SQL 注入技术

目录 一、判断是否存在注入点 二、构造类似?id1 --的语句 三、判断数据表中的列数 四、使用union联合查询 五、使用group_concat()函数 六、爆出数据库中的表名 七、爆出users表中的列名 八、爆出users表中的数据 🌈嗨!我是Filotimo__🌈。很…

肾合胶囊 | 冬不养肾春易病,若出现了这六大表现,小心是肾虚!

冬季作为一年中最寒冷的季节,自然万物皆静谧闭藏,而肾具有潜藏、封藏、闭藏精气的特点,是封藏之本,肾的脏腑特性与冬季相通应,所以在冬季更应该重视养肾。 而现在正值初冬,正是开始养肾的最佳时间。此时培…

肾合胶囊 | “导龙入海,引火归元”——浅谈中医治法中的“引火归元”!

中医有许多特色的治疗方法,医家更是给它们起了文艺的名字。逆流挽舟、提壶揭盖、增水行舟,这些治疗方法无不体现了中医对生活、对自然的深入观察,并将这些自然现象与临床相结合,创立了一个个行之有效的方剂。 我们今天谈一谈“引…

【Linux】第二十站:模拟实现shell

文章目录 一、shell的实现细节1.shell的一些细节2.用户名、主机名、工作目录2.输入命令3.改为循环4.切割字符串5.普通命令的执行6.内建命令的处理7.子进程的退出码8.总结 二、模式实现shell完整代码 一、shell的实现细节 1.shell的一些细节 shell操作系统的一个外壳程序。 s…

字符串原地旋转

记录一下做的练习题 字符串原地旋转:五 三 mat [[1,2,3],[3,4,5],[4,5,6]] tag0 total 0 for i in mat:total total i[tag]tag 1 print(total) 四 X [[12,7,3],[4,5,6],[7,8,9]] Y [[5,8,1],[6,7,3],[4,5,9]] res [[0,0,0],[0,0,0],[0,0,0]] for i in rang…

阶梯排列硬币

题意: 你总共有 n 枚硬币,并计划将它们按阶梯状排列。对于一个由 k 行组成的阶梯,其第 i 行必须正好有 i 枚硬币。阶梯的最后一行 可能 是不完整的。 给你一个数字 n ,计算并返回可形成 完整阶梯行 的总行数。 示例 1&#xff…

线程的创建方式

作者简介: zoro-1,目前大二,正在学习Java,数据结构,mysql,javaee等 作者主页: zoro-1的主页 欢迎大家点赞 👍 收藏 ⭐ 加关注哦!💖💖 线程的创建方…

Spring Security 6.1.x 系列(5)—— Servlet 认证体系结构介绍

一、前言 本章主要学习Spring Security中基于Servlet 的认证体系结构,为后续认证执行流程源码分析打好基础。 二、身份认证机制 Spring Security提供个多种认证方式登录系统,包括: Username and Password:使用用户名/密码 方式…

【采坑分享】导出文件流responseType:“blob“如何提示报错信息

目录 前言: 采坑之路 总结: 前言: 近日,项目中踩了一个坑分享一下经验,也避免下次遇到方便解决。项目基于vue2axioselement-ui,业务中导出按钮需要直接下载接口中的文件流。正常是没有问题,但…

STM32 默认时钟更改 +debug调试

STM32时钟 文章目录 STM32时钟前言一、修改系统时钟二、DEBUG 前言 为什么我们要改STM32的时钟呢,打个比方在做SPI驱动的时候,需要16M的时钟,但是stm32默认是72的分频分不出来,这个时候我们就要改系统时钟了,那么怎么…

[科普] 无刷直流电机驱动控制原理图解

Title: [科普] 无刷直流电机驱动控制原理图解 文章目录 I. 引言II. 直流电机的原理1. 有刷直流电机和无刷直流电机的区别2. 有刷直流电机的运行原理3. 既是电动机又是发电机 III. 无刷直流电机的原理1. 无刷直流电机与永磁同步电机的区别2. 无刷直流电机的换向控制原理3. 无刷直…

Spring Cache(缓存框架)

学习的最大理由是想摆脱平庸,早一天就多一份人生的精彩;迟一天就多一天平庸的困扰。各位小伙伴,如果您: 想系统/深入学习某技术知识点… 一个人摸索学习很难坚持,想组团高效学习… 想写博客但无从下手,急需…

指针的进阶

重中之重: 目录 1.字符指针: 2.指针数组 3.数组指针 4.数组参数、指针参数 5.函数指针 1.字符指针: 一般实现: int main() {char ch w;char *pc &ch;*pc w;return 0; } 二班实现: int main() {const c…
最新文章