10

I write a script and set it as a cron job. But due to a difference of environment variables it doesn't work as it should be.

In that case I change a little bit with crontab -e and set a cron job time closest minute, and wait next minute to come to show the result. I feel this is a totally absurd approach, but I don't know better way to do it.

If there is a way to run a script as if it is called inside cron job, I'm going to use it.

Does anyone know how to do it?

5

3 Answers 3

5

Here is how to do the other way around: forcing cron execution to use your login environment:

bash -lc "your_command"

From the bash manual:

-c string     If the -c option is present, then commands are read from string.
              If there are arguments after the string, they are assigned to the
               positional parameters, starting with $0.
-l            Make bash act as if it had been invoked as a login shell
               (see INVOCATION below).

INVOCATION (a bit stripped):

When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

To known more:

5
  • Cron does not invoke the shell as a login shell when launching commands.
    – phemmer
    Mar 26, 2014 at 1:24
  • That's why forcing it with bash -l option.
    – Ouki
    Mar 26, 2014 at 1:43
  • Oh, I misunderstood what you were saying. While this works, I wouldn't consider it a very elegant solution :-/
    – phemmer
    Mar 26, 2014 at 1:46
  • 1
    Sure. The elegant thing would be to tune whatever environment set for cron ...
    – Ouki
    Mar 26, 2014 at 1:48
  • Wouldn't --norc be closer to what cron runs?
    – terdon
    Mar 26, 2014 at 2:58
2

Another way would be:

/usr/bin/env --ignore-environment your command

From the manpage of env:

-i, --ignore-environment

start with an empty environment

-1

A better way is to use at.

Here are some examples

 echo $PWD/script.sh | at now

or

 echo "reboot" | at 5:00

or

 echo "mail -s test user@host" | at now + 1 hour

Here are some date/time Examples

4
  • I don't see the point here to play with at
    – Ouki
    Mar 26, 2014 at 1:45
  • @Ouki take a look at /var/spool/cron/
    – user55518
    Mar 26, 2014 at 2:21
  • and it's POSIX also
    – user55518
    Mar 26, 2014 at 21:18
  • at retains the working directory and environment at invocation, so it does not run as if from cron. Apr 8, 2020 at 17:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .