Installing new crontab

Когда я пишу команду crontab -e в терминале,

я получаю это сообщение об ошибке:

no crontab for root - using an empty one 888

Я не знаю, что означает «888»?

Файл конфигурации crontab / etc / crontab:

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
58 * * * * root cd / && run-parts --report /etc/cron.hourly
52 0 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
46 0 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
9 5 28 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#

Пожалуйста, помогите мне.

Your error is a little bizarre. To investigate it further you might like to install gdb and the debuginfo package for your crontab command so that we can see what it is trying to do. My crontab command is part of the cronie package, as I found by doing:

$ rpm -qf $(command -v crontab)
cronie-1.4.12-5.fc22.x86_64

You can install the debuginfo package for it with dnf:

$ sudo dnf --enablerepo='*-debuginfo' install cronie-debuginfo
# gdb crontab
(gdb) break glue_strings
(gdb) run -e

You should see a dump of the parameters passed to glue_strings() when it was called.

Breakpoint 1, glue_strings (buffer=0x7ffdaa552740 "", buffer_size=4096, 
    a=0x55c50950e567 "/var/spool/cron", b=0x55c5097154c0 <User> "meuh", 
    separator=47 '/') at misc.c:110
110             if (buffer_size <= 0)

Enter the command c to continue. There may be several calls. The last one before the program ends is the most interesting. Add this output to your original post for further diagnosis.


The above commands on getting debuginfo are for Fedora. For Red Hat 7.1 see this article which seems to be saying list the channels with

subscription-manager repos --list | grep -i debug

and enable the one you want, eg

