Bash script convert "string" to number
Solution 1
Guys i've solved after change this :
if ((filesize > size))
Now work, thanks for support
Solution 2
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.
Solution 3
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.
lukebaccio
Updated on September 18, 2022Comments
-
lukebaccio over 1 year
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;
-
xenoid over 4 yearsInstead of checking the file size in the script, you can use
find
with-size
to only list files that are in the adequate size bracket, and since you can tell find to execute a command against matching files, your whole script becomesfind /test/ -maxdepth 1 -type f -size +1000c -exec mv {} /sobstitude \;
-