linux 脚本 语法错误,/bin/bash和/bin/sh解释器的误用引起的脚本语法错误

背景

下面的脚本,在Linux上运行良好,在SUNOS执行的时候报语法错误。

#! /bin/sh

#支持fwu的使用fwu 不支持的使用fu

PS_TYPE="ps -fwu"

do_ps=`ps -fwu 2>/dev/null`

if [ "$?" -eq 1 ]

then

PS_TYPE="ps -fu"

fi

OSTYPE=`uname -a | awk '{print substr($0,1,3)}'`

SELF_PATH=$(cd `dirname $0`; pwd)

#SELF_PATH=`dirname $0`

SELF_NAME=`basename $0`

其实就是获取脚本的当前文件路径。

同样的一段shell脚本,在 Linux主机上运行良好, 但是在SUNOS上 却执行报错了

Syntax error at line 12: `SELF_PATH=$' unexpected

问题分析

于是把这行脚本单独拿出来单独执行,但OK。

一番折腾之后,是脚本解释器的问题.

查看主机的SHELL解释器类型

ocsdb02:[/oracle$]echo $SHELL

/bin/bash

ocsdb02:[/oracle$]

解决办法

将 第一行的 #! /bin/sh 调整为 #!/bin/bash ,重新执行OK了。

事实上 SUOS主机上的sh的软连接的配置:

LINUX主机上的 sh的软连接配置 (sh一般设成bash的软链)

所以才会在Linux上运行OK,在sunos上执行语法错误,sh解释器不支持bash下的一些操作

第二种方法 是修改主机的默认SHELL,即修改软连接为BASH。

知识点回顾

Bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also incorporates useful features from the Korn and C shells (ksh and csh).

Linux中的shell有多种类型,其中最常用的几种是Bourne shell(sh)、C shell(csh)和Korn shell(ksh)。

Bourne shell在shell编程方面相当优秀,但在处理与用户的交互方面做得不如其他几种shell。

Linux操作系统缺省的shell是Bourne Again shell,它是Bourne shell的扩展,简称Bash,与Bourne shell完全向后兼容,并且在Bourne shell的基础上增加、增强了很多特性。Bash放在/bin/bash中,它有许多特色,可以提供如命令补全、命令编辑和命令历史表等功能,它还包含了很多C shell和Korn shell中的优点,有灵活和强大的编程接口,同时又有很友好的用户界面。

GNU/Linux 操作系统中的 /bin/sh 是 bash(Bourne-Again Shell)的符号链接,但鉴于 bash 过于复杂,有人把 ash 从 NetBSD 移植到 Linux 并更名为 dash(Debian Almquist Shell) https://wiki.ubuntu.com/DashAsBinSh ,并建议将 /bin/sh 指向它,以获得更快的脚本执行速度。

What you should use when writing scripts

If your script requires features only supported by bash,use #!/bin/bash.

But if at all possible,it would be good to make sure your script is POSIX-compatible,and use #!/bin/sh,which should always,quite reliably,point to the preferred POSIX-compatible system shell in any installation.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值