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

user3413723
  • 133
  • 1
  • 8
  • 6
    Since you specify `/bin/date` with an explicit path: Is `PATH` set correctly to contain `hostname`? – DonHolgo Sep 04 '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?](//unix.stackexchange.com/q/29578) – Kusalananda Sep 04 '19 at 15:04
  • 1
    @DonHolgo You are exactly right! I don't know why I didn't think of that! Works perfect once I add the full path. – user3413723 Sep 04 '19 at 15:59
  • 1
    @user3413723 Ok, I've turned that into an answer. – DonHolgo Sep 04 '19 at 18:10

2 Answers2

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
francois P
  • 1,219
  • 11
  • 27
1

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).

DonHolgo
  • 625
  • 1
  • 4
  • 7
  • It would be better to investigate why the root user's PATH is wrong, which indicates a deeper issue with the system. – Kusalananda Mar 08 '23 at 07:00