ubuntu rc.local 为何不执行?

----

rc.local的调试

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

exec 2> /tmp/rc.local.log  # send stderr from rc.local to a log file
exec 1>&2                      # send stdout to the same log file
set -x                         # tell sh to display commands before execution

/opt/stuff/somefancy.error.script.sh

exit 0

----

默认启动的其实还不是/etc/rc.local而是/etc/init.d/rc.local

#! /bin/sh
### BEGIN INIT INFO
# Provides:          rc.local
# Required-Start:    $remote_fs $syslog $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Run /etc/rc.local if it exist
### END INIT INFO


PATH=/sbin:/usr/sbin:/bin:/usr/bin

. /lib/init/vars.sh
. /lib/lsb/init-functions

do_start() {
,.if [ -x /etc/rc.local ]; then
,.        [ "$VERBOSE" != no ] && log_begin_msg "Running local boot scripts (/etc/rc.local)"
,.,./etc/rc.local
,.,.ES=$?
,.,.[ "$VERBOSE" != no ] && log_end_msg $ES 
,.,.return $ES 
,.fi
}

仅仅在dostart函数中启动了/etc/rc.local

可以看出来,在启动这个脚本之前,手动设置了PATH变量(这个很坏吧!)

----

对于12.04后的ubuntu,这个问题应该不存在了,dash可以兼容决大多数脚本,不信调试一下,几乎不会是dash的问题,而是脚本问题,或者其他文,比如环境变量的问题。

      为了让mysql开机启动,我将mysql命令添加到/etc/rc.local中,但怎么也运行不了。一开始认为只是/etc/rc.local的权限问题,但通过以下命令修改后,还是不起作用。

sudo chmod +x /etc/rc.local  // 增加可执行权限

sudo chmod +s /etc/rc.local  // 让普通用户执行该文件时拥有文件所有者的权限

      后来Google之后才发现是Ubuntu默认的dash在作怪:

#ls -al /bin/sh 

lrwxrwxrwx 1 root root 4 2009-12-11 06:04 /bin/sh -> dash

#ls -al /bin/dash

-rwxr-xr-x 1 root root 92132 2009-09-21 07:49 /bin/dash

      可以看出Ubuntu默认将/bin/sh链接到/bin/dash,而/etc/rc.local脚本中用的正是/bin/sh,导致出错,可以将/etc/rc.local的命令改成更加兼容的模式,或者直接将/bin/sh链接到/bin/bash。

/usr/bin/mystar >& /dev/null &         # dash报错,bash和csh不会报错

/usr/bin/mystar > /dev/null 2>&1     # dash兼容

      其实,从 Ubuntu 6.10开始,Ubuntu就将先前默认的bash shell 更换成了dash shell,其表现为 /bin/sh 链接倒了/bin/dash而不是传统的/bin/bash。Ubuntu dgy是第一个将dash作为默认shell来发行的版本,这似乎是受了debian的影响。wiki 里面有官方的解释,https://wiki.ubuntu.com/DashAsBinSh,主要原因是dash更小,运行更快,还与POSIX兼容。但目前存在的问题是,由于shell的更换,致使很多脚本出错,毕竟现在的很多脚本不是100%POSIX兼容。

将默认的shell改成bash的方法: 

方法1:在终端执行 sudo dpkg-reconfigure dash,然后选择 no.

方法2:重新进行软链接:

sudo rm /bin/sh

sudo ln -s /bin/bash /bin/sh

参见:http://blog.163.com/lgh_2002/blog/static/44017526201032803748503/

猜你喜欢

转载自fantaxy025025.iteye.com/blog/2097862
今日推荐