bash - How to change the pseudocode into real code? -
there 4 time servers, want synchronize local time ntp time server.
arr=(s2c.time.edu.cn s2d.time.edu.cn s2e.time.edu.cn s2f.time.edu.cn) var in ${arr[@]}; # 2 lines pseudocode here if `ntpdate $var` secceed ,exit loop if none of ntp time server can used,echo "failure" done
how change pseudocode real code?
fix flaw codes:
arr=(s2c.time.edu.cn s2d.time.edu.cn s2e.time.edu.cn s2f.time.edu.cn) switch = 0 var in ${arr[@]}; # 1 lines pseudocode here if `ntpdate $var` secceed ,assign switch = 1 ,exit loop done if["$switch" = "0"] ;then echo "synchronize local time ntpdate failure" fi
how change if
ntpdate $varsecceed ,assign switch = 1 ,exit loop
real bash script?
your proposed algorithm has obvious flaw:
- loop on servers
- if ntp server can used -> exit loop
- if none of ntp server can used -> echo failure
the flaw last step, "if none of ntp servers ...". doesn't make sense have inside loop, because cannot judge until finished loop.
consider instead:
- create function
- loop on servers
- if ntp server can used -> return function success
- if none of ntp server can used -> return function failure
implementation:
use_any_ntp_server() { server; ntpdate $server && return done return 1 } if ! use_any_server s2c.time.edu.cn s2d.time.edu.cn s2e.time.edu.cn s2f.time.edu.cn; echo failure: none of ntp servers used fi
Comments
Post a Comment