Shell-/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.

参考资料:
https://man.cx/bash

你可能感兴趣的:(【系统运维-Linux】,Linux手札)