日期:2014-05-16  浏览次数:20620 次

shell script脚本不同执行方式结果不同,求教
脚本内容如下:
echo "$PATH\n"
echo "I love U."
echo "I Miss U"

第一种执行方式及结果:
root@sophie:/usr/bin# lily.sh
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n
I love U.
I Miss U


第二种执行方式及结果:
root@sophie:/usr/bin# sh lily.sh
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

I love U.
I Miss U


求大鸟解答。
------解决方案--------------------
echo 和 echo -e 的区别?
------解决方案--------------------
估计你用sh lily.sh调的话是直接用sh解析的。用lily.sh直接运行的话,调的是/bin/bash
应该是这个差别导致的。你可以在脚本第一行加一句:echo $BASH确认一下。
你可以分别试用如下方法调用看区别:
sh lily.sh
./lily.sh
bash ./lily.sh
我记得在一本书里看过,说是直接用sh调用不建议。另外,脚本开头一般要明确指定用哪个shell调用,你可以在脚本第一行分别加如下语句看看区别:
#!/bin/bash
#!/bin/sh

------解决方案--------------------
其实答案也很简单, 就是不同shell的echo实现不一样 (注意 这里的 echo 是内置命令)

$sh
$echo "test\n"
test

$bash
$ echo "test\n"
test\n
$

man page 清楚的写明了echo的用法不同

$man sh
DASH(1)                                       BSD General Commands Manual                                      DASH(1)

NAME
     dash — command interpreter (shell)

...
     echo [-n] args...
            Print the arguments on the standard output, separated by spaces.  Unless the -n option is present, a new‐
            line is output following the arguments.

            If any of the following sequences of characters is encountered during output, the sequence is not output.
            Instead, the specified action is performed:

            \b      A backspace character is output.

            \c      Subsequent output is suppressed.  This is normally used at the end of the last argument to sup‐
                    press the trailing newline that echo would otherwise output.

            \f      Output a form feed.

        &