简体   繁体   English

BASH脚本:代码可在终端上运行,但不能从rc.local上运行

[英]BASH SCRIPT : Code works from terminal but not from rc.local

I've written a small script that ping's an address and then mounts the device at that address if the ping returned successful. 我编写了一个小脚本,该命令ping是一个地址,如果ping返回成功,则将设备安装到该地址。 The file is located in rc.local on a Ubuntu Linux System. 该文件位于Ubuntu Linux系统上的rc.local中。

It works great if run from a terminal (as root), but won't run from rc.local at boot. 如果从终端(以root用户身份)运行,则效果很好,但在启动时不会从rc.local运行。 I know it's being executed because /tmp/buffalo_mount.log contains "Executing Network Device Detect Script From rc.local". 我知道它正在执行,因为/tmp/buffalo_mount.log包含“从rc.local执行网络设备检测脚本”。 Anyone got any ideas? 任何人有任何想法吗?

NOTE: Now working! 注意: 现在可以使用! Please read notes below :-) 请阅读以下说明:-)

#!/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.

ADDRESS=192.168.1.101
DATETIME="$(date)"
LOGFILE="/tmp/buffalo_mount.log"

sleep 30s

echo "Executing Network Device Detect Script From rc.local" >> $LOGFILE
    if /bin/ping -c 1 -t 1 $ADDRESS > /tmp/ping 2>&1 ;then  # check the exit code
        echo "$ADDRESS is LIVE  "+$DATETIME >> $LOGFILE # display the output
    # Ping reply was good, so run the mount command.
    echo "Slept, now mounting device" >> $LOGFILE
    /bin/mount /media/Buffalo/Acer-laptop-back_in_time
    else
        echo "$ADDRESS is DEAD  "+$DATETIME >> $LOGFILE
fi

Then I had to edit the '/etc/fstab' file so the fstab knows about the mount, but doesn't mount until told to by my script above, using the ' noauto ' parameter. 然后,我必须编辑'/ etc / fstab'文件,以便fstab知道有关安装的信息,但是直到上面的脚本通过使用' noauto '参数告知安装为止。 My example in fstab is:- 我在fstab中的示例是:

//192.168.1.101/back-in-time/ /media/Buffalo/Acer-laptop-back_in_time cifs **noauto**,guest,uid=1000,iocharset=utf8,codepage=unicode,unicode,_netdev  0  0

Really hope this help someone because it was driving me nuts. 真的希望这对某人有所帮助,因为它使我发疯。 Thanks to all those that helped. 感谢所有提供帮助的人。

The -e argument asks sh to exit if a command have a non 0 exist status, thus the script will stop instead of executing the else branch of your if. -e参数要求sh退出命令是否存在非0状态,因此脚本将停止而不是执行if的else分支。 You should replace 你应该更换

/bin/ping -c 1 -t 1 $ADDRESS > /dev/null 2> /dev/null  # ping and discard output
if [ $? -eq 0 ] ; then

by 通过

if /bin/ping -c 1 -t 1 $ADDRESS > /dev/null 2>&1 ; then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM