我的里面有一个 shell 脚本Ubuntu 服务器 14.04 LTS在./ShellScript.sh
。我设置/etc/rc.local
为在启动后但在登录之前使用以下代码运行 shell 脚本。
要运行它,请在终端中输入此命令: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.
#!/bin/bash
./ShellScript.sh
exit 0
注意:请记住,我正在root
模式下工作。现在当我运行时crontab -e
,我得到了以下信息。现在该做什么?
no crontab for root - using an empty one
Select an editor. To change later, run 'select-editor'.
1. /bin/ed
2. /bin/nano <---- easiest
3. /usr/bin/vim.basic
4. /usr/bin/vim.tiny
Choose 1-4 [2]:
选择后2
,我得到了crontab: "/usr/bin/sensible-editor" exited with status 2
现在我想反复运行/执行此 shell 脚本,每次运行间隔为 15 分钟,在启动后但登录前。我能做到吗?
回答:
首先,您不能通过crontab -e
root 访问。您必须通过 USER 帐户登录。登录 USER 帐户后,转到终端并输入crontab -e
您将获得如下所示的一些文本。
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
现在,在文件末尾,您必须添加*/15 * * * * /ShellScript.sh
一行,以便每 15 分钟运行一次脚本。现在保存文件,就完成了。
笔记: 如果您想要以不同的时间间隔反复运行脚本,那么不要感到困惑。这里有一些可以为您生成 Cron 行的在线工具。
答案1
你不能简单地在后台运行它吗,在 while 循环内:
while true
do
[command]
sleep [number of seconds]
done
因此构造如下:
- 添加一行
/etc/rc.local
来调用你的脚本(你的ShellScript.sh
)+“&”使其退出 ShellScript.sh
在 while 循环中(在 内)运行您想要执行的命令Shellscript.sh
:while true do [command_1] [command_2] [command_3] [command_4] sleep 900 done
这样它就会在启动时运行,然后每 15 分钟运行一次
请注意,如果您想从运行它cron
,您需要设置完整路径,因为它cron
使用有限的环境变量运行。
例子:
我创建了一个愚蠢的脚本,在我的桌面上的文件中添加了一行带有字符串“monkey”的内容test.txt
:
剧本:
#!/bin/bash
while true
do
echo monkey>>/home/jacob/Desktop/test.txt
sleep 5
done
我的文件中的行/etc/rc.local
:
sh /home/jacob/Desktop/while.sh &
就这样。