分页: 1 / 1

为何使用sh xx.sh和./xx.sh运行的结果不同呢?

发表于 : 2011-01-13 9:35
zipkong
例如我要运行这个shell script

vi sh01.sh
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo -e "Hello World!\a\n"
exit 0

如果我使用shsh01.sh来运行,则会显示-e Hello World!
如果我使用./sh01.sh来运行,则显示正常:Hello World!

而且发现这不是特例,例如
vi sh06.sh
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
read -p "Please input (Y/N): " yn
[ "$yn" == "Y" -o "$yn" == "y" ] && echo "OK, continue" && exit 0
[ "$yn" == "N" -o "$yn" == "n" ] && echo "Oh, interrupt!" && exit 0
echo "I don't know what your choice is" && exit 0

使用./sh06.sh非常正常,
但是使用sh sh06.sh就会显示:
Please input (Y/N):y
[:10:y:unexpected operator
[:11:y:unexpected operator
I don't know what your choice is

以上如果都用source运行,显示都正常,不过都会因为script里面的exit 0而导致整个shell的退出

我知道使用source是在父shell运行script的,而是用路径或者sh是在子shell运行的,是不是因为这种原因导致了三种运行方式都有不同的结果?
大侠能否具体的说明?谢谢

Re: 为何使用sh xx.sh和./xx.sh运行的结果不同呢?

发表于 : 2011-01-13 9:56
退避九舍
sh bash不同
第一行为 #!/bin/bash 故 ./shellname 用的是bash
而 sh shellname 用的是sh
好像默认的sh是指向dash的,而dash和bash之间有很大差别
你可以用 bash shellname 来运行它
如果第一行是 #!/bin/sh 则 ./shellname 和 sh shellname 的运行结果一致
shell有很多种,例如bash, csh, ksh ,zsh 等,每种shell的语法各有差异
第一行的 #!/bin/bash 表明它是用bash写的,也要用bash来运行

Re: 为何使用sh xx.sh和./xx.sh运行的结果不同呢?

发表于 : 2011-01-13 10:24
zipkong
非常感谢,醍醐灌顶啊!

Re: 为何使用sh xx.sh和./xx.sh运行的结果不同呢?

发表于 : 2011-01-13 10:25
peteryeh64
:em11 ...學習了...

Re: 为何使用sh xx.sh和./xx.sh运行的结果不同呢?

发表于 : 2011-01-13 10:33
remeber
shell多了也是问题。
了解下。

Re: 为何使用sh xx.sh和./xx.sh运行的结果不同呢?

发表于 : 2011-01-13 10:48
jmw778s
受教了,还真不知道这两个的区别。有bash为什么还要dash?

Re: 为何使用sh xx.sh和./xx.sh运行的结果不同呢?

发表于 : 2011-01-13 16:45
astolia
jmw778s 写了:受教了,还真不知道这两个的区别。有bash为什么还要dash?
自己看dash的描述呗
Since it executes scripts faster than bash, and has fewer library
dependencies (making it more robust against software or hardware
failures), it is used as the default system shell on Debian systems.