Search code examples
bashwhile-loopunary-operator

Unary Operator with a while loop in bash


I'm trying to get a bash script setup so it'll move files up to a specified size limit(in this case 1GB) from one directory to another. I'm trying to get it to enter the loop but I'm having issues with the while statement. It keeps returning the below output and I'm not sure why. If I try to use "$currentSize" in the while bash says it's expecting an integer comparison. But variables in bash are supposed to be untyped, so I can't cast it to an intiger, right? Any help is appropriated.

Output

54585096

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

Code

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

Solution

  • What you're trying to achieve by:

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

    is to capture the current size of /root/Dropbox in currentSize. That isn't happening. That's because whitespace is significant when setting shell variables, so there's a difference between:

    myVar=foo
    

    and

    myVar= foo
    

    The latter tries to evaluate foo with the environment variable myVar set to nothing.

    Bottom line: currentSize was getting set to nothing, and line 9 became:

    while [ -lt 1048576 ]
    

    and of course, -lt isn't a unary operator which is what the shell is expecting in that situation.

    To achieve your intent, use Bash command substitution:

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