Shell-/bin/bash和/bin/sh解释器的误用引起的脚本语法错误
文章目錄
- 生猛干貨
- 背景
- 問題分析
- 解決辦法
- 知識點回顧
- 搞定Linux核心技術(shù)
生猛干貨
從系統(tǒng)安裝到程序員必備的Linux技能,還原真實工作場景,手把手帶你實戰(zhàn)演練
背景
下面的腳本,在Linux上運行良好,在SUNOS執(zhí)行的時候報語法錯誤。
#! /bin/sh#支持fwu的使用fwu 不支持的使用fu PS_TYPE="ps -fwu" do_ps=`ps -fwu 2>/dev/null` if [ "$?" -eq 1 ] thenPS_TYPE="ps -fu" fiOSTYPE=`uname -a | awk '{print substr($0,1,3)}'` SELF_PATH=$(cd `dirname $0`; pwd) #SELF_PATH=`dirname $0` SELF_NAME=`basename $0`其實就是獲取腳本的當(dāng)前文件路徑。
同樣的一段shell腳本,在 Linux主機(jī)上運行良好, 但是在SUNOS上 卻執(zhí)行報錯了
syntax error at line 12: `SELF_PATH=$' unexpected問題分析
于是把這行腳本單獨拿出來單獨執(zhí)行,但OK。
一番折騰之后,是腳本解釋器的問題.
查看主機(jī)的SHELL解釋器類型
ocsdb02:[/oracle$]echo $SHELL /bin/bash ocsdb02:[/oracle$]解決辦法
將 第一行的 #! /bin/sh 調(diào)整為 #!/bin/bash ,重新執(zhí)行OK了。
事實上 SUOS主機(jī)上的sh的軟連接的配置:
LINUX主機(jī)上的 sh的軟連接配置 (sh一般設(shè)成bash的軟鏈)
所以才會在Linux上運行OK,在sunos上執(zhí)行語法錯誤, sh解釋器不支持bash下的一些操作
第二種方法 是修改主機(jī)的默認(rèn)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編程方面相當(dāng)優(yōu)秀,但在處理與用戶的交互方面做得不如其他幾種shell。
Linux操作系統(tǒng)缺省的shell是Bourne Again shell,它是Bourne shell的擴(kuò)展,簡稱Bash,與Bourne shell完全向后兼容,并且在Bourne shell的基礎(chǔ)上增加、增強(qiáng)了很多特性。Bash放在/bin/bash中,它有許多特色,可以提供如命令補(bǔ)全、命令編輯和命令歷史表等功能,它還包含了很多C shell和Korn shell中的優(yōu)點,有靈活和強(qiáng)大的編程接口,同時又有很友好的用戶界面。
GNU/Linux 操作系統(tǒng)中的 /bin/sh 是 bash(Bourne-Again Shell)的符號鏈接,但鑒于 bash 過于復(fù)雜,有人把 ash 從 NetBSD 移植到 Linux 并更名為 dash(Debian Almquist Shell) https://wiki.ubuntu.com/DashAsBinSh ,并建議將 /bin/sh 指向它,以獲得更快的腳本執(zhí)行速度。
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核心技術(shù)
總結(jié)
以上是生活随笔為你收集整理的Shell-/bin/bash和/bin/sh解释器的误用引起的脚本语法错误的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Oracle-Oracle数据库结构
- 下一篇: Spring-Spring4.X 概述