ubuntu rc.local 爲何不執行?

http://www.tuicool.com/articles/FVrQner


----

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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章