Bash脚本嵌套循环错误

时间:2012-02-02 18:56:28

标签: bash

代码:

#! /bin/bash
while [ 1 -eq 1 ]
do
while [ $(cat ~/Genel/$(ls -t1 ~/Genel | head -n1)) != $(cat ~/Genel/$(ls -t1 ~/Genel | head -n1)) ]
$(cat ~/Genel/$(ls -t1 ~/Genel | head -n1)) > /tmp/cmdb;obexftp -b $1 -B 6 -p /tmp/cmdb
done
done 

此代码给我这个错误:

  

btcmdserver:6:语法错误:“完成”意外(期待“做”)

2 个答案:

答案 0 :(得分:5)

你的第二个while循环缺少一个do关键字。

看起来你没有关闭你的while条件([没有匹配]),并且你的循环没有正文。

答案 1 :(得分:1)

您无法比较这样的整个文件。无论如何,您似乎将文件与自身进行比较。

#!/bin/bash
while true
do
  newest=~/Gene1/$(ls -t1 ~/Gene1 | head -n 1)
  while ! cmp "$newest" "$newest" # huh? you are comparing a file to itself
  do
    # huh? do you mean this:
    cat "$newest" > /tmp/cmdb
    obexftp -b $1 -B 6 -p /tmp/cmdb
  done
done

这有最令人不安的语法错误和反模式修复,但实际上保证不会做任何有用的事情。希望它仍然足以让你更接近你的目标。 (在问题中说明它也可能有所帮助。)

编辑:如果您每次在正在观看的目录中出现新文件时尝试复制最新文件,请尝试此操作。还有竞争条件;如果您在复制时出现多个新文件,您将会错过除其中一个之外的所有文件。

#!/bin/sh
genedir=$HOME/Gene1
previous=randomvalue_wehavenobananas
while true; do
  newest=$(ls -t1 "$genedir" | head -n 1)
  case $newest in
    $previous) ;;   # perhaps you should add a sleep here
    *) obexftp -b $1 -B 6 -p "$genedir"/"$newest"
       previous="$newest" ;;
  esac
done

(我将shebang更改为/ bin / sh主要是为了表明这不再包含任何bashisms。主要更改是使用${HOME}而不是~。)

更强大的方法是查找自上次复制以来出现的所有文件,并将其复制。然后你可以稍微不那么积极地运行它(比如,每5分钟一次,而不是你在这里的自旋锁,在迭代之间根本没有sleep)。您可以使用watch目录中的sentinel文件来跟踪上次复制某些文件的时间,或者只是在for输出上运行ls -t1循环,直到您看到之前看到的文件为止。 (注意关于解析ls输出时缺乏健壮性的评论。)

相关问题