4

System: Xubuntu 13.10

When I have this crontab entry

*/5 * * * * cat /home/dbk/.bash_aliases &> /home/dbk/Desktop/junk

junk has a byte size of 0.

Running

$ cat /home/dbk/.bash_aliases &> /home/dbk/Desktop/junk

gives a file with a proper size and content.

1 Answer 1

5

The probem because cron run task with sh. &> is a shortcut to redirect both stderr and stdout to the same file in bash, not in sh.

In sh, your command:

cat /home/dbk/.bash_aliases &> /home/dbk/Desktop/junk

meaning run two commands separately:

  • Run cat /home/dbk/.bash_aliases in background

    cat /home/dbk/.bash_aliases &

  • Truncate the junk file.

    > /home/dbk/Desktop/junk

So you should use bash to run your command in crontab:

*/5 * * * * bash -c "cat /home/dbk/.bash_aliases &> /home/dbk/Desktop/junk"

or using more portable way:

*/5 * * * * cat /home/dbk/.bash_aliases > /home/dbk/Desktop/junk 2>&1
6
  • Its true that >&1 2>&1 is the analog to &>, but i think that in the portable cat case it is useless - if cat errors it should quit and write nothing anyway so >file is enough.
    – mikeserv
    Commented Mar 23, 2014 at 20:44
  • @mikeserv: Yes, you can see man bash, REDIRECTION section for more details. No, if cat produce any errors, these errors will be saved to file.
    – cuonglm
    Commented Mar 24, 2014 at 1:27
  • What kind of errors will be saved to the file?
    – mikeserv
    Commented Mar 24, 2014 at 1:28
  • @mikeserv: any errors produce by cat, i.e you cat a file which doesn't exist.
    – cuonglm
    Commented Mar 24, 2014 at 1:31
  • Much better than that test -e $file && cat $_ >$tgt
    – mikeserv
    Commented Mar 24, 2014 at 1:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .