Bash script convert "string" to number

i need to change a string to interger, because i check the size of file (extract with : stat -c%s $filename) with a number, follow the complete script :

#!/bin/bash # Variable that contain path destination file path=/sobstitude # Variable for size size=1000 # Loop for file scan for filename in /test/*; do # Take the size of file filesize=$(stat -c%s $filename) # Check if the file is empty if [ $filesize > $size ] then # Replace file mv $filename $path fi done exit 0; 
1

3 Answers

In bash/sh variables contain strings, there is no strict concept of integers. A string may look like an integer and it's enough.

stat -c%s $filename should return a string that looks like an integer.

In your case the main problem is in the redirection operator > (you probably now have files with names that are numbers in the working directory). This snippet:

 [ $filesize > $size ] 

should be

[ "$filesize" -gt "$size" ] 

And use double quotes around variable substitutions and command substitutions.

No need to "convert" data types. You can use -gt or -lt to compare numbers:

➜ size="$(stat -c%s test.mp4)"; [[ "$size" -gt 4000 ]] && echo "bigger" || echo "smaller" bigger ➜ size="$(stat -c%s test.mp4)"; [[ "$size" -gt 400000 ]] && echo "bigger" || echo "smaller" smaller 

The > is not wrong in principle. You can use arithmetic expressions to perform the comparison.

I've used [[ in place of [ for its extended features.

Note that all variable expansions should be double-quoted. Particularly with $filename and $path, if any of those contain whitespace, your script will fail.

0

Guys i've solved after change this :

if ((filesize > size)) 

Now work, thanks for support

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like