dig_123
dig_123

Reputation: 2358

Script working fine from command line, but not from crontab

My crontab entry as "ins" user is this:

* * * * * /usr/bin/ksh /apps/swbkp/swbkp.sh

The script is:

#! /usr/bin/ksh

. /apps/ins/.profile

cdate=$(date +'%y%m%d')

/apps/omni/bin/swmml -e "backup-node:" >> /apps/swbkp/swerrr1.$cdate

#
if [[ -f /apps/omni/conf/archive.C7M3UAA.500.$cdate ]]
then
   mv -f /apps/omni/conf/archive.C7M3UAA.500.$cdate /apps/swbkp/
elif [[ -f /apps/omni/labeir1/dffile/archive.C7M3UAA.500.$cdate ]]
then
   mv -f /apps/omni/labeir1/dffile/archive.C7M3UAA.500.$cdate /apps/swbkp/
else
   printf "Backup archive File not present to move"
fi >> /apps/swbkp/swerrr1.$cdate
#

Note: /apps/omni/bin/swmml -e "backup-node:" this line simply creates a backup file on my system of type archive.C7M3UA.500.<current date>

2 weird things happening:

  1. the backup file generated is:

    -rw-r--r-- 1 root root 165 Aug 28 21:55 /apps/omni/labeir1/dffile/archive.C7M3UAA.500.130828

When getting moved to /apps/swbkp, the timestamp is 1 min before:

-rw-r--r-- 1 root root  165 Aug 28 21:54 archive.C7M3UAA.500.130828
  1. Nothing is getting redirected to /apps/swbkp/swerrr1.$cdate file

    -rw-r--r-- 1 ins ins 0 Aug 28 21:24 swerrr1.130828

Whereas when I run the script from terminal, everything works perfect, i.e the file has the same timestamp in backup folder as well as moved folder, and outputs are getting logged in the log file as well.

Kindly help

Upvotes: 1

Views: 422

Answers (2)

Ishy
Ishy

Reputation: 11

This may already have been answered, but for anyone looking for help:

You'll need to escape the 'percent' like below when using date/time stamps in crons:

cdate=$(date +'\%y\%m\%d') instead of cdate=$(date +'%y%m%d')

if using this in yaml/ Ansible playbooks, you'll need to double escape or escape the escape like:

$(date +'\\%y\\%m\\%d')

Eventually the cron should look something like

* * * * * script.sh > /tmp/script_$(date +\%y\%m\%d).log 2>&1

Upvotes: 1

Sir Athos
Sir Athos

Reputation: 9867

Take a look at /apps/ins/.profile and the files it executes - such files usually have a conditional that exits the script early if it's not run in a terminal.

For example:

[ -z "$PS1" ] && return

This may change the behavior of your script (or even skip it, if exit is used in place of return). At the very least, you will miss aliases, possible PATH changes, and other things set up in the .profile script, which will affect if and how your main script is run.

Try to comment the line . /apps/ins/.profile in the script above, and see if it still runs in the terminal. If it does, run it like that from crontab and see if it fixes your problem.

Upvotes: 0

Related Questions