1

I have a simple backup script with this line to come up with a name for the backup:

backup=$(/bin/date +'%Y-%m-%d_%H:%M_%S')_$(hostname).gz

It works great when I run it under the root user. Unfortunately when I set it to run as a cronjob, the $(hostname) part is always empty and I don't get the hostname. Why isn't it working, and how can I get the hostname in a cron job?

I'm running ubuntu 18.04

4
  • 5
    Since you specify /bin/date with an explicit path: Is PATH set correctly to contain hostname?
    – DonHolgo
    Sep 4 '19 at 14:40
  • 2
    Is that a line from the actual cron schedule? % is special in crontabs, and must be escaped. See e.g. How can I execute `date` inside of a cron tab job?
    – Kusalananda
    Sep 4 '19 at 15:04
  • @DonHolgo You are exactly right! I don't know why I didn't think of that! Works perfect once I add the full path. Sep 4 '19 at 15:59
  • @user3413723 Ok, I've turned that into an answer.
    – DonHolgo
    Sep 4 '19 at 18:10
2

Crontab has its own variables lists for path etc...you might use them or run from crontab a bash script instead of a shell-like commad.

This is how to use crontab

VARIABLE=value
PATH=/bin:/path/to/doanything
0 0 * * * doanything.sh $VARIABLE
0

hostname doesn't seem to be in the PATH in your script. Either put /bin/hostname there, like you did for date, or set PATH to include /bin (inside the script or in the crontab).

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.