【问题标题】:Unary Operator with a while loop in bashbash中带有while循环的一元运算符
【发布时间】:2012-06-20 18:19:03
【问题描述】:

我正在尝试设置一个 bash 脚本,以便它将文件从一个目录移动到指定的大小限制(在本例中为 1GB)到另一个目录。我试图让它进入循环,但我遇到了 while 语句的问题。它不断返回以下输出,我不知道为什么。如果我尝试在 while bash 中使用“$currentSize”表示它期望进行整数比较。但是 bash 中的变量应该是无类型的,所以我不能将它转换为整数,对吧?任何帮助都是适当的。

输出

54585096

1048576
./dbsFill.bsh: line 9: [: -lt: unary operator expected

代码

#!/bin/bash

currentSize= du -s /root/Dropbox | cut -f 1
maxFillSize=1048576
echo $currentSize
echo $maxFillSize

cd /srv/fs/toSort/sortBackup
while [ $currentSize -lt $maxFillSize ]

do
        #fileToMove= ls -1
        #rsync -barv --remove-source-files $fileToMove /root/Dropbox/sortme
#       mv -t /root/Dropbox/sortme $(ls -1 | head -n 1)
        #find . -type f -exec mv -t /root/Dropbox/sortme {} \;
        #currentSize= du -s /root/Dropbox | cut -f 1
#       sleep 5
        echo Were are here
done

【问题讨论】:

    标签: bash while-loop unary-operator


    【解决方案1】:

    你想要达到的目标:

    currentSize= du -s /root/Dropbox | cut -f 1
    

    是在currentSize中捕获/root/Dropbox的当前大小。那没有发生。那是因为在设置 shell 变量时空格很重要,所以有以下区别:

    myVar=foo
    

    myVar= foo
    

    后者尝试在环境变量 myVar 设置为空的情况下评估 foo

    底线:currentSize 被设置为空,第 9 行变为:

    while [ -lt 1048576 ]
    

    当然,-lt 不是 shell 在这种情况下所期望的一元运算符。

    要实现您的意图,请使用Bash command substitution

    currentSize=$( du -s /root/Dropbox | cut -f 1 )
    

    【讨论】:

    • +1 相同的答案,但最好的解释是什么需要改变和为什么。
    • 啊,非常感谢。在设置变量时,我没有意识到 whitepsace 很重要,这很有意义。并解释对命令替换的引用解决了该脚本的下一个问题。 :)
    【解决方案2】:
    currentSize= du -s /root/Dropbox | cut -f 1
    

    这并不像你认为的那样。

    currentSize=$(du -s /root/Dropbox | cut -f 1)
    

    【讨论】:

    • ./dbsFill.bsh: line 3: 37188888: command not found 1048576 ./dbsFill.bsh: line 9: [: -lt: unary operator expected 是更改该命令的结果。我同意这行可能是问题所在,但我不确定您的更改是做什么的。
    【解决方案3】:

    您需要将“currentSize ...”行重写为

    currentSize=$(du-s /root/Dropbox | cut -f 1)
    

    您的代码将 currentSize 的值留空。

    您可以发现此类问题(稍加练习),但使用 shell 调试功能

    set -vx
    

    在脚本的顶部,或者如果您认为自己很确定哪里有问题,请将您的可疑代码括起来,例如:

    set -vx
    myProblematicCode
    set +vx
    

    set +vx 关闭调试模式。)

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 2022-06-27
      • 1970-01-01
      • 2022-11-12
      相关资源
      最近更新 更多