Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have to following cron script that runs daily. As you should be able to see from the code, it outputs the results from reflector to /etc/pacman.d/mirrorlist.

$ cat /etc/cron.daily/update-mirrorlist

reflector -l 5 -r -o /etc/pacman.d/mirrorlist

Sometimes, reflector outputs a empty file and thus a invalid mirrorlist is created.

How can I modify the script above to only write to /etc/pacman.d/mirrorlist IF there is valid output from relfector?

share|improve this question
up vote 4 down vote accepted

It's a good idea to first accumulate the data, then move it into place. That way the target file will always be valid, even while the data accumulator program is running.

set -e
reflector -l 5 -r -o "$target.tmp"
mv -f -- "$target.tmp" "$target"

If reflector does not properly report errors by returning a nonzero status, add your own validation test before the mv command, for example test -s "$target.tmp" to test that the file is not empty.

If you want to keep a backup of the old version, add ln -f -- "$target" "$target.old" || true before the mv command.

share|improve this answer
what does set -e do? – Stefan Oct 25 '10 at 20:47
@Stefan: set -e tells the shell to stop the script as soon as a command returns a nonzero status (conventionally indicating a failure). (If a command is allowed to fail, such as ln in my answer, adding || true after it ensures that that command as a whole always succeeds and won't terminate the script.) – Gilles Oct 25 '10 at 21:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.