shell混用引发的一个问题

来源:岁月联盟 编辑:exp 时间:2011-09-19

今天在使用debian 脚步启动一个sh时一直报错,由此引发此文的形成:

 


在使用bash shell时,我们有这样的场景:

env.sh  -- 定义公共的变量


run1.sh  -- 定义运行代码

run2.sh  -- 定义运行代码

 

 

如果env.sh中的内容是根据具体的run*.sh作变化,那么就需要给env.sh中传入变量。

很多人可能会采用这种方式,

 


场景模拟:


env.sh:

view plaincopy to clipboardprint?#!/bin/sh 
echo $1 
#!/bin/sh
echo $1

 


run1.sh:
view plaincopy to clipboardprint?#!/bin/sh 
 
CURRENT_PATH='core' 
 
echo ${CURRENT_PATH} 
 
. /home/admin/tmp/madding.lip/env.sh $CURRENT_PATH 
 
echo "invoke $CURRENT_PATH-service $1"  
 
if [ "$1" = "stop" ] ; then 
    echo "`date`:stop --------------------------------"  
    echo "remove $shutdownFile" 
elif [ "$1" = "debug" ] ; then 
    echo "`date`:debug --------------------------------"  
fi 
#!/bin/sh

CURRENT_PATH='core'

echo ${CURRENT_PATH}

. /home/admin/tmp/madding.lip/env.sh $CURRENT_PATH

echo "invoke $CURRENT_PATH-service $1"

if [ "$1" = "stop" ] ; then
    echo "`date`:stop --------------------------------"
    echo "remove $shutdownFile"
elif [ "$1" = "debug" ] ; then
    echo "`date`:debug --------------------------------"
fi

 

 

执行命令:

sh run.sh start

 


结果:

在redhat 5.3中:

core
core
invoke core-service

 

debian 6:

core

start

invoke core-service

 

 

 

分析:

 

 

表面现象问题出在:


view plaincopy to clipboardprint?. /home/admin/tmp/madding.lip/env.sh $CURRENT_PATH 
. /home/admin/tmp/madding.lip/env.sh $CURRENT_PATH

 


根本:

debian默认使用的:

view plaincopy to clipboardprint?madding@wmmad:~$ which sh 
/bin/sh 
madding@wmmad:~$ ls -l /bin/sh 
lrwxrwxrwx 1 root root 4 Jun  6 05:49 /bin/sh -> dash 
madding@wmmad:~$ which sh
/bin/sh
madding@wmmad:~$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Jun  6 05:49 /bin/sh -> dash

redhat默认sh使用:

view plaincopy to clipboardprint?[admin@**** ~]$ which sh 
/bin/sh 
[admin@**** ~]$ ls -l /bin/sh  
lrwxrwxrwx 1 root root 4 Nov 16  2010 /bin/sh -> bash 
[admin@**** ~]$ which sh
/bin/sh
[admin@**** ~]$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Nov 16  2010 /bin/sh -> bash

 

 


处理意见:

1.shell尽量用各个都兼容的方式书写,这样可移植性比较强

2.如果明确使用的shell,尽量在头部表明,这样执行./方式执行时能识别具体的shell

3.如果用具体的shell加脚步方式执行的话,建议明确shell脚步的解析器,如dash xx.sh 或者 bash xx.sh

 作者“madding.lip”