shell脚本检验----帮你更快解决代码错误

目录

sh  -n 

sh   -x

常见错误及解决方法:

command not found                找不到命令

syntax error:    unexpected end of file


sh  -n  filename  #不运行脚本,只检查语法错误
                        #作用和--syntax-check一样
sh  -x  filename  #运行并跟踪脚本执行过程

sh  -n 

使用演示:

[root@localhost test]# bash -n test1.sh     #直接在sh或bash后面加-n
test1.sh: line 13: syntax error: unexpected end of file #syntax error:语法错误

如果没有语法错误便不会有任何返回,演示:

sh   -x

使用演示:和- n一样

[root@localhost test]# bash -x test1.sh
test1.sh: line 13: syntax error: unexpected end of file
[root@localhost test]# bash -x test2.sh
++ ps -ef
++ grep sshd
++ grep -v grep
++ wc -l
+ num1=3
+ test 3 -ge 1
+ echo sshd is running
sshd is running
+ num2=ss
+ -lntup
+ grep 22
test2.sh: line 18: -lntup: command not found
+ wc -l
0
+ [[ '' -ge 1 ]]
+ echo sshd is off
sshd is off

sh -x会直接在错误的地方显示就可以较快的找到错误

sh -n只会报语法错误,其他不管,比如上面的test2.sh脚本,有其他类型错误但没有语法错误

常见错误及解决方法:

command not found                找不到命令

这类错误出现的原因有很多,要根据具体情况分析常见的有以下几种

1.不是可执行命令

[root@localhost test]# $?  像$?这种不可直接执行的命令会出现这类错误,修改我们的输出格式就好了
bash: 0: command not found...
#比如
[root@localhost test]# echo $?   #echo为可执行命令
127

2.如果是echo、mv、vim等都出现command not found  报错的话,很大概率就是未配置环境变量

解决方法:

[root@localhost test] echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin

[root@localhost test] vim ~/.bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs
PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
export PATH

3.如果命令别名被修改也会出现这类错误

[root@localhost test]# ll
total 32
-rw-r--r--. 1 root root 197 Aug 22 22:38  test1.sh
-rw-r--r--. 1 root root 429 Aug 20 16:11  test2.sh
-rw-r--r--. 1 root root 233 Aug 20 16:03  test3.sh
[root@localhost test]# unalias ll
[root@localhost test]# ll
bash: ll: command not found...

syntax error:    unexpected end of file

语法错误:             文件的意外结束

解决方法:查看所写脚本添加上结束语

[root@localhost test]# vim end.sh
if [ 3 -le 4 ]
then
        echo 3
else
        echo 4
fi  #这里如果忘写fi就会出现这类语法错误

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值