1

I tested the following with no luck. Any other ideas?

#cron test, I would like to generate a stderr logfile name based on $0, but $0 value is "/bin/bash"
#why do I want this? Because some program names are quite long, and for standardization
04 10 * * * ~/bin/cron-test >> /tmp/blah 2>>~/.cronlogs/$(basename $0)  # $0 is "/bin/bash"
05 10 * * * ~/bin/cron-test >> /tmp/blah 2>>~/.cronlogs/$(basename $1)  # $1 is empty?
06 10 * * * ~/bin/cron-test >> /tmp/blah 2>>~/.cronlogs/$(basename $2)  # $2 is empty?
  • 1
    What is this being run from? What do you expect $0, $1, and $2 to be? – Jesse_b Feb 21 at 18:40
  • 1
    Better change your script ~/bin/cron-test to redirect its output. There you could use $0 to get the script name. – Bodo Feb 21 at 18:42
  • Jesse_b, it is supposed to be a cron job. Looking at $1 and $2 is an attempt to work around the fact that $0 does not have the desired value "~/bin/cron-test". I was hoping that $1 would be "-c" and $2 would be "~/bin/cron-test", for example. – reikred Feb 21 at 19:21
  • Bodo, I do not wish to hardcode output filenames into the script, I want to use stdout and stderr for testing and for non-cron use of the same scripts. – reikred Feb 21 at 19:23
1

You could write a wrapper script to send the output to some particular place.

$ cat logwrap.sh
#!/bin/bash
logname=$(basename -- "$1").log
exec "$@" 2>> "~/.cronlogs/$logname"

Now, logwrap.sh id some command would run some command and send its output to /work/logs/some.log, so this would have its output sent to /work/logs/cron-test.log:

04 10 * * * /path/to/logwrap.sh ~/bin/cron-test 
  • That's a good idea, for my particular purposes I would "exec 2> ~/.cronlogs/$logname";and let stdout pass through normally. – reikred Feb 21 at 21:25
  • I think the "$@" should be on the "exec" line, took the liberty to edit it. – reikred Feb 21 at 22:29
  • @reikred, yeah, it could be there, too, it seems to work. I don't think the difference matters much in this case. exec without a command sets the redirections for the rest of the script, so they're applied command that gets run by "$@". With exec "$@", the shell gets replaced by the command in $@, and again, of course the redirections apply to that since they're right there in the same command. – ilkkachu Feb 21 at 22:59
  • @reikred, The reason I had them separate was that originally, I had eval "$@" as the last command. Using eval would allow to pass a full shell command line to the script, with something like pipelines or such included. But it also invites extra quoting and your commands didn't need it anyway, so I left it out. – ilkkachu Feb 21 at 23:00

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.