# Shell Script 的追踪与 debug

scripts 在执行前,最怕出现语法错误问题了,可以通过 bash 相关参数来检测

sh [-nvx] scripts.sh

选项与参数:
-n:不执行 script,仅检查语法问题
-v:执行 script 前,先将 scripts 内容输出到屏幕上
-x:将执行到的 script 内容显示到屏幕上,相当于 debug 了
1
2
3
4
5
6
# 范例 1:测试 dir_perm.sh 有无语法问题?
sh -n dir_perm.sh
# 如果没有语法问题,则不会显示任何信息
# 笔者实测,貌似语法检测效果并不强大
1
2
3
4
# 范例 2:将 show_animal.sh 的执行过程全部列出来
[mrcode@study bin]$ sh -x show_animal.sh 
+ PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/home/mrcode/bin
+ export PATH
+ for animal in dog cat elephant
+ echo 'There are dogs...'
There are dogs...
+ for animal in dog cat elephant
+ echo 'There are cats...'
There are cats...
+ for animal in dog cat elephant
+ echo 'There are elephants...'
There are elephants...

# 下面是原始脚本,方便对比
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

for animal in dog cat elephant
do
        echo "There are ${animal}s..."
done
# 可以看到,每次循环执行,都打印出来了关键信息,
# 该功能非常有用,可以当成 debug 来使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

熟悉 sh 的用法,可以使你在管理 Linux 的过程中得心应手,至于在 shell script 的学习方法上,需要多看、多模仿、并加以修改成自己的代码,是最快的学习手段了。网络有上相当多的有用的 scripts,你可以将其拿来进行修改成自己的代码

另外,Linux 系统本来就有很多的服务启动脚本,如果想要知道每个 script 所代表的功能是什么,直接 vim 进入该 script 查阅下,通常就知道了。比如说之前提到的 /etc/init.d/netconsole 是做什么的?直接查看他的前几行

vim /etc/init.d/netconsole 


#!/bin/bash
# 
# netconsole    This loads the netconsole module with the configured parameters.
#
# chkconfig: - 50 50
# description: Initializes network console logging
# config: /etc/sysconfig/netconsole
#
### BEGIN INIT INFO
# Provides:          netconsole
# Required-Start:    $network
# Short-Description: Initializes network console logging
# Description:       Initializes network console logging of kernel messages.
### END INIT INFO

# Copyright 2002 Red Hat, Inc.
#
# Based in part on a shell script by
# Andreas Dilger <adilger@turbolinux.com>  Sep 26, 2001

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

通过上述的描述可以知道,在网络终端机来应付登录的意思,且配置文件在 /etc/sysconfig/netconsole