linux shell本身支持一些调试手段,可以方便分析shell文件的执行路径;
使用set命令可以查看与设置shell的环境变量,如下
robot:~# set
HISTFILE='/home/root/.history'
HOME='/home/root'
HOSTNAME='robot'
IFS='
'
LINENO=''
LOGNAME='root'
OPTIND='1'
PATH='/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin'
PPID='25587'
PS1='robot:~#'
PS2='> '
PS4='+ '
PWD='/home/root'
SHELL='/bin/sh'
SHLVL='1'
SSH_CLIENT='192.168.1.138 51210 22'
SSH_CONNECTION='192.168.1.138 51210 192.168.1.10 22'
SSH_TTY='/dev/pts/0'
TERM='xterm'
USER='root'
set支持的选项可参考:
Linux set命令 | 菜鸟教程 (runoob.com)
Bash Reference Manual (gnu.org) 4.3.1 The Set BuiltIn
如使用set -x指令使能显示shell执行的指令及参数;使用set +<para>可取消para对应的设置;
robot:~#set -x
robot:~#ls -l
+ ls -l
-rw-r--r-- 1 root root 21 Jan 3 06:19 bash_profile
robot:~#set +x
+ set +x
robot:~#ls -l
-rw-r--r-- 1 root root 21 Jan 3 06:19 bash_profile
robot:~#
也可以在脚本中增加-x选项,则执行脚本时也会打印脚本中对应的语句
robot:~#cat debug.sh
#!/bin/bash -x
echo test
hostname
robot:~#./debug.sh
+ echo test
test
+ hostname
robot
可以看到,打印的执行指令前都有1个“+”,对应着shell的环境变量PS4,因此可以在脚本使用如下方法显示指令所在的文件以及行号;
robot:~#echo $PS4
+
robot:~#cat debug.sh
#!/bin/bash -x
export PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '
echo test
hostname
robot:~#./debug.sh
+ export 'PS4=+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '
+ PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '
+./debug.sh:4:main: echo test
test
+./debug.sh:6:main: hostname
robot
更改shell环境变量 PS1的值即可更改shell的显示的用户名@主机名
robot:~#cat ./bash_profile
export PS1=robot@arm:~#
robot:~#source ./bash_profile
robot@arm:~#
export PS1="\u@\h:\w\$" 恢复PS1默认值