subscription-manager repos --enable=rhel-rs-for-rhel-7-server-fastrack-debug-rpms
if [ -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY exists.
fi

Or to check if a directory doesn’t exist:

if [ ! -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY doesn't exist.
fi

However, as Jon Ericson points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check.
E.g. running this:

ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then 
  rmdir "$SYMLINK" 
fi

Will produce the error message:

rmdir: failed to remove `symlink': Not a directory

So symbolic links may have to be treated differently, if subsequent commands expect directories:

if [ -d "$LINK_OR_DIR" ]; then 
  if [ -L "$LINK_OR_DIR" ]; then
    # It is a symlink!
    # Symbolic link specific commands go here.
    rm "$LINK_OR_DIR"
  else
    # It's a directory!
    # Directory command goes here.
    rmdir "$LINK_OR_DIR"
  fi
fi

Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean in another answer.

If the variables contain spaces or other unusual characters it will probably cause the script to fail.

You would have to run this as root, but:

for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done

for user in $(cut -f1 -d: /etc/passwd); do echo $user; crontab -u $user -l; done

Your commands should actually work, however it’s not as I would do it.

Instead try :-

sudo crontab -e -u root

then to list :-

sudo crontab -l -u root

As a general rule I go to a great deal of trouble to never run a root shell. When I do I use sudo -s rather than sudo su.

When you exit from vi you should see two lines :-

crontab: no crontab for root - using an empty one
crontab: installing new crontab

If you don’t get those two lines you have serious troubles. If you do and then the list command doesn’t show anything I would suspect permission troubles.

I also wouldn’t use your example line as you are asking the system to run «sayhi.sh» once a minute all day, every day. I also wonder about the path «/sayhi.sh» — do you really have the script right up the top of your boot drive? That’s not a good idea either or do you perhaps mean «~/sayhi.sh» which in this case would be in roots home directory (usually /var/root) or do you mean your home directory. In crontab files it’s best to explicitly code the entire path, regardless.

You do also realise that tany output of the cron job will not go to any terminal but will instead be emailed to root (by default).

If you want to check that cron is running tasks a simple

*/5 * * * *   echo "CRON" > /Users/myname/.cronout

will do that (the first field runs the task a much more reasonable every 5 minutes).

The crontabs themselves are stored in /usr/lib/cron/tabs. /usr/lib/cron is actually a link to /var/at and if you go there you will find the tabs directory and also the cron.deny file. Check that nobody has added root to that and if you still have no joy then you might try :

echo > /var/at/tabs/root

which should create an empty file that you might then be able to edit.

Добрый день, cron перестал выполнять задания совсем. Решил попробовать создать занового файл и все прописать. Получился вот такой файл

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin/
# m h dom mon dow user  command

*  *    * * *   root    touch /root/home/1.txt
#

Для теста решил дать задание, чтобы он создавал файл в определенной папке, но ничего не происходит абсолютно, задание редактирую через команду sudo crontab -e. Если в ручную выполняю touch /root/home/1.txt, то файл создается.

Дополнительно:  Не работают наушники на компьютере. Почему не идет звук на наушники?

Кто знает в чем может быть дело?


  • Вопрос задан

Видимо служба не запущена.

service cron status
что говорит?

/etc/init.d/cron status
что говорит?

Если ubuntu/debian, то:
sudo systemctl enable cron

чтобы всегда запускалась служба.

А запустить вручную:
service cron start
/etc/init.d/cron start

Если у Вас старые версии, то там может быть не cron, а crond

Часто очень, простое добавление в nano или др. редакторе команды расписания через:
sudo crontab -e
после сохранения Ctrl+O -> Enter, Ctrl+X, хоть и пишет, что задание модифицировано (добавлено), расписание не срабатывает.

Рекомендуется сделать перезапуск cron (crontab):

sudo /etc/init.d/cron restart

Если без него, т.е. задание писалось через crontab -e, файл ваше_имя_пользователя_в_системе пишется в:
/var/spool/cron/crontabs/ваше_имя_пользователя_в_системе

Если с sudo, т.е. задание писалось через sudo crontab -e, файл root пишется в:
/var/spool/cron/crontabs/root

export s="$(which touch)"; perl -i -pe 's/touch/$ENV{"s"}/' /etc/crontab

проверьте через минуту, сработал ли крон.

Укажите полный путь к команде touch

В конце файла добавьте не менее 2-х пустых строк — это не бага, это фича.
Если в конце файла нет 2 пустых строк, то файл не будет выполняться.

04 июл. 2023, в 21:18

5000 руб./за проект

04 июл. 2023, в 21:05

5000 руб./за проект

04 июл. 2023, в 21:02

30000 руб./за проект

My Dockerfile appears to build correctly (it tells me so). When I run the container, I get the below error message. I have tried running the commands (CMD) with and without the service’s directory.

crontab.sh basically writes a cron schedule to a text file (cron.jobs) and then imports the text file to crontab.

FROM node:0.10
MAINTAINER Tom

VOLUME /var/log/

RUN mkdir /pulse
ADD . /pulse
WORKDIR /pulse

RUN apt-get update && apt-get install -y cron

ADD *.sh /pulse/
RUN chmod 750 /pulse/crontab.sh && chmod 750 /pulse/

RUN chmod 644 /etc/crontab

CMD cron -f
CMD touch /var/log/cron.log && sh /pulse/crontab.sh && tail -f /var/log/cron.log
CMD cron /pulse/cron.jobs
CMD crontab -l

edited to add crontab.sh

crontab.sh (some crons have been removed):

#!/bin/bash

cat <<- 'EOF' > cron.jobs

0 * * * * node /pulse/scripts/awsPulseTest.js > /tmp/awsPulseTest.log 2>&1

EOF

crontab cron.jobs
no crontab for root
  • Pulse is the name of the service.
  • The version of node is old due to the service, this will be upgraded.
  • The service is essentially for cron jobs in node

asked May 22, 2017 at 7:06

TomFirth's user avatar

1 gold badge2 silver badges7 bronze badges

It’s an issue with the dockerfile (rather than the commands in the file).
Only one CMD is run (the last one) — see https://docs.docker.com/engine/reference/builder/#cmd

There can only be one CMD instruction in a Dockerfile. If you list
more than one CMD then only the last CMD will take effect.

answered May 22, 2017 at 8:45

Paul Haldane's user avatar

Paul Haldane

1 gold badge21 silver badges32 bronze badges

As the other answers have already explained, only one CMD will be run per Dockerfile and the command you want to run is wrong.

But there is a more pressing issue with your setup IMO — Docker containers are not usually designed to work this way. What you should do instead is running the cron services from the host (or your orchestrator) as one-off processes (probably using something like docker run or docker-compose run, or, if for some reason you don’t want to start a separate container for this, I guess you could use docker exec).

This is just my view on how containers should be used though, so obviously you should take it with a grain of salt.

answered May 22, 2017 at 12:53

Artur Ciesielski's user avatar


My guess is that /pulse/crontab.sh (which you don’t show, why?) adds the relevant crontab line to the system wide crontab file /etc/crontab. You later execute the command crontab -l, but this only shows an error because it lists roots personal crontab only (which happens to be empty), not the system-wide one in /etc/crontab. This is all perfectly normal and expected. To show the line your script added, you would replace CMD crontab -l with CMD cat /etc/crontab.

All of this has nothing to to with any dockerfile commands like ADD, RUN or CMD, it’s just basic Linux stuff.

answered May 22, 2017 at 7:27

Sven's user avatar

13 gold badges179 silver badges226 bronze badges

Php – UTF-8 all the way through
  • Specify the utf8mb4 character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use utf8mb4 encoding if a utf8mb4_* collation is specified (without any explicit character set).

  • In older versions of MySQL (< 5.5.3), you’ll unfortunately be forced to use simply utf8, which only supports a subset of Unicode characters. I wish I were kidding.

  • In your application code (e.g. PHP), in whatever DB access method you use, you’ll need to set the connection charset to utf8mb4. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.

  • Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:

    • If you’re using the PDO abstraction layer with PHP ≥ 5.3.6, you can specify charset in the DSN:

       $dbh = new PDO('mysql:charset=utf8mb4');
      
    • If you’re using mysqli, you can call set_charset():

        $mysqli->set_charset('utf8mb4');       // object oriented style
        mysqli_set_charset($link, 'utf8mb4');  // procedural style
      
    • If you’re stuck with plain mysql but happen to be running PHP ≥ 5.2.3, you can call mysql_set_charset.

  • If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: SET NAMES 'utf8mb4'.

  • The same consideration regarding utf8mb4/utf8 applies as above.

  • If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or HTML metadata).

  • In PHP, you can use the default_charset php.ini option, or manually issue the Content-Type MIME header yourself, which is just more work but has the same effect.

  • When encoding the output using json_encode(), add JSON_UNESCAPED_UNICODE as a second parameter.

  • Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP’s mb_check_encoding() does the trick, but you have to use it religiously. There’s really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven’t found a trick to get PHP to do this for you reliably.

    • For HTML before HTML5 only: you want all data sent to you by browsers to be in UTF-8. Unfortunately, if you go by the only way to reliably do this is add the accept-charset attribute to all your <form> tags: <form ... accept-charset="UTF-8">.
    • For HTML before HTML5 only: note that the W3C HTML spec says that clients «should» default to sending forms back to the server in whatever charset the server served, but this is apparently only a recommendation, hence the need for being explicit on every single <form> tag.

Other Code Considerations:

  • Obviously enough, all files you’ll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.

  • You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You’ll probably want to make extensive use of PHP’s mbstring extension.

  • PHP’s built-in string operations are not by default UTF-8 safe. There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent mbstring function.

  • To know what you’re doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from utf8.com for some good resources to learn everything you need to know.

Linux – How to change permissions for a folder and its subfolders/files in one step

The other answers are correct, in that chmod -R 755 will set these permissions to all files and subfolders in the tree. But why on earth would you want to? It might make sense for the directories, but why set the execute bit on all the files?

I suspect what you really want to do is set the directories to 755 and either leave the files alone or set them to 644. For this, you can use the find command. For example:

To change all the directories to 755 (drwxr-xr-x):

find /opt/lampp/htdocs -type d -exec chmod 755 {} \;

To change all the files to 644 (-rw-r--r--):

find /opt/lampp/htdocs -type f -exec chmod 644 {} \;
  • chmod 755 {} specifies the command that will be executed by find for each directory
  • chmod 644 {} specifies the command that will be executed by find for each file
  • {} is replaced by the path
  • ; the semicolon tells find that this is the end of the command it’s supposed to execute
  • \; the semicolon is escaped, otherwise it would be interpreted by the shell instead of find

Next, education about cron

If the computer is not powered on or crond daemon is not running, and the date/time for a command to run has passed, crond will not catchup and run past queries.

crontab particulars, how to formulate a command:

A crontab command is represented by a single line. You cannot use \ to extend a command over multiple lines. The hash (#) sign represents a comment which means anything on that line is ignored by cron. Leading whitespace and blank lines are ignored.

Be VERY careful when using the percent (%) sign in your command. Unless they are escaped \% they are converted into newlines and everything after the first non-escaped % is passed to your command on stdin.

There are two formats for crontab files:

  •  # Example of job definition:
     # .---------------- minute (0 - 59)
     # |  .------------- hour (0 - 23)
     # |  |  .---------- day of month (1 - 31)
     # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
     # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
     # |  |  |  |  |
     # *  *  *  *  *   command to be executed
    
  • System wide /etc/crontab and /etc/cron.d fragments

     # Example of job definition:
     # .---------------- minute (0 - 59)
     # |  .------------- hour (0 - 23)
     # |  |  .---------- day of month (1 - 31)
     # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
     # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
     # |  |  |  |  |
     # *  *  *  *  * user-name  command to be executed
    

The first 5 fields of the line represent the time(s) when the command should be run.
You can use numbers or where applicable day/month names in the time specification.

  • The fields are separated by spaces or tabs.
  • A comma (,) is used to specify a list e.g 1,4,6,8 which means run at 1,4,6,8.
  • Ranges are specified with a dash (-) and may be combined with lists e.g. 1-3,9-12 which means between 1 and 3 then between 9 and 12.
  • The / character can be used to introduce a step e.g. 2/5 which means starting at 2 then every 5 (2,7,12,17,22…). They do not wrap past the end.
  • An asterisk (*) in a field signifies the entire range for that field (e.g. 0-59 for the minute field).
  • Ranges and steps can be combined e.g. */2 signifies starting at the minimum for the relevant field then every 2 e.g. 0 for minutes( 0,2…58), 1 for months (1,3 … 11) etc.

Debugging cron commands

Check the mail!

MAILTO=user@somehost.tld
1 2 * * * /path/to/your/command

Capture the output yourself

You can redirect stdout and stderr to a file. The exact syntax for capturing output may vary depending on what shell cron is using. Here are two examples which save all output to a file at /tmp/mycommand.log:

1 2 * * * /path/to/your/command &>/tmp/mycommand.log
1 2 * * * /path/to/your/command >/tmp/mycommand.log 2>&1

Look at the logs

Cron logs its actions via syslog, which (depending on your setup) often go to /var/log/cron or /var/log/syslog.

If required you can filter the cron statements with e.g.

grep CRON /var/log/syslog 

Now that we’ve gone over the basics of cron, where the files are and how to use them let’s look at some common problems.

Check that cron is running

ps -ef | grep cron | grep -v grep

should get you something like

root    1224   1  0 Nov16 ?    00:00:03 cron
root    2018   1  0 Nov14 ?    00:00:06 crond

If not restart it

/sbin/service cron start
/sbin/service crond start

There may be other methods; use what your distro provides.

cron runs your command in a restricted environment.

What environment variables are available is likely to be very limited. Typically, you’ll only get a few variables defined, such as $LOGNAME, $HOME, and $PATH.

Of particular note is the PATH is restricted to /bin:/usr/bin. The vast majority of «my cron script doesn’t work» problems are caused by this restrictive path. If your command is in a different location you can solve this in a couple of ways:

  1. Provide the full path to your command.

     1 2 * * * /path/to/your/command
    
  2. Provide a suitable PATH in the crontab file

     PATH=/bin:/usr/bin:/path/to/something/else
     1 2 * * * command 
    

If your command requires other environment variables you can define them in the crontab file too.

cron runs your command with cwd == $HOME

The last command in my crontab doesn’t run

Cron generally requires that commands are terminated with a new line. Edit your crontab; go to the end of the line which contains the last command and insert a new line (press enter).

Check the crontab format

I put a file in /etc/cron.{hourly,daily,weekly,monthly} and it doesn’t run

  • Check that the filename doesn’t have an extension see run-parts
  • Ensure the file has execute permissions.
  • Tell the system what to use when executing your script (eg. put #!/bin/sh at top)

Percent signs, again

To emphasise the advice about percent signs, here’s an example of what cron does with them:

# cron entry
* * * * * cat >$HOME/cron.out%foo%bar%baz

will create the ~/cron.out file containing the 3 lines

foo
bar
baz

This is particularly intrusive when using the date command. Be sure to escape the percent signs

* * * * * /path/to/command --day "$(date "+\%Y\%m\%d")"

How to use sudo in cron jobs

crontab -e
sudo crontab -e

This is a community wiki, if you notice anything incorrect with this answer or have additional information then please edit it.


Ответа

Это количество символов в файле по умолчанию. Ubuntu создает «пустой» файл crontab с большим количеством комментариев, показывающих, как его использовать.

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
"/tmp/crontab.vILdXR/crontab" 22L, 888C

Ваш crontab редактор был переключен на ed. Чтобы выйти ed, нажмите Q , а затем Enter . Это выйдет из редактора ed.

Если вы хотите изменить свой crontab редактор обратно на nano, используйте:

sudo select-editor

Это также может быть полезно:

EDITOR=nano crontab -e

ответ дан
12 February 2014 в 23:09

Другие вопросы по тегам:

Похожие вопросы:

Оцените статью
Master Hi-technology
Добавить комментарий