5

I created a simple script to check environment variable to run from crontab.

#!bin/bash
echo $USER > cron.txt

saves as script.sh in home directory.

Crontab setting: */1 * * * * ./script.sh

If I run it manually, it works but not from crontab.Output should shows my username in cron.txt file but it doesn't.

2
  • In what specific way does it not work when run (how?) from crontab (which?). – Kusalananda Feb 9 '17 at 11:27
  • @Kusalananda crontab setting: */1 * * * * ./script.sh and output should shows my username in cron.txt file but it doesn't. – d a i s y Feb 9 '17 at 11:36
5

When the cron execute your job, it does so in an environment that is not the same as your current shell environment.

This means, for example, that ./script.sh may not be found.

There are two solutions:

*/1 * * * * ( cd $HOME/mydir && ./script.sh )

or

*/1 * * * * $HOME/mydir/script.sh

I.e., specify exactly where the script may be found.

The first alternative may be preferable if you don't use absolute pathnames for the output file within the script.

If you go with the second option, modify your script so that you know where the output file goes:

#!/bin/bash
echo "$USER" >"$HOME/mydir/cron.txt"

or

#!/bin/bash
( cd "$HOME/mydir" && echo "$USER" >cron.txt )

Notice that the #! line has to contain the correct absolute path to bash (your's was a relative path).

It should also be noted that cron on some Unices (Linux) do not set USER to the username of the user running the cron job. On these systems, use $LOGNAME instead, or set USER to $LOGNAME when invoking the script:

*/1 * * * * env USER=$LOGNAME $HOME/mydir/script.sh
10
  • script.sh is in home directory – d a i s y Feb 9 '17 at 11:40
  • @daisy In that case, just delete mydir from my examples. And also make sure it's executable and has the correct absolute path to bash on the #!-line (see answer). – Kusalananda Feb 9 '17 at 11:43
  • path is also correct and permission has also given – d a i s y Feb 9 '17 at 11:47
  • @daisy If the #! is now correct (#!/bin/bash) and the script is executable, then it should work. I've tested it on my own machine. – Kusalananda Feb 9 '17 at 11:51
  • okay. Let me do all steps again. – d a i s y Feb 9 '17 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.