linux下的bash与sh 详解以及例子

来源:互联网 发布:matlab怎么导入数据 编辑:程序博客网 时间:2024/05/17 22:52

 

背景:经常会遇到bash执行ok,sh执行失败的情况

           即使sh 软连接到 bash也会失败

 

解决办法: shell脚本写明 #!/bin/bash

 

原因如下:

1、bash的POSIX标准

在一般的linux系统当中(如redhat),
使用sh调用执行脚本相当于打开了bash的POSIX标准模式
(等效于bash的 --posix 参数)

一般的,sh是bash的“子集”
(不是子集的部分,具体区别见下的“Things sh has that bash does not”)

例子:

[wwy@sf-watch test]$ cat t2.sh
#!/bin/bash
diff <(echo xxx) <(echo yyy)

[wwy@sf-watch test]$ bash -x ./t2.sh # 使用bash 调用,不会出问题
+ diff /dev/fd/63 /dev/fd/62
++ echo xxx
++ echo yyy
1c1
< xxx
---
> yyy
[wwy@sf-watch test]$ sh ./t2.sh    # 而用sh调用,报错如下
./t2.sh: line 3: syntax error near unexpected token `('
./t2.sh: line 3: `diff <(echo xxx) <(echo yyy)'
[wwy@sf-watch test]$ echo $?
2


但是,在我们的linux系统中,sh是bash的一个软链接:

[wangweiyu@ComSeOp mon]$ which sh
/bin/sh
[wangweiyu@ComSeOp mon]$ ls -l /bin/sh
lrwxrwxrwx  1 root root 4 Mar 21  2007 /bin/sh -> bash

 

那为什么上面的例子中还会出现问题呢?原因在于:
bash程序执行,当“$0”是“sh”的时候,
则要求下面的代码遵循一定的规范,当不符合规范的语法存在时,则会报错,
所以可以这样理解,
“sh”并不是一个程序,而是一种标准(POSIX),
这种标准,在一定程度上(具体区别见下面的“Things bash has that sh does not”)保证了脚本的跨系统性(跨UNIX系统)


下面的内容详细的说明了bash与sh在语法等方面的具体差异(引自Bash FAQ):

Things bash has that sh does not:

        long invocation options
        [+-]O invocation option
        -l invocation option
        `!' reserved word to invert pipeline return value
        `time' reserved word to time pipelines and shell builtins
        the `function' reserved word
        the `select' compound command and reserved word
        arithmetic for command: for ((expr1 ; expr2; expr3 )); do list; done
        new $'...' and $"..." quoting
        the $(...) form of command substitution
        the $(<filename) form of command substitution, equivalent to
                $(cat filename)
        the ${#param} parameter value length operator
        the ${!param} indirect parameter expansion operator
        the ${!param*} prefix expansion operator
        the ${paramffset[:length]} parameter substring operator
        the ${param/pat[/string]} parameter pattern substitution operator
        expansions to perform substring removal (${p%[%]w}, ${p#[#]w})
        expansion of positional parameters beyond $9 with ${num}
        variables: BASH, BASH_VERSION, BASH_VERSINFO, UID, EUID, REPLY,
                   TIMEFORMAT, PPID, PWD, OLDPWD, SHLVL, RANDOM, SECONDS,
                   LINENO, HISTCMD, HOSTTYPE, OSTYPE, MACHTYPE, HOSTNAME,
                   ENV, PS3, PS4, DIRSTACK, PIPESTATUS, HISTSIZE, HISTFILE,
                   HISTFILESIZE, HISTCONTROL, HISTIGNORE, GLOBIGNORE, GROUPS,
                   PROMPT_COMMAND, FCEDIT, FIGNORE, IGNOREEOF, INPUTRC,
                   SHELLOPTS, OPTERR, HOSTFILE, TMOUT, FUNCNAME, histchars,
                   auto_resume
        DEBUG trap
        ERR trap
        variable arrays with new compound assignment syntax
        redirections: <>, &>, >|, <<<, [n]<&word-, [n]>&word-
        prompt string special char translation and variable expansion
        auto-export of variables in initial environment
        command search finds functions before builtins
        bash return builtin will exit a file sourced with `.'
        builtins: cd -/-L/-P, exec -l/-c/-a, echo -e/-E, hash -d/-l/-p/-t.
                  export -n/-f/-p/name=value, pwd -L/-P,
                  read -e/-p/-a/-t/-n/-d/-s/-u,
                  readonly -a/-f/name=value, trap -l, set +o,
                  set -b/-m/-o option/-h/-p/-B/-C/-H/-P,
                  unset -f/-v, ulimit -i/-m/-p/-q/-u/-x,
                  type -a/-p/-t/-f/-P, suspend -f, kill -n,
                  test -o optname/s1 == s2/s1 < s2/s1 > s2/-nt/-ot/-ef/-O/-G/-S
        bash reads ~/.bashrc for interactive shells, $ENV for non-interactive
        bash restricted shell mode is more extensive
        bash allows functions and variables with the same name
        brace expansion
        tilde expansion
        arithmetic expansion with $((...)) and `let' builtin
        the `[[...]]' extended conditional command
        process substitution
        aliases and alias/unalias builtins
        local variables in functions and `local' builtin
        readline and command-line editing with programmable completion
        command history and history/fc builtins
        csh-like history expansion
        other new bash builtins: bind, command, compgen, complete, builtin,
                                 declare/typeset, dirs, enable, fc, help,
                                 history, logout, popd, pushd, disown, shopt,
                                 printf
        exported functions
        filename generation when using output redirection (command >a*)
        POSIX.2-style globbing character classes
        POSIX.2-style globbing equivalence classes
        POSIX.2-style globbing collating symbols
        egrep-like extended pattern matching operators
        case-insensitive pattern matching and globbing
        variable assignments preceding commands affect only that command,
                even for builtins and functions
        posix mode and strict posix conformance
        redirection to /dev/fd/N, /dev/stdin, /dev/stdout, /dev/stderr,
                /dev/tcp/host/port, /dev/udp/host/port
        debugger support, including `caller' builtin and new variables
        RETURN trap
        the `+=' assignment operator

Things sh has that bash does not:
        uses variable SHACCT to do shell accounting
        includes `stop' builtin (bash can use alias stop='kill -s STOP')
        `newgrp' builtin
        turns on job control if called as `jsh'
        $TIMEOUT (like bash $TMOUT)
 &nb

文章出处:http://www.diybl.com/course/6_system/linux/Linuxjs/200883/134576.html

原创粉丝点击