Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
#!/bin/bash

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
add comment

1 Answer

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
target=/etc/pacman.d/mirrorlist
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? –  NixNinja Oct 25 '10 at 20:47
1  
@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
add comment

Your Answer

 
discard

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.