【问题标题】:linux - how to change directory and run a command on startup using rc.locallinux - 如何在启动时使用 rc.local 更改目录和运行命令
【发布时间】:2016-06-02 01:19:47
【问题描述】:

我在 ec2 的一个盒子上运行 ubunto。每次机器启动时,我想在特定目录中执行以下命令:

celery -A someapp.tasks --concurrency=1 --loglevel=info worker > output.log 2> errors.log

我跑了

sudo nano /etc/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.
(
    cd /home/ubuntu/somefolder/
    sh -e -c 'celery -A someapp.tasks worker -Ofair --loglevel=info > output.log > errors.log'
)
exit 0

但是当服务器启动时,命令不会运行。如果我直接 cd 进入 /home/ubunto/somefolder 并运行 celery 命令,操作将按预期开始。每次机器启动时如何运行这个命令?

【问题讨论】:

  • 您是否尝试过以 root 用户身份“直接 cd 进入 /home/ubunto/somefolder 并运行 celery 命令”?
  • 即$ sudo celery ... ?我还没有尝试过,但了解这对权限的影响。
  • 甚至sudo su - 然后 cd ... 和 celery ...,以防权限问题已经影响到目录
  • celery 在哪里?它可能不在默认的$PATH 中。
  • @StefanHegny 当我运行sudo su - 时,我无法使用cd /home/ubuntu/somefolder/ 更改密码。如果我执行 ls 它什么也不返回。 pwd 只是给\root

标签: linux bash ubuntu


【解决方案1】:

像这样尝试,使用子shell,这样你就不会改变rc.local的工作目录:

(
  cd /home/ubuntu/somefolder 
  celery -A someapp.tasks --concurrency=1 --loglevel=info worker >output.log 2> errors.log
)
exit 0

【讨论】:

  • 感谢您的意见。我试过括号,但没有骰子。我将更新我的问题以反映 rc.local 的新状态
  • 啊,我明白了。你能帮我试试这个吗? cd /home/ubuntu/somefolder 然后sh -e -c 'celery -A someapp.tasks --concurrency=1 --loglevel=info worker > output.log 2> errors.log'
  • 我已经按照建议编辑了文件(也更新了有问题的代码),但仍然没有骰子。为了测试我添加了编辑。停了机器。然后又开始了。经检查,celery 命令尚未运行:/
  • 对不起,我的意思是在命令行上手动运行它,看看它是否有效。
  • 对我也不起作用,但尝试了不同的命令。可能与 etc 文件夹的位置有关?
【解决方案2】:

您可以简单地使用以下内容:

sudo vi /etc/crontab

在最后添加:

@reboot  cd /home/ubuntu/somefolder/ && sh -e -c 'celery -A someapp.tasks worker -Ofair --loglevel=info > output.log > errors.log'

干杯。

【讨论】:

    【解决方案3】:

    我会试试这个:

    cd /home/ubuntu/somefolder && celery -A someapp.tasks --concurrency=1 --loglevel=info worker >output.log 2> errors.log
    

    【讨论】:

      猜你喜欢
      • 2016-09-24
      • 2013-01-07
      • 2021-12-31
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      相关资源
      最近更新 更多