一种算术条件和一种非算术条件的逻辑或

Logical OR on one arithmetic and one non-arithmetic condition

我在 Unix/Linux shell 脚本编写和 none 算术和逻辑运算符方面经验不多。从我在文档中看到的,这个符号是一场噩梦!我有一个简单的任务要完成,但我不清楚哪种符号会给我正确的结果,所以我想我会在这里问一下。

我想生成一个新的 Kerberos 票证,如果自上次签发以来已经过去了一定的时间以前的票已过期。我可以分别检查这些,并且 运行 在每种情况下使用相同的代码:

maxIterations=480 # 4 hours, given a 30-second loop
iteration=0
kinit ... [generate the first Kerberos ticket]
while true
do
  sleep 30 # short-duration loop because in the real application
           # I'm also testing other conditions that could arise at any time,
           # not just whether a new ticket should be issued
  iteration=`expr $iteration + 1`
  if [ $iteration -eq $maxIterations ]
  then
    echo "Requesting new Kerberos ticket"
    kinit ...
  fi
  if ! klist -f -s
  then
    echo "Requesting new Kerberos ticket"
    kinit ...
  fi
  # other checks here
done

但是,当然,我不想重复代码,所以我想知道我可以使用什么语法将算术比较和调用返回的状态测试“或”在一起klist -f -s.

对现有代码的较小更改是:

iteration=$((iteration + 1))
if [ "$iteration" -ge "$maxIterations" ] || ! kinit -f -s; then

...但是更好的方法(如果这真的是一个 bash 脚本而不是 sh 脚本)是:

if (( ++iteration >= maxIterations )) || ! kinit -f -s; then

请注意,在算术上下文中使用 ++iteration 意味着您可以去掉上面的 expr 行。