سؤال

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
هل كانت مفيدة؟

المحلول

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 )

نصائح أخرى

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

This does not do what you think it does.

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

you need to re-write your 'currentSize ...' line as

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

Your code left the value of currentSize empty.

You can spot such problems (with a little practice), but using the shell debugging feature

set -vx

at the top of your script, or if you think you're pretty sure where there's a problem, surround your suspiocus code like:

set -vx
myProblematicCode
set +vx

(the set +vx turns off debug mode.)

I hope this helps.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top