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?

ironsand
  • 5,205

3 Answers3

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:

Ouki
  • 5,962
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

AdminBee
  • 22,803
-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